android 性能优化--禁用广播接收器
只有当应用在前台的时候才可以启用广播接收器
1.广播接收模式为成禁用。
manifest.xml
<receiver android:name=".ReceiverName" android:enabled="false">
2.广播接收器在onResume()中启用,在onPause()中禁用。
1 public class TestActivity extends Activity{ 2 3 private void enableReceiver(boolean enabled){ 4 PackageManager pm = getPackageManager(); 5 ComponentName receiverName = new ComponentName(getApplicationContext(),ReceiverName.class); 6 int newState; 7 8 if(enabled){ 9 newState = PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 10 }else{ 11 newState = PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 12 } 13 14 pm.setComponentEnabledSetting(receiverName,newState,PackageManager.DONT_KILL_APP); 15 } 16 @Override 17 protected void onPause(){ 18 super.onPause(); 19 unregisterReceiver(mReceiver); 20 enableReceiver(false);//没在前台时候要隐藏 21 } 22 23 @Override 24 protected void onResume(){ 25 super.onResume(); 26 if( mReceiver == null ) { 27 //创建receiver 28 } 29 registerReceiver(mReceiver,new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); 30 enableReceiver(true); 31 } 32 33 }