我想注册广播接收器接收短信只有当我的应用程序在前台,否则注销广播接收器。
<receiver android:name="smsreader.com.messagereciver.IncomingSms">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
//接收短信代码
public class IncomingSms extends BroadcastReceiver {
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
// receive SMS code
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
}
这将帮助你知道你的应用程序是否在前台
private boolean isFG;
@Override
protected void onPause() {
super.onPause();
isFG = false;
}
@Override
protected void onResume() {
super.onResume();
isFG = true;
}
// Some function.
public boolean isInForeground() {
return isFG;
}
然后用下面的方式编写一个函数以编程方式注册您的Broadcast receiver
。
在代码(MyBroadcastReceiver)中创建BroadcastReceiver
。在你的活动范围内声明MyBroadcastReceiver
:
MyBroadcastReceiver mMyBroadcastReceiver;
注册BroadcastReceiver
在您的活动:
if(isFG == true){
IntentFilter filter = new IntentFilter(android.provider.Telephony.SMS_RECEIVED);
this.registerReceiver(mMyBroadcastReceiver, filter);
}else{
//dont register
}
希望这对你有帮助。谢谢。
你可以在Application
的onCreate()
方法中注册一个ActivityLifecycleCallbacks,当一个活动开始时回调计数,当一个活动停止时回调计数。如果count大于1,这意味着至少有一个活动已经启动,你可以注册广播接收器,如果它是零,那么没有启动(用户可见)的活动,你可以取消注册广播接收器。
此解决方案是独立于活动的,并且将在您的任何活动启动时工作。
我建议你在onResume()中注册广播接收器,并在onPause()中取消注册。
:
@Override
protected void onResume() {
super.onResume();
registerReceiver(receiver, intentFilter);
}
@Override
protected void onPause() {
unregisterReceiver(receiver);
super.onPause();
}
我按语法创建了Broadcastreceiver,并在活动的onResume()中注册,也在onPause()中未注册,在我的情况下工作得很好。
IncomingSms smsReceiver;
private IntentFilter myFilter;
@Override
protected void onPause() {
unregisterReceiver(smsReceiver); // UnRegister BroadCastReceiver as you no longer have your activity at Foreground -- Saving CPU & Battery Drainage
super.onPause();
}
@Override
protected void onResume()
{
smsReceiver = new IncomingSms();
myFilter = new IntentFilter();
myFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(smsReceiver, myFilter); // Register BroadCastReceiver Once again as your activity comes from pause to forground state again.
super.onResume();
}