gpt4 book ai didi

android - 在哪里注销 BroadcastReceiver(在服务中)?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:24:15 25 4
gpt4 key购买 nike

我有一个在服务中动态创建的 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

最佳答案

像这样尝试:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com