我的LocalBroadcastManager回调函数选择'接收消息。有人可以告诉我为什么吗?
我尝试在我的三星Galaxy S3 mini(4.1.2 -Jelly Bean,API 16)上进行此操作。
SenderClass:
public static final String BROADCAST = "com.android.SOME_BROADCAST";
private Context context;
public SenderClass(Context context) {
this.context = context;
//...
Intent intent = new Intent(BROADCAST);
//intent.putExtra(EXTRA_SOMEEXTRA, "some extra");
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
//just to keep it simple i do it here
}
MainActivity
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive"); //this is never called!
}
};
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume()");
LocalBroadcastManager.getInstance(this).registerReceiver(
broadcastReceiver,
new IntentFilter(SenderClass.BROADCAST)
);
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause()");
LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver);
}
编辑:这里是清单
清单
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android....">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".Activities.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".Services.MyService"
android:enabled="true"
android:exported="false"></service>
</application>
</manifest>
答案 0 :(得分:-1)
尝试此步骤: - 在onCreate中注册您的广播,并在onDestroy of Activity中取消注册广播。
谢谢, 它可能对你有所帮助。