Trying to create a simple notification in Android

I'm trying to set a notification in my Android app that just says “It worked”, but I need my app to be compatible right down to API 1. I am really confused about how to do this though. There are old tutorials that are out of date, and there are new tutorials that do not support older API levels. In accordance with this question, https://stackoverflow.com/a/166269/2326323 should I use NotificationCompat.Builder . There is an example that I use, but I do not quite understand the code.

From this code:

Intent notificationIntent = new Intent(ctx, YourClass.class); PendingIntent contentIntent = PendingIntent.getActivity(ctx, YOUR_PI_REQ_CODE, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT); NotificationManager nm = (NotificationManager) ctx .getSystemService(Context.NOTIFICATION_SERVICE); Resources res = ctx.getResources(); Notification.Builder builder = new Notification.Builder(ctx); builder.setContentIntent(contentIntent) .setSmallIcon(R.drawable.some_img) .setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.some_big_img)) .setTicker(res.getString(R.string.your_ticker)) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setContentTitle(res.getString(R.string.your_notif_title)) .setContentText(res.getString(R.string.your_notif_text)); Notification n = builder.build(); nm.notify(YOUR_NOTIF_ID, n); 

I get red lines under: ctx , YOUR_PI_REQ_CODE and YOUR_NOTIF_ID

+4
source share
2 answers

The ctx variable is for the Android context - often this is an Activity (or actually a class that extends an Activity).

You need to study the PendingIntent class a PendingIntent to understand YOUR_PI_REQ_CODE , but you need to determine what to put here; this is your pending intent request code.

You should also examine the NotificationManager notify() method to determine what you want to use as your notification identifier.

+2
source

ctx - Context. He can convey your activity.

YOUR_PI_REQ_CODE - YOUR_PI_REQ_CODE request code. It can be any int constant.

YOUR_NOTIF_ID - notification identifier. It can be any int constant.

+2
source

Source: https://habr.com/ru/post/1439272/


All Articles