我在取消注册BroadcastReceiver时遇到了一些问题.我首先注册它,但是当我想通过使用unregisterReceiver()取消注册它时;命令给了我很多错误.错误说我没有注册我的BroadcastReceiver.
码:
public class Receiver extends BroadcastReceiver implements Variables {
CheckConexion cc;
@Override
public void onReceive(Context contxt, Intent intent) {
// Cuando hay un evento, lo diferenciamos y hacemos una acción.
if (intent.getAction().equals(SMS_RECEIVED)) {
Sms sms = new Sms(null, contxt);
sms.uploadNewSms(intent);
} else if (intent.getAction().equals(Intent.ACTION_BATTERY_LOW)) {
// st.batterylow(contxt);
} else if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) {
// st.power(1, contxt);
} else if (intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED)) {
// st.power(0, contxt);
} else if (intent.getAction().equals(Intent.ACTION_PACKAGE_ADDED)
|| intent.getAction().equals(Intent.ACTION_PACKAGE_CHANGED)
|| intent.getAction().equals(Intent.ACTION_PACKAGE_REMOVED)) {
Database db = new Database(contxt);
if (db.open().Preferences(4)) {
Uri data = intent.getData();
new ListApps(contxt).import_app(intent, contxt, data,
intent.getAction());
}
db.close();
} else if (intent.getAction().equals(
ConnectivityManager.CONNECTIVITY_ACTION)) {
cc = new CheckConexion(contxt);
if (cc.isOnline()) {
/*Database db = new Database(contxt);
db.open();
if (db.move() == 1) {
new UploadOffline(contxt);
}
db.close();*/
}
}
}
public void register(Context c) {
Receiver r = new Receiver();
IntentFilter i = new IntentFilter();
i.addAction(SMS_RECEIVED);
i.addAction(Intent.ACTION_BATTERY_LOW);
i.addAction(Intent.ACTION_POWER_CONNECTED);
i.addAction(Intent.ACTION_POWER_DISCONNECTED);
i.addAction(Intent.ACTION_CALL_BUTTON);
i.addAction(Intent.ACTION_CAMERA_BUTTON);
i.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
c.registerReceiver(r, i);
IntentFilter apps = new IntentFilter();
apps.addAction(Intent.ACTION_PACKAGE_ADDED);
apps.addAction(Intent.ACTION_PACKAGE_CHANGED);
apps.addAction(Intent.ACTION_PACKAGE_REMOVED);
apps.addDataScheme("package");
c.registerReceiver(r, apps);
}
public void unregister(Context c) {
BroadcastReceiver r = new Receiver();
if (r != null) {
c.unregisterReceiver(r);
}
}
}
解决方法:
首先,
使用它来处理类Reciever的对象
删除所有r对象,不要在扩展类中调用构造函数.
然后:
限定
boolean isRegistered = false;
在您的注册方法中:
c.registerReceiver(this);
isRegistered = true;
在取消注册方法中:
if (isRegistered) {
c.unregisterReceiver(this);
isRegistered = false;
}
然后在您的活动中使用类Reciver的实例.
希望,这很有帮助!
标签:android,broadcastreceiver 来源: https://codeday.me/bug/20190714/1455381.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。