1

Is possible create a permanent notification of battery level starting from this code?:

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.
    }
};

And this is an example of a notification.

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());
    }   }

I have to create a permanent notification with the battery level if possible. How can i do it?

David_D
  • 1,404
  • 4
  • 31
  • 65

1 Answers1

2

Use the ongoing flags : http://developer.android.com/reference/android/app/Notification.Builder.html#setOngoing%28boolean%29

The user will not be able to cancel the notification so please don't forget to remove it when it's not useful anymore.

For toggle in it, you need to add a PreferenceActivity or a PreferenceFragment to your app. Then add a checkboxPreference : http://developer.android.com/guide/topics/ui/settings.html

In your code, you can now toggle this particular setting :

boolean permanent = PreferenceManager.getDefaultSharedPreferences(context).getBoolean("permanent", false);
if(permanent) {
    notificationBuilder.setOngoing(true);
}
NitroG42
  • 5,336
  • 2
  • 28
  • 32