从ram清除时,Android广播不会执行

时间:2015-10-06 04:56:47

标签: android broadcast

您好我创建的广播接收器在Intent.ACTION_BATTERY_CHANGED事件中接收电池电量。它工作得很好但是当我从ram中使用从按住主页按钮滑动删除此应用程序时,它不会收到事件。 我的广播代码是

private BroadcastReceiver BatteryReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        int level = intent.getIntExtra("level", 0);
        Toast.makeText(BatteryIndicatorService.this,""+level, Toast.LENGTH_SHORT).show();
    }
};

1 个答案:

答案 0 :(得分:4)

当你的广播在后台运行以便你需要创建服务时,可以这样做。在这项服务中你必须定义你的广播。

  

BatteryIndi​​catorService.java

public class BatteryIndicatorService extends Service {
private BroadcastReceiver BatteryReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        int level = intent.getIntExtra("level", 0);
        Toast.makeText(BatteryIndicatorService.this,""+level, Toast.LENGTH_SHORT).show();
    }
};

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();
    // Register Receiver.
    registerReceiver(BatteryReceiver, new IntentFilter(
            Intent.ACTION_BATTERY_CHANGED));
}

public void onStart(Intent intent, int startId) {
    // TODO Auto-generated method stub
    super.onStart(intent, startId);
}

@Override
public void onDestroy() {
      // TODO Auto-generated method stub
      super.onDestroy();
   }
}

从MainActivity开始,如

  

MainActivity.java

protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    // Start service in Background
    startService(new Intent(this, BatteryIndicatorService.class));
 }

在应用程序标记中的Manifest.xml中定义服务

  

的manifest.xml

<service
        android:name="com.ittl.batteryindicator.BatteryIndicatorService"
        android:enabled="true" >
</service>