我一直在尝试使用 LocalBroadcastManager,但它似乎不起作用。基本上我希望我的 intentService 在运行时广播一个意图。然后,我希望我的活动在用户积极使用活动时接收广播。
我尝试按照此处的说明进行操作: 如何使用 LocalBroadcastManager?
但由于某种原因它不起作用。我没有得到任何被调用的接收者的日志条目。
这是我的代码的相关部分:
public class MainActivity extends Activity {
// Debug log tag
private static final String tag = "PhoneControlMainActivity";
// Broadcast receiver
PhoneControlBroadcastReceiver receiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
// Register the receiver with the local broadcast manager
receiver = new PhoneControlBroadcastReceiver();
LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter(PhoneControlBroadcastReceiver.SERVICE_OUTPUT));
// Start IntentService
try {
serviceName = startService(new Intent(this, PhoneControlIntentService.class));
}
catch(SecurityException e)
{
Log.d(tag,"SecurityException occured when starting IntentService: "+ e.getMessage());
return;
}
if(serviceName != null) {
Log.d(tag,"serviceName NOT NULL");
}
else {
Log.d(tag,"serviceName NULL");
}
}
}
public class PhoneControlIntentService extends IntentService {
public PhoneControlIntentService() {
super("PhoneControlIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Intent msgIntent = new Intent(PhoneControlBroadcastReceiver.SERVICE_OUTPUT);
msgIntent.putExtra("message", "This is my message!");
LocalBroadcastManager.getInstance(this).sendBroadcast(msgIntent);
}
}
public class PhoneControlBroadcastReceiver extends BroadcastReceiver{
// Action
public static final String SERVICE_OUTPUT = "com.axr0284.phonecontrol.SERVICE_OUTPUT";
@Override
public void onReceive(Context context, Intent intent) {
Log.d(tag,"onReceive called");
}
}
任何帮助将不胜感激?谢谢阿米什