遵循本教程:http://www.vogella.de/articles/AndroidServices/article.html#receiver我创建了自己的项目。清单:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="alex.broadcast.sample"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="13" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<receiver android:name="MyPhoneReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"></action>
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
</application>
</manifest>
代码:
public class MyPhoneReceiver extends BroadcastReceiver {
final String logTag = "BroadcastReceiverSample";
@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
String state = extras.getString(TelephonyManager.EXTRA_STATE);
Log.i(logTag, "Call state: " + state);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
String phoneNumber = extras.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
Log.i(logTag, "Phone number: " + phoneNumber);
}
}
}
}
在Android模拟器上运行此示例,我看到它已成功安装。但是,永远不会调用onReceive函数。我使用以下方式拨打来电:
telnet localhost 5554
gsm call 12345678
模拟器显示来电,但未调用onReceive。
答案 0 :(得分:6)
不应该是:
<receiver android:name=".MyPhoneReceiver">
^ note the dot
此外,权限的位置是错误的,应该是<manifest>
而不是<Application>
的孩子。
答案 1 :(得分:1)
在Android 6上不要忘记允许许可:
onCreate(){
if (
ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
&&
ActivityCompat.checkSelfPermission(this, Manifest.permission.PROCESS_OUTGOING_CALLS) != PackageManager.PERMISSION_GRANTED
)
{
requestPermission();
}else {
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.PHONE_STATE");
filter.addAction("android.intent.action.NEW_OUTGOING_CALL");
registerReceiver(receiver, filter);
}
}
private void requestPermission() {
final List<String> permissionsList = new ArrayList<String>();
permissionsList.add(Manifest.permission.READ_PHONE_STATE);
permissionsList.add(Manifest.permission.PROCESS_OUTGOING_CALLS);
ActivityCompat.requestPermissions(this,permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS:{
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.PHONE_STATE");
filter.addAction("android.intent.action.NEW_OUTGOING_CALL");
registerReceiver(receiver, filter);
}
}
}