BroadcastReceiver在Android上没有按预期工作

大鹏一日同风起,扶摇直上九万里。这篇文章主要讲述BroadcastReceiver在Android上没有按预期工作相关的知识,希望能为你提供帮助。
我知道这已被问过很多次,但我无法让这个工作。我查看了android文档和其他来源。我得到了这个活动,里面有一个广播接收器变量,并在构造函数中启动一个服务:

private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(getApplicationContext(), "Received", Toast.LENGTH_SHORT).show(); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_compass); Intent mIntent = new Intent(this, GPSTracker.class); startService(mIntent); }@Override public void onResume() { super.onResume(); registerReceiver(mReceiver, new IntentFilter()); }@Override protected void onStop() { unregisterReceiver(mReceiver); super.onStop(); }

我把服务放在清单中,我确信它能正常工作。任何帮助将不胜感激。
广播接收器应该定期从服务中接收2个浮点数。
< ?xml version="1.0" encoding="utf-8"?> < manifest xmlns:android="http://schemas.android.com/apk/res/android" package="jemboy.compass" > < uses-permission android:name="android.permission.INTERNET" /> < uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> < application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > < service android:name=".GPSTracker"> < /service> < activity android:name=".MainActivity" android:label="@string/app_name" > < /activity> < activity android:name=".CompassActivity"> < intent-filter> < action android:name="android.intent.action.MAIN" /> < category android:name="android.intent.category.LAUNCHER" /> < /intent-filter> < /activity> < activity android:name=".OtherActivity"> < /activity> < /application>


答案在活动中
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(UPDATE_PLAYER)) { updateMediaPlayerToggle(); } else if (intent.getAction().equals(BUFFERING)) { showMediaPlayerBuffering(); } } }; private void registerBroadcastReceiver() { LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(this); IntentFilter updateIntentFilter = new IntentFilter(); updateIntentFilter.addAction(UPDATE_PLAYER); updateIntentFilter.addAction(BUFFERING); broadcastManager.registerReceiver(broadcastReceiver, updateIntentFilter); }

在服务中。
private void sendUpdatePlayerIntent() { Log.d(TAG, "updatePlayerIntent"); Intent updatePlayerIntent = new Intent(MainActivity.UPDATE_PLAYER); LocalBroadcastManager.getInstance(this).sendBroadcast(updatePlayerIntent); }

【BroadcastReceiver在Android上没有按预期工作】来自媒体播放器服务的示例。

    推荐阅读