如何使用电池级别创建永久通知?

时间:2013-07-30 13:51:58

标签: android statusbar android-notifications batterylevel permanent

是否可以从此代码开始创建电池电量的永久通知?:

public void onCreate(Bundle savedInstanceState) {
    ...
    this.registerReceiver(this.myBatteryReceiver , new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    ...
}

private BroadcastReceiver myBatteryReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
        //here you can use level as you wish.
    }
};

这是通知的一个例子。

private void CheckNoti(){ 
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
                                service.this);
                notificationBuilder.setContentTitle("Title");
                notificationBuilder.setContentText("Context");
                notificationBuilder.setTicker("TickerText");
                notificationBuilder.setWhen(System.currentTimeMillis());
                notificationBuilder.setSmallIcon(R.drawable.ic_stat_icon);

                Intent notificationIntent = new Intent(this, service.class);
                PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                                notificationIntent, 0);

                notificationBuilder.setContentIntent(contentIntent);

                notificationBuilder.setDefaults(Notification.DEFAULT_SOUND
                                | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE);

                mNotificationManager.notify(1,
                                notificationBuilder.build());
    }   }

如果可能,我必须使用电池级别创建永久通知。我该怎么办?

1 个答案:

答案 0 :(得分:2)

使用正在进行的标记:http://developer.android.com/reference/android/app/Notification.Builder.html#setOngoing%28boolean%29

用户将无法取消通知,因此请不要忘记将其删除。

要切换,您需要在应用中添加PreferenceActivityPreferenceFragment。然后添加checkboxPreference:http://developer.android.com/guide/topics/ui/settings.html

在您的代码中,您现在可以切换此特定设置:

boolean permanent = PreferenceManager.getDefaultSharedPreferences(context).getBoolean("permanent", false);
if(permanent) {
    notificationBuilder.setOngoing(true);
}