我正在尝试将sendMessage从服务发送到活动,但由于某种原因它无法正常工作。
活动
@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“广播消息”,然后没有任何反应
问题已解决
在android清单
中<service
android:name=".service.TerminalService"
android:process=":update_service" >
</service>
似乎当指定android:process时,localbroadcastmanager无效。我刚刚删除了android:process line并且它工作了
答案 0 :(得分:2)
您的代码没有任何问题。只更新您的接收方法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();
}
}
};
答案 1 :(得分:-1)
com.android.support:localbroadcastmanager->更改 androidx.localbroadcastmanager:localbroadcastmanager:1.0.0