Trying to build a simple notification in android

我怕爱的太早我们不能终老 提交于 2020-01-24 08:13:30

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/12850033/trying-to-build-a-simple-notification-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!