Manipulating Broadcast Receivers On Demand 按需操控廣播接收

來源:互聯網
上載者:User

The simplest way to monitor device state changes is to create a BroadcastReceiver for each state you're monitoring and register each of them in your application manifest. Then within each of these receivers you simply reschedule your recurring alarms based on the current device state. A side-effect of this approach is that your app will wake the device each time any of these receivers is triggered—potentially much more frequently than required. A better approach is to disable or enable the broadcast receivers at runtime. That way you can use the receivers you declared in the manifest as passive alarms that are triggered by system events only when necessary. Toggle and Cascade State Change Receivers to Improve EfficiencyUse can use the PackageManager to toggle the enabled state on any component defined in the manifest, including whichever broadcast receivers you wish to enable or disable as shown in the snippet below: ComponentName receiver = new ComponentName(context, myReceiver.class); PackageManager pm = context.getPackageManager(); pm.setComponentEnabledSetting(receiver,        PackageManager.COMPONENT_ENABLED_STATE_ENABLED,        PackageManager.DONT_KILL_APP)Using this technique, if you determine that connectivity has been lost, you can disable all of your receivers except the connectivity-change receiver. Conversely, once you are connected you can stop listening for connectivity changes and simply check to see if you're online immediately before performing an update and rescheduling a recurring update alarm. You can use the same technique to delay a download that requires higher bandwidth to complete. Simply enable a broadcast receiver that listens for connectivity changes and initiates the download only after you are connected to Wi-Fi.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.