【问题标题】:BroadcastReceiver cause crash inside AndroidServiceBroadcastReceiver 导致 AndroidService 内部崩溃
【发布时间】:2017-01-19 10:06:04
【问题描述】:

我正在开发 AndroidService,每 5 分钟进行一次网络调用以从数据库中搜索新数据。我已经实现BroadcastListener 来监听服务内部的持续连接,但应用程序每次都崩溃。

错误:

java.lang.RuntimeException: 在 com.test.service.MyService$1@d3df904 中接收广播 Intent { act=android.net.conn.CONNECTIVITY_CHANGE flg=0x4000010 (has extras) } 时出错

全局声明:

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;

}

【问题讨论】:

    标签: android service connection broadcastreceiver runtimeexception


    【解决方案1】:

    onCreate 发生在 onStartCommand 之前,因此您尝试使用空接收器注册广播接收器。从onCreate 中删除寄存器,它应该可以工作。

    【讨论】:

    • 我还是一样的RuntimeException,我也删除了
    • 还应该在哪里注册接收者?
    • 服务被销毁时是否注销?我在一个运行良好的服务中有几乎完全相同的代码。
    猜你喜欢
    • 2014-11-22
    • 2016-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多