我试图让应用程序读取电话状态,当手机状态更改为显示Toast与当前状态.但是当我启动它,应用程序意外停止.
我的课 :
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.PhonestateListener;
import android.telephony.TelephonyManager;
import android.widget.TextView;
public class TelephonyDemo extends Activity {
TextView textout;
TelephonyManager telephonyManager;
PhonestateListener listener;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the UI
textout = (TextView) findViewById(R.id.textout);
// Get the telephony manager
telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
// Create a new PhonestateListener
listener = new PhonestateListener() {
@Override
public void onCallStateChanged(int state,String incomingNumber) {
String stateString = "N/A";
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
stateString = "Idle";
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
stateString = "Off Hook";
break;
case TelephonyManager.CALL_STATE_RINGING:
stateString = "Ringing";
break;
}
textout.append(String.format("\nonCallStateChanged: %s",stateString));
}
};
// Register the listener with the telephony manager
telephonyManager.listen(listener,PhonestateListener.LISTEN_CALL_STATE);
}
}
我的清单是:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.marakana"
android:versionCode="1"
android:versionName="1.0" >
<application
android:icon="@drawable/icon"
android:label="@string/app_name"
android:theme="@android:style/Theme.Light" >
<activity
android:name=".TelephonyDemo"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="7" />
</manifest>
我的布局是:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Telephony Demo"
android:textSize="22sp" />
<TextView
android:id="@+id/textout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Output" >
</TextView>
</LinearLayout>
解决方法
我没有看到< uses-permission android:name =“android.permission.READ_PHONE_STATE”/>在你的清单文件.
您的应用程序需要能够读取该状态.