|
| 1 | +package com.example.r_k.intentservicebatterypercentage; |
| 2 | + |
| 3 | +import android.app.NotificationManager; |
| 4 | +import android.content.Intent; |
| 5 | +import android.content.SharedPreferences; |
| 6 | +import android.os.Bundle; |
| 7 | +import android.support.v7.app.AppCompatActivity; |
| 8 | +import android.support.v7.app.NotificationCompat; |
| 9 | +import android.widget.CompoundButton; |
| 10 | +import android.widget.Switch; |
| 11 | + |
| 12 | +public class MainActivity extends AppCompatActivity{ |
| 13 | + private myservice service; |
| 14 | + Switch Batteryswitch; |
| 15 | + Intent intent; |
| 16 | + NotificationCompat.Builder notificationCompat; |
| 17 | + NotificationManager manager; |
| 18 | + |
| 19 | + SharedPreferences preferences; |
| 20 | + SharedPreferences.Editor editor; |
| 21 | + @Override |
| 22 | + protected void onCreate(Bundle savedInstanceState) { |
| 23 | + super.onCreate(savedInstanceState); |
| 24 | + setContentView(R.layout.activity_main); |
| 25 | + Batteryswitch = (Switch) findViewById(R.id.Batteryswitch); |
| 26 | + |
| 27 | + preferences = getSharedPreferences("myPreference", MODE_PRIVATE); |
| 28 | + Batteryswitch.setChecked |
| 29 | + (preferences.getBoolean("Switch", false)); |
| 30 | + |
| 31 | + |
| 32 | + Batteryswitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){ |
| 33 | + @Override |
| 34 | + public void onCheckedChanged(CompoundButton compoundButton, boolean b) { |
| 35 | + |
| 36 | + if (Batteryswitch.isChecked() == true) { |
| 37 | + if (service == null) { |
| 38 | + intent = new Intent(MainActivity.this, myservice.class); |
| 39 | + |
| 40 | + preferences = getSharedPreferences("myPreference", MODE_PRIVATE); |
| 41 | + |
| 42 | + editor = preferences.edit(); |
| 43 | + |
| 44 | + editor.putBoolean("Switch", true); |
| 45 | + |
| 46 | + editor.commit(); |
| 47 | + startService(intent); |
| 48 | + } |
| 49 | + } else { |
| 50 | + editor = preferences.edit(); |
| 51 | + editor.putBoolean("Switch", false); |
| 52 | + editor.apply(); |
| 53 | + intent = new Intent(MainActivity.this, myservice.class); |
| 54 | + |
| 55 | + stopService(intent);//stop service. |
| 56 | + |
| 57 | + //cancel notification from status bar . |
| 58 | + |
| 59 | + notificationCompat = (NotificationCompat.Builder) new NotificationCompat.Builder(getApplicationContext()) |
| 60 | + .setContentTitle("Battery is low") |
| 61 | + .setContentText("Current percentage is ") |
| 62 | + .setSmallIcon(R.drawable.one) |
| 63 | + .setTicker("Battery "); |
| 64 | + manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); |
| 65 | + manager.cancel(0); |
| 66 | + |
| 67 | + } |
| 68 | + } |
| 69 | + }); |
| 70 | + |
| 71 | + } |
| 72 | + |
| 73 | +} |
0 commit comments