我正在使用AndroidService,每5分钟就会进行一次网络调用,以便从数据库中搜索新数据。我已经实现BroadcastListener
来监听服务中的持续连接,但是应用程序每次都会崩溃。
错误:
java.lang.RuntimeException: Error receiving broadcast Intent { act=android.net.conn.CONNECTIVITY_CHANGE flg=0x4000010 (has extras) } in com.test.service.MyService$1@d3df904
全球声明:
BroadcastReceiver receiver;
代码:
@Override
public void onCreate() {
super.onCreate();
registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(ConnectionStatus.isConnected(MyService.this)){
//some work
}
else {
//some task
}
}
};
registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
return START_STICKY;
}
答案 0 :(得分:2)
onCreate
发生在onStartCommand
之前,因此您尝试使用空接收器注册广播接收器。从onCreate
删除寄存器,它应该可以工作。