电池监视/监视应用程序Android

时间:2012-06-15 20:08:23

标签: android

我正在开发一个应用程序来显示手机/平板电脑的电池状态。我让它运行并按原样运行,但不知何故,当屏幕关闭时应用程序被“杀死”。

奇怪的是,虽然这是在我的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'的方法,然后应用程序可以重新加载,但我愿意接受如何在屏幕上运行它的建议关闭/锁定。

提前致谢

1 个答案:

答案 0 :(得分:2)

您可能要考虑使用Service,因为您希望长期运行,开发人员指南here会详细说明。另外(虽然我找不到链接)想要告诉Android它应该重启你的应用程序,如果它必须杀死它。我不记得究竟是什么叫

**其他信息** 我在上面给出了一些虚假的信息。我相信你可以在Android杀死它但不是活动后重新启动服务。在上面的链接中,有关服务的开发人员指南,详细信息请参见此处。它被称为粘性服务,请参阅Extending the Service Class小节。