手动注册和注销广播接收机



我创建了一个在后台上传数据的服务。如果没有互联网连接,我想注册一个正在等待互联网连接的广播接收器,然后再次启动服务。我的问题:

broadcastreceiver从app开始,我不想这样。广播接收器应该取消注册,直到服务注册它。我该怎么做呢?

和谁可以张贴一个代码样本如何从服务注册一个取消注册的接收器?

谢谢

在service内部注册和注销receiver的示例代码

public class CallDetectService extends Service {
    BroadcastReceiver phoneCallreceiver;
    Calendar futuretime=Calendar.getInstance();
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
        Log.v("ranjith","Inside onstartcommand of calldetectservice");
        phoneCallreceiver = new PhoneCallreceiver();
        registerReceiver(phoneCallreceiver, intentFilter);

        return START_STICKY;
    }
    @Override
    public void onDestroy() {
        Toast.makeText(getApplicationContext(), "Service destroy called", Toast.LENGTH_LONG).show();
        Log.v("ranjith", "stopped the service");
        if (phoneCallreceiver != null) {
            unregisterReceiver(phoneCallreceiver);
            Log.v("ranjith", "Unregistered receiver");
        }
        super.onDestroy();
    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

最新更新