LocalBroadcastManager不会将消息从服​​务发送到活动

时间:2017-09-19 14:02:24

标签: android service broadcastreceiver

我正在尝试连接我的服务和活动,尝试了不同的方法,但没有任何方法可以帮助我。

当应用程序启动时,我在SplashActivity中启动Servise。然后,Service会在后台完成一些工作,当这项工作完成后,stopself()方法正在服务onStartCommand()中进行调用。

还有另一项活动,应该是这项背景工作的结果。问题是,只有在工作完成且服务停止时才需要将数据加载到Recyclerview中。所以我尝试使用LocalBroadcastManager并在stopself()方法之前向活动发送消息。

问题是,活动没有从服务获得任何消息。这是我的代码,它来自stackoverflow上的这个答案 - https://stackoverflow.com/a/8875292/7478869

服务:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    helper = ItemDatabaseHelper.getInstance(this);
    preferences = getSharedPreferences(PREFERENCES, MODE_MULTI_PROCESS);
    editor = preferences.edit();
    helper.clearTable(Contacts_Contract.CONTACT_TABLE_NAME);
    Set<ContactItem> setC = getContactList();
    for(ContactItem item: setC){
        helper.insertContacts(item);
    }
    editor.putBoolean(IS_CONTACTS_IMPORTED, true);
    editor.apply();


    Intent intent2 = new Intent("myevent");
    // You can also include some extra data.
    intent2.putExtra("message", "This is my message!");
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent2);

    Log.d(TAG, "onStartCommand: stopping service");
    stopSelf();
    return START_STICKY;
}

的活动:

    @Override
protected void onCreate(Bundle savedInstanceState) {
    Log.d(TAG, "onCreate: starts");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_contacts);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Register to receive messages.
    // We are registering an observer (mMessageReceiver) to receive Intents
    // with actions named "custom-event-name".
    LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
            new IntentFilter("myevent"));


}

// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Get extra data included in the Intent
        String message = intent.getStringExtra("message");
        Log.e("receiver", "Got message: " + message);
        Toast.makeText(context, "Import completed", Toast.LENGTH_SHORT).show();
    }
};

1 个答案:

答案 0 :(得分:1)

从战术上讲,这不起作用的原因是LocalBroadcastManager是进程本地的,而且你有两个进程。

从战略上讲,将此代码放在一个单独的过程中是不必要和危险的。例如,您依赖于MODE_MULTI_PROCESShas been deprecated for over two years并且从一开始就没有特别好用。