【问题标题】:Where to unregister BroadcastReceiver (in a service)?在哪里注销 BroadcastReceiver(在服务中)?
【发布时间】:2011-09-19 01:11:12
【问题描述】:

我有一个在服务中动态创建的 BroadcastReceiver。其目的是检测何时发送了 SMS。它按预期工作。

我的问题是我收到一条错误消息“Intent Receiver has leaked”。我错过了给unregisterReceiver() 的电话吗?

我正在拨打onDestroy() 中的unregisterReceiver()。我想这一定是错误的。我应该在哪里取消注册接收器?

代码...

public class MyService extends Service {
    BroadcastReceiver brSms;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
    }

    @Override
    public void onStart(Intent intent, int startid) {
        //Define the receiver
        brSms = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                //Do some  stuff
            };
        }

        registerReceiver(brSms, new IntentFilter(SENT_SMS_ACTION));
    }

    @Override
    public void onDestroy() {
        unregisterReceiver(brSms);
        Toast.makeText(this, "onDestroy has been called", Toast.LENGTH_SHORT).show();
    }
}//end of MyService

【问题讨论】:

  • 您的代码看起来正确:您是否在看到泄漏通知前不久抛出任何异常?
  • Service.onDestroy() 不能保证被调用。

标签: android broadcastreceiver


【解决方案1】:

试试这样:

public class MyService extends Service {
    BroadcastReceiver brSms;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        brSms = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                //Do some  stuff
            }
        };

        registerReceiver(brSms, new IntentFilter(SENT_SMS_ACTION));
    }

    @Override
    public void onStart(Intent intent, int startid) {
    }

    @Override
    public void onDestroy() {
        unregisterReceiver(brSms);
        Toast.makeText(this, "onDestroy has been called", Toast.LENGTH_SHORT).show();
    }
}

【讨论】:

    【解决方案2】:

    我不知道是什么导致了您的错误消息,但要回答您的问题,您在 onDestroy() 中取消注册是绝对正确的。我从经验中知道这很好用,而且根据documentation for Service.onDestroy(),这也是一个很好的地方:

    ...此时服务应该清理它持有的所有资源(线程、注册的接收器等)。 ...

    【讨论】:

      【解决方案3】:

      避免onStart()...尝试onStartCommand(Intent intent, int flags, int startId)...

      【讨论】:

        【解决方案4】:

        你需要调用 super.onDestroy()。

        @Override
        public void onDestroy() {
            unregisterReceiver(brSms);
            Toast.makeText(this, "onDestroy has been called", Toast.LENGTH_SHORT).show();
        
            super.onDestroy();
        }
        

        希望这对你有用。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-05-13
          • 1970-01-01
          • 2017-02-01
          • 1970-01-01
          • 2019-05-19
          • 1970-01-01
          相关资源
          最近更新 更多