我创建了一个广播接收器,用于带有活动的服务反馈。但这不起作用。调试器 - 从服务调用sendBroadcast后,跳过此(LocalBroadcastManager.getInstance(this).sendBroadcast(RTReturn);)行并且不会导致活动
This is Activity
package com.example.my;
BroadcastReceiver br;
public static final String RECEIVE_JSON =
"com.example.my.RECEIVE_JSON";
public class cama extends AppCompatActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
xcxc();
xcx();
}
public void xcxc()
{
br = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(RECEIVE_JSON)) {
String serviceJsonString = intent.getStringExtra("json");
Toast toast = Toast.makeText(getApplicationContext(),
"Test!", Toast.LENGTH_SHORT);
toast.show();
}
}
};
}
public void xcx()
{
LocalBroadcastManager bManager;
bManager = LocalBroadcastManager.getInstance(this);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(RECEIVE_JSON);
bManager.registerReceiver(br, intentFilter);
}
@Override
public void onDestroy() {
super.onDestroy();
if (br != null) {
unregisterReceiver(br);
}
}
这是服务
package com.example.my;
public class MyService extends Service
@Override
public void onCreate() {
do_anything();
}
public void do_anything()
{Intent RTReturn = new Intent(cama.RECEIVE_JSON);
RTReturn.putExtra("json", "ole");
LocalBroadcastManager.getInstance(this).sendBroadcast(RTReturn);}
答案 0 :(得分:0)
只需在onCreate(Bundle savedInstanceState)
内使用:
LocalBroadcastManage
mlocal = LocalBroadcastManager.getInstance(getApplicationContext());
mlocal.sendBroadcast(YOUR Reciever)