push notification in service class android studio code example

Example 1: android create notification

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(yourContext.getApplicationContext(), "notify_001");
Intent ii = new Intent(yourContext.getApplicationContext(), YourMainActivty.class);
PendingIntent pendingIntent = PendingIntent.getActivity(yourContext, 0, ii, 0);

NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
bigText.bigText(notificationsTextDetailMode); //detail mode is the "expanded" notification
bigText.setBigContentTitle(notificationTitleDetailMode);
bigText.setSummaryText(usuallyAppVersionOrNumberOfNotifications); //small text under notification

mBuilder.setContentIntent(pendingIntent);
mBuilder.setSmallIcon(R.mipmap.ic_launcher); //notification icon
mBuilder.setContentTitle(notificationTitle); //main title
mBuilder.setContentText(notificationText); //main text when you "haven't expanded" the notification yet
mBuilder.setPriority(Notification.PRIORITY_MAX);
mBuilder.setStyle(bigText);

NotificationManager mNotificationManager = (NotificationManager) yourContext.getSystemService(Context.NOTIFICATION_SERVICE);

NotificationChannel channel = new NotificationChannel("notify_001",
                                                      "Channel human readable title",
                                                      NotificationManager.IMPORTANCE_DEFAULT);
if (mNotificationManager != null) {
  mNotificationManager.createNotificationChannel(channel);
}

if (mNotificationManager != null) {
  mNotificationManager.notify(0, mBuilder.build());
}

Example 2: android notification addaction example

public class ActionReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    //Toast.makeText(context,"recieved",Toast.LENGTH_SHORT).show();

    String action=intent.getStringExtra("action");
    if(action.equals("action1")){
        performAction1();
    }
    else if(action.equals("action2")){
        performAction2();

    }
    //This is used to close the notification tray
    Intent it = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
    context.sendBroadcast(it);
}

public void performAction1(){

}

public void performAction2(){

}
}

Tags:

Java Example