gpt4 book ai didi

android - LocalBroadcastManager 不会将消息从服​​务发送到 Activity

转载 作者:行者123 更新时间:2023-11-30 00:20:53 30 4
gpt4 key购买 nike

我正在尝试连接我的服务和 Activity ,尝试了不同的方法,但没有任何效果。

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

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

问题是, Activity 没有从服务获得任何消息。这是我的代码,来自 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;
}

Activity :

    @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();
}
};

最佳答案

从策略上讲,这不起作用的原因是 LocalBroadcastManager 是本地进程,而您有两个进程。

从战略上讲,将这段代码放在一个单独的进程中是不必要的,也是危险的。例如,您依赖于 MODE_MULTI_PROCESShas been deprecated for over two years并且从来没有特别好地工作过。

关于android - LocalBroadcastManager 不会将消息从服​​务发送到 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46302542/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com