i was trying to pop a notification when the device have under 15% battery left.
but it shows the notification every time, also when i have over 15%.
this is my code:
public class MainActivity extends Activity {
public int battery, level;
private static final int DIALOG_EXIT=1;
Button Hscore,ToInfo,ToProj;
ImageView Easter,EXIT,Help,Info;
private TextView contentTxt;
public BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent intent) {
// TODO Auto-generated method stub
level = intent.getIntExtra("level", 0);
contentTxt.setText(String.valueOf(level) + "% Battery");
}
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
contentTxt = (TextView) this.findViewById(R.id.txtbattery);
if(level <= 15)
{
Intent Charge = new Intent(MainActivity.this,ChargeActivity.class);
// Intent st =new Intent(android.provider.Settings.ACTION_SETTINGS);
String title="you have low battery", message="charge your phone";
int icon = R.raw.duck_yellow;
int mNotificationId = 001;
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
getBaseContext(),
0,
Charge,
PendingIntent.FLAG_CANCEL_CURRENT
);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
getBaseContext());
Notification notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
.setAutoCancel(true)
.setContentTitle(title)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setContentIntent(resultPendingIntent)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setLargeIcon(BitmapFactory.decodeResource(getBaseContext().getResources(), R.raw.duck_yellow))
.setContentText(message).build();
NotificationManager notificationManager = (NotificationManager) getBaseContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(mNotificationId, notification);
}
what should i do to fix this?
i think its something to do with the private/public variables
Related
How can I set Large Icon to notification? I getting URL of the Image in timetable.getImage(). In my project, Picasso supports get() method, not with().
I am new in android, please help.
You can see my notififcation on picture below. Icon image of notification is hardcoded. But I need this icon image from timetable.getImage().
This is my code:
public class EpisodeNotifyActivity extends AppCompatActivity {
private NotificationManagerCompat notificationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ativity_episode_notify);
final Timetable timetable = (Timetable) requestService.getResult();
ImageView serImage = (ImageView) findViewById(R.id.seriesImage1);
Button button = findViewById(R.id.notify);
Picasso.get()
.load(timetable.getImage())
.into(serImage);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendNotification(timetable.getSeriesName().toUpperCase() + ", New Episode", timetable.getEpisodesSeason().toString() + "x" + timetable.getEpisodesNumber() + " " + timetable.getEpisodeName());
} }); }
private void sendNotification(String messageTitle, String messageBody) {
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(this, EpisodeNotifyActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
#SuppressLint("WrongConstant")
NotificationChannel notificationChannel = new NotificationChannel("my_notification", "n_channel", NotificationManager.IMPORTANCE_MAX);
notificationChannel.setDescription("description");
notificationChannel.setName("Channel Name");
assert notificationManager != null;
notificationManager.createNotificationChannel(notificationChannel);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_live_tv_black_24dp)
.setContentTitle(messageTitle)
// .setLargeIcon(R.drawable.icon)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_ALL)
.setOnlyAlertOnce(true)
.setChannelId("my_notification")
.setColor(Color.parseColor("#3F5996"));
assert notificationManager != null;
int m = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
notificationManager.notify(m, notificationBuilder.build());
}
}}
public class EpisodeNotifyActivity extends AppCompatActivity {
private NotificationManagerCompat notificationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ativity_episode_notify);
final Timetable timetable = (Timetable) requestService.getResult();
ImageView serImage = (ImageView) findViewById(R.id.seriesImage1);
Button button = findViewById(R.id.notify);
Picasso.get()
.load(timetable.getImage())
.into(serImage);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(this, EpisodeNotifyActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
#SuppressLint("WrongConstant")
NotificationChannel notificationChannel = new NotificationChannel("my_notification", "n_channel", NotificationManager.IMPORTANCE_MAX);
notificationChannel.setDescription("description");
notificationChannel.setName("Channel Name");
assert notificationManager != null;
notificationManager.createNotificationChannel(notificationChannel);
final NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_live_tv_black_24dp)
.setContentTitle(timetable.getSeriesName().toUpperCase() + ", New Episode")
.setContentText(timetable.getEpisodesSeason().toString() + "x" + timetable.getEpisodesNumber() + " " + timetable.getEpisodeName())
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_ALL)
.setOnlyAlertOnce(true)
.setChannelId("my_notification")
.setColor(Color.parseColor("#3F5996"));
Picasso.get().load(timetable.getImage())
.into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
// !!!!!!!! MAGIC HAPPENS HERE
notificationBuilder.setLargeIcon(bitmap);
}
#Override
public void onBitmapFailed(Exception e, Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendNotification();
}
});
}
}
private void sendNotification() {
assert notificationManager != null;
int m = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
notificationManager.notify(m, notificationBuilder.build());
}
}
I have setup Notification Channels in Android Studio for sending my notifications.
So far, I can send a notification when I click a button.
However, I want to add a delay to when the notification is sent.. for example, send the notification after 20 seconds.
I know there is a function in the AlarmManager for System.getTimeInMillis, that would be related to this, but not sure where to go from here.
Here is my code:
public class MyNotificationPublisher extends Application {
public static final String CHANNEL_1_ID = "channel1";
public static final String CHANNEL_2_ID = "channel2";
#Override
public void onCreate() {
super.onCreate();
createNotificationChannels();
}
private void createNotificationChannels() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel1 = new NotificationChannel(
CHANNEL_1_ID,
"Channel 1",
NotificationManager.IMPORTANCE_HIGH
);
channel1.setDescription("This is Channel 1");
NotificationChannel channel2 = new NotificationChannel(
CHANNEL_2_ID,
"Channel 2",
NotificationManager.IMPORTANCE_LOW
);
channel2.setDescription("This is Channel 2");
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel1);
manager.createNotificationChannel(channel2);
}
}
}
public class EmailActivity extends AppCompatActivity {
private Button btnSend;
private NotificationManagerCompat notificationManager;
private long tenSeconds = 10000L;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_email);
notificationManager = NotificationManagerCompat.from(this);
btnSend = findViewById(R.id.button_send);
}
public void sendOnChannel1(View v) {
Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Hi")
.setContentText("Test")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.build();
notificationManager.notify(1, notification);
}
}
You can just schedule the notifications to be sent :-
Use the following method :
public void scheduleNotification(Context context, long delay, int notificationId)
{
//delay is after how much time(in millis) from current time you want to schedule the notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(context) .setContentTitle(context.getString(R.string.title)) .setContentText(context.getString(R.string.content)) .setAutoCancel(true) .setSmallIcon(R.drawable.app_icon) .setLargeIcon(((BitmapDrawable) context.getResources().getDrawable(R.drawable.app_icon)).getBitmap()) .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
Intent intent = new Intent(context, YourActivity.class);
PendingIntent activity = PendingIntent.getActivity(context, notificationId, intent, PendingIntent.FLAG_CANCEL_CURRENT);
builder.setContentIntent(activity); Notification notification = builder.build();
Intent notificationIntent = new Intent(context, MyNotificationPublisher.class);
notificationIntent.putExtra(MyNotificationPublisher.NOTIFICATION_ID, notificationId);
notificationIntent.putExtra(MyNotificationPublisher.NOTIFICATION, notification);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, notificationId, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
long futureInMillis = SystemClock.elapsedRealtime() + delay;
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
}
Then, the receiver class:
public class MyNotificationPublisher extends BroadcastReceiver {
public static String NOTIFICATION_ID = "notification_id";
public static String NOTIFICATION = "notification";
#Override
public void onReceive(final Context context, Intent intent)
{
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = intent.getParcelableExtra(NOTIFICATION);
int notificationId = intent.getIntExtra(NOTIFICATION_ID, 0);
notificationManager.notify(notificationId, notification);
}
}
Then, call scheduleNotification with the appropriate arguments.
Use a handler to delay the execution of notification sending code
Update your code like that
public void sendOnChannel1(View v) {
Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Hi")
.setContentText("Test")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.build();
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
notificationManager.notify(1, notification);
}
}, 20000);
}
Hello I created Broadcast Receiver in the Service class to receive application notifications but it doesn't receive any intents from Notification. When I make the broadcast receiver static, the problem is solved but at this time I cannot access the elements of the non-static upper class. I have to solve this without making it static.
My Code:
public class BackgroundService extends Service {
private final int TASK_DELAY = 0;
private final int TASK_PERIOD = 5 * 1000;
int NOTIFICATION_ID = 1;
private Context context;
private NotificationCompat.Builder builder;
private NotificationManager notificationManager;
private static Timer timer;
private PendingIntent test;
private int runRate;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//User pressed a notifiacition button
Log.w(TAG, "onReceive: Recived" );
}
// constructor
public MyReceiver(){
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
public static Timer getTimer() {
return timer;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onCreate() {
Toast.makeText(this, "Service has been started!", Toast.LENGTH_SHORT).show();
context = getApplicationContext();
timer = new Timer();
runRate = 0;
builder = new NotificationCompat.Builder(context)
.setSmallIcon(android.R.drawable.ic_dialog_alert)
.setContentTitle("KolBoost")
.setContentText("Arkaplan servisi etkinleştirildi!")
.setAutoCancel(false)
.setPriority(NotificationCompat.PRIORITY_HIGH);
MyReceiver myReceiver = new MyReceiver();
IntentFilter filter = new IntentFilter();
Intent close = new Intent(getBaseContext(), BackgroundService.class);
close.setAction("CLOSE_SERVICE");
PendingIntent closeServiceIntent = PendingIntent.getBroadcast(getBaseContext(), 0, close, 0);
Intent i2 = new Intent(getBaseContext(), BackgroundService.class);
i2.setAction("BOOST_MEMORY");
PendingIntent boostIntent = PendingIntent.getBroadcast(getBaseContext(), 0, i2, 0);
Intent launch = new Intent(getBaseContext(),BackgroundService.class);
launch.setAction("OPEN_MANAGER");
PendingIntent contentIntent = PendingIntent.getBroadcast(getBaseContext(), 0, launch, 0);
builder.setContentIntent(contentIntent);
builder.addAction(0, "Clear Memory", boostIntent);
builder.addAction(0, "Exit", closeServiceIntent);
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(getBaseContext(), MainActivity.class);
test = PendingIntent.getActivity(getBaseContext(), NOTIFICATION_ID, notificationIntent, PendingIntent.FLAG_NO_CREATE);
//I'm adding actions to intentFilter.
filter.addAction(close.getAction());
filter.addAction(i2.getAction());
filter.addAction(launch.getAction());
//Registering Receiver with intentFilter
registerReceiver(myReceiver,filter);
super.onCreate();
}
#Override
public void onDestroy() {
timer.cancel();
notificationManager.cancelAll();
Log.d(TAG, "onDestroy: Destroyed");
super.onDestroy();
}
}
So, im working on making daily notifications for my app. And it works somehow, but the problem is that everytime i start the app or restart, it starts a notification randomly. Its just really frustating.
I've been going trough the code many times, and i just cant see why its happens
So here is everything that have to do with notifications
MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public NavigationView navigationView;
private NotificationManagerCompat notificationManager;
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Notifications
preferences = getSharedPreferences("shared preferences", Context.MODE_PRIVATE);
SetNotification();
}
public void SetNotification(){
if (GetNotificationsChecked()){
Intent notificationIntent =new Intent(this,Notification_Reciever.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,notificationIntent,PendingIntent.FLAG_ONE_SHOT);
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, Integer.valueOf(preferences.getString("notificationsHour", "15"))) ;
calendar.set(Calendar.MINUTE, Integer.valueOf(preferences.getString("notificationsMinute", "00"))) ;
if (manager != null) {
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY, pendingIntent);
}
}
}
public boolean GetNotificationsChecked(){
boolean i = preferences.getBoolean("notifications", true);
return i;
}
}
Notification_reciever.java
public class Notification_Reciever extends BroadcastReceiver {
private NotificationManagerCompat notificationManagerCompat;
#Override
public void onReceive(Context context, Intent intent) {
Intent activityIntent = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context,
0, activityIntent, 0);
notificationManagerCompat = NotificationManagerCompat.from(context);
Notification notification = new NotificationCompat.Builder(context,CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_face)
.setContentTitle("Your Daily Life Tip!")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_ALARM)
.setContentIntent(contentIntent)
.setStyle(new NotificationCompat.BigTextStyle()
.setSummaryText("Daily Notification"))
.setAutoCancel(true)
.setContentText(getlifetip(context))
.setColor(Color.parseColor("#EE3D33"))
.build();
notificationManagerCompat.notify(0, notification);
}
public String getlifetip(Context context){
//gets lifetip from jsonobject
}
MyService.java
public class MyService extends Service {
SharedPreferences preferences;
public MyService(){
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
SetNotification();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null){
SetNotification();
}else Toast.makeText(this, "Intent was null", Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags,startId);
}
public void SetNotification(){
preferences = getSharedPreferences("shared preferences", Context.MODE_PRIVATE);
if (GetNotificationsChecked()){
Intent notificationIntent =new Intent(this,Notification_Reciever.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
try{
manager.cancel(pendingIntent);
}catch (Exception ignored){}
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, Integer.valueOf(preferences.getString("notificationsHour", "15"))) ;
calendar.set(Calendar.MINUTE, Integer.valueOf(preferences.getString("notificationsMinute", "00"))) ;
if (manager != null) {
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY, pendingIntent);
}
}
}
public boolean GetNotificationsChecked(){
boolean i = preferences.getBoolean("notifications", true);
return i;
}
}
BootReciever.java
public class BootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context,MyService.class);
context.startService(i);
}
}
App.java
public class App extends Application {
public static final String CHANNEL_1_ID = "dailylifetip";
#Override
public void onCreate() {
super.onCreate();
CreateNotificationChannel();
}
private void CreateNotificationChannel(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel channel1 = new NotificationChannel(
CHANNEL_1_ID,
"Daily Life Tips",
NotificationManager.IMPORTANCE_HIGH
);
channel1.setDescription("This is the daily life tips channel");
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel1);
}
}
}
Manifest
<receiver android:name=".Notification_Reciever"/>
<service android:name=".MyService" android:enabled="true" android:exported="true"/>
The user selects the hour and minute of the day in an options menu, and is saved in preferences. And then should give an notification everyday on that time. And that works!. But everytime you open the app it randomly sends you a notifications, there is no errors.
I am trying to connect following MainActivity.java's buttonclick intents to a pendingIntent in my RathuMakara.java Service class. I tried to use CONSTANTS, but I was not successful. I want to add buttons to notification to control the music. So that I know, I should use pending intents, that's why I am trying to connect button click action in MainActivity.java to a pendingIntent in my RathuMakara.java Service class.
This is MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button buttonStart;
private Button buttonStop;
public static final String CHANNEL_ID = "exampleServiceChannel";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonStart = (Button) findViewById(R.id.buttonStart);
buttonStop = (Button)findViewById(R.id.buttonSop);
buttonStart.setOnClickListener(this);
buttonStop.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v == buttonStart){
startService(new Intent(this, RathuMakara.class));
buttonStart.setEnabled(false);
buttonStop.setEnabled(true);
Toast.makeText(getApplicationContext(),"Lets's Go... Collecting the Awesomeness",Toast.LENGTH_LONG).show();
}
else if (v == buttonStop){
stopService(new Intent(this, RathuMakara.class));
Toast.makeText(getApplicationContext(),"Playing Stopped",Toast.LENGTH_LONG).show();
buttonStop.setEnabled(false);
buttonStart.setEnabled(true);
}
}
}
This is RathuMakara.java
public class RathuMakara extends Service {
public static Object action;
private MediaPlayer rathu;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public int onStartCommand(Intent intent,int flags , int startID){
String url ="http://206.189.34.189:8000/rathumakara.mp3";
MediaPlayer rathu = new MediaPlayer();
rathu.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
rathu.setDataSource(url);
rathu.prepare();
rathu.start();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Bitmap icon = BitmapFactory.decodeResource(getResources(),
R.drawable.logo);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Rathu Makara FM")
.setContentText("දැන් අහන්නේ")
.setSmallIcon(R.drawable.logo)
.setLargeIcon(icon)
.setOngoing(true)
// .addAction(android.R.drawable.ic_media_play, "Play", )
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
}
catch (IOException e){
e.printStackTrace();
}catch (IllegalArgumentException e){
e.printStackTrace();
}catch (SecurityException e){
e.printStackTrace();
}catch (IllegalStateException e){
e.printStackTrace();
}
return START_NOT_STICKY;
}
#Override
public void onDestroy(){
rathu.stop();
}
}
This is Rathu.java where I created the Notification channel
package com.example.yomal.rathumakarafm;
import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
public class Rathu extends Application {
public static final String CHANNEL_ID = "exampleServiceChannel";
#Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Example Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
}
Please Help Me.Thank you
Set the notification content
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(textTitle)
.setContentText(textContent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
and add action buttons
Intent snoozeIntent = new Intent(this, MyBroadcastReceiver.class);
snoozeIntent.setAction(ACTION_SNOOZE);
snoozeIntent.putExtra(EXTRA_NOTIFICATION_ID, 0);
PendingIntent snoozePendingIntent =
PendingIntent.getBroadcast(this, 0, snoozeIntent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.addAction(R.drawable.ic_snooze, getString(R.string.snooze),
snoozePendingIntent);