如何创建永久通知以显示电池电量

时间:2013-07-03 15:21:56

标签: android statusbar android-notifications batterylevel

我陷入了通知的创建状态。只想在状态栏中显示电池电量(通知栏)通知是永久性的。这是代码的一部分:

private BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

            int  level= intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);

              String[] status = {
                "Level: "+level
                 . . .
               };

             NotificationManager notifi = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

             Notification notification = new Notification(R.drawable.ic_launcher,"Level",System.currentTimeMillis());

             notification.flags = Notification.FLAG_ONGOING_EVENT;

             Intent i = new Intent(context, MainActivity.class); 

             PendingIntent penInt = PendingIntent.getActivity(getApplicationContext(), 0 , i , 0);

             notification.setLatestEventInfo(getApplicationContext(), +level+"%", penInt);

             notifi.notify(215,notification);


            }
};

这是对的吗?在清单中还有其他东西需要添加吗?我没有指定的通知类,所以我用这种方式编写了这一行:Intent i = new Intent(context, MainActivity.class);但我不知道它是否正确。

1 个答案:

答案 0 :(得分:0)

是的,您需要添加:

<uses-permission android:name="android.permission.BATTERY_STATS" />

此处提供更多信息:

Get battery level only once using Android SDK