簡體   English   中英

當應用程序處於前台或活動狀態時,廣播接收器不起作用

[英]Broadcast receiver is not working when app on foreground or active

我正在構建有關電池指示器的應用程序,並且正在使用本文中的代碼。

即使關閉應用程序也獲得電池狀態

當應用關閉時,它運行良好,但是當應用處於活動狀態或處於前台狀態時,它不起作用或未發送任何廣播。

這是我開始服務的主要活動

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();
        }
    });

}  }

據我了解,當您第一次啟動應用程序時,您什么也看不到,僅啟動了服務並注冊了廣播接收器。 更改電池電量時,將調用checkBatteryLevel()方法,並且廣播接收器將被注銷。 結果,您從未收到過電池電量的新變化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM