EGHDK
EGHDK

Reputation: 18130

Trying to build a simple notification in android

I'm trying to set a notification in my android app that will simply say "It worked", but I need my app to have compatibility all the way down to API 1. I'm really confused on how to do this though. There are old tutorials that are deprecated, and there are new tutorials that don't support older API levels. According to this SO question, I should use NotificationCompat.Builder. There is an example that I'm using, but I don't fully understand the code.

Out of 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

Upvotes: 4

Views: 945

Answers (2)

mah
mah

Reputation: 39837

The ctx variable is intended to be an Android context -- often an Activity (or actually a class that extends Activity).

You should do a little research on the PendingIntent class to understand YOUR_PI_REQ_CODE but you need to determine what to put here; it's your pending intent request code.

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

Upvotes: 2

vasart
vasart

Reputation: 6702

ctx is Context. It can pass instead your Activity.

YOUR_PI_REQ_CODE is PendintIntent Request Code. It can be any int constant.

YOUR_NOTIF_ID is Notification id. It can be any int constant too.

Upvotes: 2

Related Questions