gpt4 book ai didi

android - LocalBroadcastManager 不工作

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

我正在尝试从服务向 Activity 发送消息,但由于某种原因它无法正常工作。

Activity

 @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_barcode);
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("custom-event-name"));


private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
Boolean state = intent.getBooleanExtra("state",false);
if(state){
Toast.makeText(getApplicationContext(),"Данные успешно отправлены",Toast.LENGTH_SHORT).show();
}
}
};

@Override
protected void onDestroy() {
// Unregister since the activity is about to be closed.
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}

服务

   private void sendMessage(boolean state) {
Log.d("sender", "Broadcasting message");
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("state", state);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}

显示 Log.d “广播消息”,然后什么也没有发生

问题已解决

在安卓 list 中

<service
android:name=".service.TerminalService"
android:process=":update_service" >
</service>

似乎在指定 android:process 时,localbroadcastmanager 不工作。我刚刚删除了 android:process 行并且它起作用了

最佳答案

您的代码没有问题。仅更新您的接收方法 else 子句

  private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
Boolean state = intent.getBooleanExtra("state",false);
if(state){
Toast.makeText(getApplicationContext(),"Данные успешно отправлены",Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplicationContext(),"else message ",Toast.LENGTH_SHORT).show();

}
}
};

关于android - LocalBroadcastManager 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28691042/

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