应用程序在前台或活动时,广播接收器不工作

时间:2016-04-28 08:14:08

标签: android broadcastreceiver

我正在构建有关电池指示器的应用程序,我正在使用此帖子中的代码。

Getting battery status even when the application is closed

应用程序关闭时工作正常,但当应用程序处于活动状态或前台时,它无效或无法发送任何广播。

这是我开始服务的主要活动

public class Main extends Activity {

private MyService service;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    if (service == null) {

        Intent i = new Intent(this, MyService.class);
        startService(i);
    }

    finish();
}

}

以下是服务代码。

public class MyService extends Service{

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

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d("MyService", "onStartCommand");
    // do not receive all available system information (it is a filter!)
    final IntentFilter battChangeFilter = new IntentFilter(
            Intent.ACTION_BATTERY_CHANGED);
    // register our receiver
    this.registerReceiver(this.batteryChangeReceiver, battChangeFilter);
    return super.onStartCommand(intent, flags, startId);
}
private final BroadcastReceiver batteryChangeReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(final Context context, final Intent intent) {
        checkBatteryLevel(intent);
    }
};

private void checkBatteryLevel(Intent batteryChangeIntent) {
    // some calculations
    final int currLevel = batteryChangeIntent.getIntExtra(
            BatteryManager.EXTRA_LEVEL, -1);
    final int maxLevel = batteryChangeIntent.getIntExtra(
            BatteryManager.EXTRA_SCALE, -1);
    final int percentage = (int) Math.round((currLevel * 100.0) / maxLevel);

    if(percentage==100)
    {
        Intent intent = new Intent(getBaseContext(), Last.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getApplication().startActivity(intent);

    }
    // do not forget to unregister
    unregisterReceiver(batteryChangeReceiver);
} }

当以下活动开始时,我没有收到任何广播。

public class Last extends Activity {
Button btnCancel;
Uri notification;
Ringtone r;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_last);

    notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
    r = RingtoneManager.getRingtone(getApplicationContext(), notification);
    r.play();


     btnCancel = (Button) findViewById(R.id.stopsound);

     btnCancel.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub

             r.stop();
        }
    });

}  }

1 个答案:

答案 0 :(得分:0)

据我了解, 当您第一次启动应用程序时,您什么也看不到,只启动服务并注册广播接收器。当电池电量改变时,方法 checkBatteryLevel()正在呼叫,广播接收器将被取消注册。结果,您从未收到过新的电池电量变化。