我正在开发一个应用程序来显示手机/平板电脑的电池状态。我让它按原样运行和工作,但是当屏幕关闭时,应用程序以某种方式被“杀死”。
奇怪的是,虽然它在我的 LG 手机上被杀死,但在屏幕关闭/锁定时不会在我的 Galaxy Tab 上被杀死。
源代码如下:
public class BatteryLevelActivity extends Activity {
private TextView batterLevel;
CharSequence tickerText = "No need to charge at the moment";
public void onCreate(Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
setContentView(R.layout.main);
this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(
Intent.ACTION_BATTERY_CHANGED));
batterLevel = (TextView) findViewById(R.id.batteryLevel);
};
private void notif(int level) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon;
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
Context context = getApplicationContext();
CharSequence contentTitle = "BatteryWatch";
CharSequence contentText = "Remaining charge level is " + level + "%";
Intent notificationIntent = new Intent();
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText,
contentIntent);
notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
notification.flags |= Notification.FLAG_ONGOING_EVENT;
final int HELLO_ID = 1;
mNotificationManager.notify(HELLO_ID, notification);
}
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent intent) {
int level = intent.getIntExtra("level", 0);
batterLevel.setText("Battery level is at " + level + "%\n\n"
+ tickerText);
notif(level);
tickerText = "";
}
};
}
不知何故,我认为我应该有一个称为“onScreenOff”或“onScreenOn”之类的方法,然后可以重新加载应用程序,但我愿意接受有关如何在屏幕关闭时使其运行的建议/锁定。
提前致谢