1

我有一个由外部应用程序触发的 BroadcastReceiver,它的 OnReceive 方法被成功触发。但我想从那个 OnReceive 向我的应用程序中正在运行的服务发送另一个 LocalBroadcast,问题是 LocalBroadcastManager 的 SendBroadcast 方法返回 false 并且服务中的接收器没有被触发。android 网站中没有关于该布尔值的文档。我google了一下,发现这意味着没有注册的接收者。但我确定我已经在正在运行的服务中成功注册了意图,并且我已经将其作为前台服务以确保它正在运行。

另一个问题,这是从 BroadcastReceiver 与正在运行的服务进行通信的最佳方式吗?

这是代码:

我的服务.java

public class MyService extends Service {

private final IBinder mBinder = new OneSheeldBinder();

public static final String PLUGIN_MESSAGE = "PLUGIN_MESSAGE";
@Override
public void onCreate() {

    LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
              new IntentFilter(MyService.PLUGIN_MESSAGE));
            showNotification();
    super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    return START_REDELIVER_INTENT;
}

@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

@Override
public void onDestroy() {
    hideNotifcation();
    LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
    super.onDestroy();
}

private void showNotification(){
    Notification.Builder build=new Notification.Builder(this);
    build.setSmallIcon(R.drawable.ic_launcher);
    build.setContentText("The service is running!");
    build.setContentTitle("The service is running!");
    build.setTicker("The service is running!");
    build.setWhen(System.currentTimeMillis());

    Notification notification=build.build();
    startForeground(1, notification);
}

private void hideNotifcation(){
    stopForeground(true);
}

 public class OneSheeldBinder extends Binder {
     public MyService getService() {
            return MyService.this;
        }

    }

 private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
     @Override
     public void onReceive(Context context, Intent intent) {
          Log.d("LocalBroadcast","Received!");
       }
     };

}

FireReceiver.java

public final class FireReceiver extends BroadcastReceiver
{

@Override
public void onReceive(final Context context, final Intent intent)
{
        Intent intent = new Intent();
        boolean test=LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
        Log.d("LocalBroadcast","Intent Fired!:"+test);//test is always false!
}


}

清单文件中的接收器和服务块

<receiver
        android:name=".FireReceiver"
        android:exported="true"
        android:process=":background"
        tools:ignore="ExportedReceiver" >
        <intent-filter>
            <action android:name="com.twofortyfouram.locale.intent.action.FIRE_SETTING" />
        </intent-filter>
</receiver>

    <service
        android:name=.MyService"
        android:exported="false" />
4

1 回答 1

3

LocalBroadcastManager是本地的一个进程。无论出于何种原因,您选择使用两个不同的进程,因此LocalBroadcastManager将无法正常工作。

简单的解决方案是android:process=":background"从您的<receiver>元素中删除,因为它是浪费的、不必要的,并且会干扰您对LocalBroadcastManager.

于 2013-09-20T12:49:01.833 回答