我一直在嘗試使用LocalBroadcastManager,但它似乎不工作。基本上我希望我的intentService在運行時廣播一個intent。 然後,我希望我的活動在用戶正在使用該活動時接收廣播。intentService使用LocalBroadcastManager的活動
我試圖在這裏按照指示: how to use 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");
}
}
任何幫助將高度讚賞? 感謝 阿米什