0
我正在開發一個android應用程序,我必須通過廣播接收器獲取電池電量,並在電池更換時在後臺顯示烤麪包。 我已經註冊了接收方和意向過濾器以獲取該值。Android中的Broadcast Reciever與Intent.ACTION_BATTERY_CHANGED不在後臺工作
它在應用程序打開時運行良好,但在應用程序關閉時它不提供值。
請建議我應該以與背景值運行敬酒時做應用程序被關閉
public class MainActivity extends Activity {
private TextView batteryPercent;
int level;
private void getBatteryPercentage() {
BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(this);
int currentLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL,-1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
level = -1;
if (currentLevel >= 0 && scale > 0) {
level = (currentLevel * 100)/scale;
}
batteryPercent.setText("Battery Level Remaining: " + level + "%");
CountDownTimer cdt = new CountDownTimer(5000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
Toast.makeText(getApplicationContext(),"Level "+Integer.toString(level),
Toast.LENGTH_LONG).show();
;
}
}
.start();
}
};
IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryLevelReceiver, batteryLevelFilter);
}
/* @Override*/
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
batteryPercent = (TextView) this.findViewById(R.id.batteryLevel);
getBatteryPercentage();
}
塊引用