Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package pl.danek.battery;
- import android.app.IntentService;
- import android.app.Notification;
- import android.app.NotificationManager;
- import android.app.Service;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.content.IntentFilter;
- import android.media.audiofx.NoiseSuppressor;
- import android.os.BatteryManager;
- import android.os.Handler;
- import android.os.IBinder;
- import android.support.v4.app.NotificationCompat;
- import android.widget.Toast;
- public class BatteryService extends IntentService{
- private BroadcastReceiver receiver = new BroadcastReceiver(){
- @Override
- public void onReceive(Context context, Intent intent) {
- calculateBatteryLevel(intent);
- }
- };
- public static int NOTIFICATION_ID = 12354;
- NotificationManager manager;
- Notification notification;
- int batteryLevel;
- private boolean finish = true;
- public BatteryService() {
- super("Battery Service");
- }
- @Override
- protected void onHandleIntent(Intent intent) {
- registerReceiver(receiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
- manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
- do {
- showNotification();
- try {
- Thread.sleep(5000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- } while (finish );
- }
- private void calculateBatteryLevel(Intent intent) {
- batteryLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL,-1);
- }
- private void showNotification() {
- int icon = choseIcon();
- notification = new Notification.Builder(this)
- .setContentTitle("Battery level")
- .setSmallIcon(icon)
- .setOngoing(true)
- .setContentText(batteryLevel + " %")
- .build();
- manager.notify(NOTIFICATION_ID, notification);
- }
- private int choseIcon() {
- if (batteryLevel < 25) {
- return R.drawable.battery_less;
- }
- if (batteryLevel < 50) {
- return R.drawable.battery_half;
- }
- if (batteryLevel < 75) {
- return R.drawable.battery_more;
- }
- return R.drawable.battery_full;
- }
- @Override
- public void onDestroy() {
- super.onDestroy();
- manager.cancelAll();
- finish = false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement