【问题标题】:avoid to receive Broadcast Receiver when app is pause or in background避免在应用暂停或后台接收广播接收器
【发布时间】:2013-05-07 16:42:39
【问题描述】:

我已经注册了设备级广播接收器(android.net.wifi.WIFI_STATE_CHANGED),它可以很好地监控 WiFi 信号,但我只想在应用程序处于活动状态或应用程序未处于后台或暂停状态时拉森接收类。目前当我离开我的应用程序并浏览任何其他应用程序时。如果我更改 wifi 信号(关闭或打开),那么我的接收器会生成事件。我只想在我的应用程序处于活动状态时生成事件,我不想在任何其他应用程序中接收通知

  <receiver android:name="com.android.mobileTimerClock.WifiReceiver"  >
              <intent-filter>

            <action android:name="android.net.wifi.WIFI_STATE_CHANGED"/>
    </intent-filter>
          </receiver>

【问题讨论】:

    标签: android broadcastreceiver


    【解决方案1】:

    您必须在 Activity.onResume() 方法上以编程方式注册您的 BroadcastReceiver,并在 Activity.onPause 方法上取消注册。

    Example

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
        // Create the receiver
        receiver = new TimelineReceiver();
        filter = new IntentFilter( UpdaterService.NEW_STATUS_INTENT );
    }
    
    protected void onResume() {
        super.onResume();
        super.registerReceiver(receiver, filter,
                 "com.marakana.yamba.SEND_TIMELINE_NOTIFICATIONS", null);
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(receiver);
    }
    

    【讨论】:

    • 但问题是,我有很多 Activity,我无法在 Activity 级别管理它。它应该是设备级别
    • 创建一个扩展 Activity 并实现此行为的 BaseActivity。之后,让您的所有活动都扩展 BaseActivity 而不是 Activity。
    • 谢谢,在基本 Activity 中,我将覆盖 on pause 和 on resume.but 应用程序将出现异常
    • IntentFilter 过滤器 =new IntentFilter(); filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); filter.addAction(Intent.ACTION_SCREEN_OFF);注册接收器(wReceiver,过滤器);在我的基础活动中
    • public class ScreenReciver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { Intent myintent = new Intent(context ,TimerClockActivity.class); myintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); myintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(myintent); } int wifiState = 默认:中断;
    【解决方案2】:

    我很高兴看到你的问题。我认为你在 onDestroy() 方法中取消注册接收器(),以便在后台接收广播。如果你想避免它,然后在 onPause() 中取消注册接收器。

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(receiver);
    }
    
    I hope its help you.
    

    【讨论】:

      【解决方案3】:

      Manifest Receiver 旨在处理广播事件,即使基础 Activity 未处于活动状态。实际上,您可以自己拥有一个清单广播接收器(无需任何活动)。如果您不希望根据特定 Activity 的状态调用 onReceive(),则不能使用清单接收器。

      但是,您仍然可以选择处理事件的方式。您可以在处理事件之前检查您的活动(或多个活动)是否处于活动状态(使用 ActivityManager)。

      【讨论】:

        猜你喜欢
        • 2011-12-14
        • 2013-03-05
        • 1970-01-01
        • 2014-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多