如何在android中使用系统电池状态更新通知

Posted

技术标签:

【中文标题】如何在android中使用系统电池状态更新通知【英文标题】:how to update notification with system battery status in android 【发布时间】:2012-12-07 13:52:33 【问题描述】:

在通知中我尝试更新我的电池状态。我用服务创建通知。但我不知道如何用电池状态更新通知:

我还阅读了以下文档: http://developer.android.com/guide/topics/ui/notifiers/notifications.html

主活动

@Override
    public void onCreate(Bundle savedInstanceState) 

registerReceiver(batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
..



private BroadcastReceiver batteryReceiver = new BroadcastReceiver() 

        private int scale = -1;
        private int level = -1;
        private int voltage = -1;
        private int temp = -1;

        @Override
        public void onReceive(Context context, Intent intent) 
            level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);
            voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);

            String ns = Context.NOTIFICATION_SERVICE;
            NotificationManager mNotificationManager = (NotificationManager)context.getSystemService(ns);
            long when = System.currentTimeMillis();

            String percent = ((level * 100) / scale) + "%";
            Notification notification = new Notification(R.drawable.call, percent, when);
            /* <set your intents here> */
            mNotificationManager.notify(7331, notification);

            Log.d(TAG, "Battery level is " + level + "/" + scale + ", temp is " + temp + ", voltage is " + voltage);
        
    ;

我正在使用创建通知的服务

private void showNotification() 
        Notification notification = new Notification(R.drawable.call, getString(R.string.notification_text), System.currentTimeMillis());
        Intent intent = new Intent(this, MainActivity.class);

        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
        notification.setLatestEventInfo(this, getString(R.string.notification_label), getString(R.string.notification_text_short), pi);
        notification.flags |= Notification.FLAG_NO_CLEAR;
        startForeground(7331, notification);
    

错误:

12-07 14:46:29.425: E/AndroidRuntime(25758): FATAL EXCEPTION: main
12-07 14:46:29.425: E/AndroidRuntime(25758): java.lang.RuntimeException: Error receiving broadcast Intent  act=android.intent.action.BATTERY_CHANGED flg=0x60000010 (has extras)  in com.xxx.xxx.MainActivity$1@41558b80
12-07 14:46:29.425: E/AndroidRuntime(25758):    at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:737)
12-07 14:46:29.425: E/AndroidRuntime(25758):    at android.os.Handler.handleCallback(Handler.java:605)
12-07 14:46:29.425: E/AndroidRuntime(25758):    at android.os.Handler.dispatchMessage(Handler.java:92)
12-07 14:46:29.425: E/AndroidRuntime(25758):    at android.os.Looper.loop(Looper.java:137)
12-07 14:46:29.425: E/AndroidRuntime(25758):    at android.app.ActivityThread.main(ActivityThread.java:4511)
12-07 14:46:29.425: E/AndroidRuntime(25758):    at java.lang.reflect.Method.invokeNative(Native Method)
12-07 14:46:29.425: E/AndroidRuntime(25758):    at java.lang.reflect.Method.invoke(Method.java:511)
12-07 14:46:29.425: E/AndroidRuntime(25758):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
12-07 14:46:29.425: E/AndroidRuntime(25758):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
12-07 14:46:29.425: E/AndroidRuntime(25758):    at dalvik.system.NativeStart.main(Native Method)
12-07 14:46:29.425: E/AndroidRuntime(25758): Caused by: java.lang.IllegalArgumentException: contentView required: pkg=com.xxx.xxx id=7331 notification=Notification(contentView=null vibrate=null,sound=null,defaults=0x0,flags=0x0)
12-07 14:46:29.425: E/AndroidRuntime(25758):    at android.os.Parcel.readException(Parcel.java:1331)
12-07 14:46:29.425: E/AndroidRuntime(25758):    at android.os.Parcel.readException(Parcel.java:1281)
12-07 14:46:29.425: E/AndroidRuntime(25758):    at 
android.app.INotificationManager$Stub$Proxy.enqueueNotificationWithTag(INotificationManager.java:317)
12-07 14:46:29.425: E/AndroidRuntime(25758):    at android.app.NotificationManager.notify(NotificationManager.java:127)
12-07 14:46:29.425: E/AndroidRuntime(25758):    at android.app.NotificationManager.notify(NotificationManager.java:106)
12-07 14:46:29.425: E/AndroidRuntime(25758):    at com.xxx.xxx.MainActivity$1.onReceive(MainActivity.java:72)
12-07 14:46:29.425: E/AndroidRuntime(25758):    at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:728)
12-07 14:46:29.425: E/AndroidRuntime(25758):    ... 9 more

【问题讨论】:

我认为您没有在 onCreate() 方法中为您的活动设置 contentView。 之前的评论是正确的;每个通知都需要一个 contentView。使用 Notification.Builder 类(在 API 11 中可用,或在早期平台的 support-v4 库中可用)生成通知对象。 【参考方案1】:

我认为您需要使用权限 BATTERY_STATS。 如果要更新通知,则必须在 PendingActivity.getActivity 中使用 PendingIntent.FLAG_UPDATE_CURRENT 作为标志

这是我的应用程序中的一些代码:

final NotificationManager notificationMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

Notification note = new Notification(R.drawable.icon, text, System.currentTimeMillis());
note.flags = Notification.FLAG_AUTO_CANCEL | Notification.FLAG_ONLY_ALERT_ONCE;
note.defaults = Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE;

Intent intent = null;
PendingIntent pendingIntent = null;

intent = new Intent(context, MailActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
pendingIntent = PendingIntent.getActivity(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

note.setLatestEventInfo(context, "nyxdroid", text, pendingIntent);
notificationMgr.notify(1980 + type, note);

【讨论】:

谢谢。我也可以代替图标(R.drawable.icon)显示文本吗?比如 59% 和电池图标?

以上是关于如何在android中使用系统电池状态更新通知的主要内容,如果未能解决你的问题,请参考以下文章

屏幕打开/关闭时如何更新 Android 小部件?

Android:如何在状态栏中获取电池图标资源 ID 或完整文件路径/名称?

如何在 Android 的后台监控电池电量?

使用 http 时的 Android 电池

如何使用 FUSED LOCATION API 优化电池 - Android

在android中自动更新电池电量