I'm using this code to stop a notification. I'm using Android Studio and switch buttons (via the mainActivity
):
public class MainActivity extends AppCompatActivity {
public static final String NOTIFICATION_CHANNEL_ID = "channel_id";
public static final String CHANNEL_NAME = "Notification Channel";
SharedPreferences.Editor prefEditor;
SharedPreferences prefs;
public Switch switchbtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefEditor= PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit();
prefs=PreferenceManager.getDefaultSharedPreferences(getBaseContext());
switchbtn= findViewById(R.id.switch2);
switchbtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(switchbtn.isChecked()){
shownotifi();
prefEditor.putString("checked","yes");
prefEditor.apply();
}
else{
//To Stop notification?????
prefEditor.putString("checked","no");
prefEditor.apply();
}
}
});
if(prefs.getString("checked","no").equals("yes")) {
switchbtn.setChecked(true);
}
else{
switchbtn.setChecked(false);
}
}
public void shownotifi() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
builder.setContentTitle("This is heading");
builder.setContentText("This is description");
builder.setSmallIcon(R.drawable.ic_android_black_24dp);
Notification notification = builder.build();
NotificationManager notificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0,builder.build());
}
}
What changes do I need to make to the code above to stop the notifications? I've commented where I need to stop them.