我有一个在服务中动态创建的BroadcastReceiver。其目的是检测何时发送了SMS。它按预期工作。
我的麻烦是我收到一条错误消息,提示“意图接收器已泄漏”。我是否错过了对unregisterReceiver()
的电话?
我正在unregisterReceiver()
中调用onDestroy()
。我想这一定是错的。我应该在哪里注销接收器?
代码...
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
最佳答案
尝试这样:
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();
}
}
关于android - 在哪里注销BroadcastReceiver(在服务中)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7465575/