我在BroadcsastReceiver(Action_headset_plug)中声明了一个AndroidManifest.xml,并定义了一个BroadcastHandler.class实现BroadcsastReceiver。我在设备上运行apk接收器不开火。但是,当我在活动中使用registerReceiver()时,它是正确工作的。我是不是错过了AndroidManifest.xml里的什么东西?
这是AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="irdc.Earphone_test"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="9" />
<uses-permission android:name="android.permission.ACTION_HEADSET_PLUG"></uses-permission>
<application android:icon="@drawable/icon" android:label="@string/app_name">
<receiver android:enabled="true" android:name="BroadcastHandler">
<intent-filter>
<action android:name="android.intent.ACTION_HEADSET_PLUG"></action>
</intent-filter>
</receiver>
<activity android:name=".Earphone_testActivity"
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>
</manifest>这是接收器的代码
public class BroadcastHandler extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)){
String mes;
int state = intent.getIntExtra("state", 4);
if(state == 0){
mes ="out";
}else if(state == 1){
mes ="in";
}else {
mes ="others";
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Headset broadcast");
builder.setMessage(mes);
builder.setPositiveButton("Okey-dokey", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
}
}发布于 2012-02-15 14:10:21
若要收听耳机更改,广播接收器不能在清单中声明,必须动态注册。并不是所有接收者都在清单中声明时工作,这是一个需要以编程方式注册它的示例。
例如,您可以在活动的onResume方法或服务的onCreate方法中调用它:
headsetReceiver = new BroadcastHandler();
registerReceiver(headsetReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));然后,在活动的onPause方法或服务的onDestroy方法中,您需要注销接收方:
unregisterReceiver(headsetReceiver);发布于 2011-09-20 07:13:57
清单条目中的名称是错误的。使用完整的包名,如果希望将其隐式地追加到应用程序的包名中,则使用它的句号:
<receiver android:enabled="true" android:name=".BroadcastHandler">发布于 2011-09-20 07:20:33
大多数接收器示例不启动AlertDialog,而是在状态栏中启动Toast、消息或创建通知。我确信您无法启动一个活动,因为"content“对象停止存在,但如果您可以构建一个AlertDialog,则不会。(广播记录)
因此,您可以尝试在您的接收器一份演讲会的消息,以确保它的工作。
通知示例:sms-t295.html
https://stackoverflow.com/questions/7481083
复制相似问题