在Android活动中注册两个接收器时出错

时间:2016-12-26 12:31:22

标签: android broadcastreceiver intentfilter

我有一项活动。它将从服务中接收两个变量。在服务中,我将通过

向活动发送两个变量
 // Send first variable 
 sendBroadcast(new Intent("first_one"));
 // Send second variable 
 sendBroadcast(new Intent("second_one"));

现在,在活动中,我使用了以下代码来接收数据。有

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerReceiver(firstRec, new IntentFilter("first_one"));
        registerReceiver(secondRec, new IntentFilter("second_one"));
    }   
    @Override
    protected void onPause() {
        super.onPause();
        if (firstRec != null) {
            unregisterReceiver(firstRec);
            firstRec = null;
        }
        if (secondRec != null) {
            unregisterReceiver(secondRec);
            secondRec = null;
        }
    }
    private BroadcastReceiver firstRec = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("TAG","OK first");
        }
    };

    private BroadcastReceiver secondRec = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("TAG","OK second");
        }
    };

然而,我无法打印日志" OK second"当我调用sendBroadcast(new Intent(" second_one"));在服务中。怎么了?我该如何解决?谢谢

更新:我的活动是来自@notz的接受调用活动 How can incoming calls be answered programmatically in Android 5.0 (Lollipop)?。然后我创建一个服务如下

public class myService extends Service{
@Override
    public void onCreate() {
        super.onCreate();
 }
@Override
public IBinder onBind(Intent intent) {
   return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
   Intent answerCalintent = new Intent(getApplicationContext(), AcceptCallActivity.class);
   answerCalintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
   answerCalintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   startActivity(answerCalintent);
   //Send the second command after 10 second and make the calling in background
   new CountDownTimer(10000, 100) {
        public void onTick(long millisUntilFinished) {
        }
        public void onFinish() {
           sendBroadcast(new Intent("second_one"));
        }
   }.start();

   return START_STICKY;
}
}

1 个答案:

答案 0 :(得分:0)

您应该以与注册方式相反的方法取消注册您的reсeiver: 如果您在onCreate()中注册了接收器 - 那么您应该在onDestroy()中取消注册它。 但据我所知,在大多数情况下,最佳做法是在onResume()中注册接收器并在onPause()中取消注册。