我在后台创建了一个上传数据的服务。如果没有Internet连接,我想注册正在等待Internet连接的广播接收器,然后再次启动服务。我的问题:
广播接收器从应用程序开始。我不想要这个。广播接收器应该是非注册的,直到服务注册它。 我怎么能这样做?
任何人都可以发布代码示例如何注册从服务中注销Receiver吗?
由于
答案 0 :(得分:2)
在服务中注册接收器和取消注册接收器的示例代码。
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;
}
}