Android 有时接收不到自己发送的广播消息

2020年2月29日 12点热度 0条评论 来源: kk_q

由于要跟其他应用程序进行广播通信,所以自己写好这边代码之后写了个demoapk跟自己的进行测试。

自己的APK简称A,测试APK简称B

B在启动时发送了广播消息MSG1,A收到消息MSG1之后回个广播消息MSG2,

问题:B很难接收到MSG2(测试时偶尔能接收到一次),根据打印日志是知道A是发出了MSG2的。代码如下:

应用程序 A(A的AndroidManifest.xml加了广播消息注册):

public class BootBroadcastReceiver extends BroadcastReceiver{
	static final String REQUESTMSG = "REQUESTMSG";
	static final String ANSWERMSG = "ANSWERMSG";
	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		if(intent.getAction().equals(REQUESTMSG)){
			Toast.makeText(arg0, "REQUESTMSG", Toast.LENGTH_LONG).show();
			String str = "answer msg";
			Intent it = new Intent(ANSWERMSG);
			it.putExtra("msg", str);
			context.sendBroadcast(it);
		}
	}

}

应用程序 B(代码注册广播消息,在AndroidManifest.xml不用增加广播消息注册):

public class MainActivity extends Activity {
	static final String REQUESTMSG = "REQUESTMSG";
	static final String ANSWERMSG = "ANSWERMSG";
	
	private AnswerBrocastReceiver receiver = new AnswerBrocastReceiver();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		
		
		Intent intent = new Intent();
		intent.setAction(REQUESTMSG);
		sendBroadcast(intent);
		
		.....
		
		IntentFilter intentFilter = new IntentFilter(ANSWERMSG); registerReceiver(receiver, intentFilter);
	}
	
	class AnswerBrocastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			// TODO Auto-generated method stub
			if (arg1.getAction().equals(ANSWERMSG)) {
				String msg = arg1.getStringExtra("msg");
				//if(!msg.isEmpty()){
					Toast.makeText(arg0, "ANSWERMSG", Toast.LENGTH_LONG).show();
				//}
			}
		}

	}
}

最后找到的解决办法,就是把上述红色注册ANSWERMSG广播消息的代码挪到发送REQUESTMSG消息之前就能接收了。对于为什么这样做能收到,猜想应该是广播执行周期太短,那会注册还没来得及接收。

    原文作者:kk_q
    原文地址: https://blog.csdn.net/z358247505/article/details/20545147
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。