sha*_*agz 24 android broadcastreceiver
我有BroadcastReceiver一次使用.
我在一个活动中注册它.我不能把它放进去unregisterReceiver(),onPause因为它必须保持运行,即使活动被暂停或销毁.
我希望BroadcastReceiver在完成后取消注册,如下所示:
public class SmsReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
// do some code..
context.unregisterReceiver(this)
}
}
Run Code Online (Sandbox Code Playgroud)
但它会导致异常: Receiver not registered.
tic*_*chy 25
甲BroadcastReceiver其执行过程中只存在onReceive()方法.因此,每次广播被发送/接收时,这将评估为丢弃实例.请参阅广播接收器生命周期.要动态注册/取消注册BroadcastReceivers,您必须记住接收器的实例,onPause()以便在其中再次注册onResume().
MDM*_*lik 10
我知道这个问题已经有了答案但是试试这个代码
此代码适用于BatteryInfo.它确实有效.
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent intent) {
// TODO Auto-generated method stub
int level = intent.getIntExtra("level", 0);
Log.i("Battery", String.valueOf(level) + "%");
arg0.unregisterReceiver(mBatInfoReceiver);
}
};
//Below code is the Code which attaches the reciever put this code in which ever place you want.
this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(
Intent.ACTION_BATTERY_CHANGED));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
43568 次 |
| 最近记录: |