2020年8月3日 星期一

Android 使用 Notification 頂部訊息 (含影片教學與專案) [android Notification top message]

1
2
3
4
5
6
    private Context cntContext;
    private static final String NOTIFICATION_CHANNEL_ID = "0920";

    public clsNotification(Context pcntContext) {
        cntContext = pcntContext;
    }





 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
    public void createNotification(String pstrTitle, String pstrMessage, int pintICONResource, Class pclsClass)
    {
        Intent ittResult = new Intent(cntContext , pclsClass);
        ittResult.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        PendingIntent pdiIntent = PendingIntent.getActivity(cntContext,0 , ittResult, PendingIntent.FLAG_UPDATE_CURRENT);


        NotificationCompat.Builder ncbBuilder = new NotificationCompat.Builder(cntContext);
        ncbBuilder.setTicker("SmallGCOk")
                .setContentTitle(pstrTitle)
                .setContentText(pstrMessage)
                .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
                .setSmallIcon(pintICONResource)
                .setContentIntent(pdiIntent);

        NotificationManager nmtManager = (NotificationManager) cntContext.getSystemService(Context.NOTIFICATION_SERVICE);

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
        {
            NotificationChannel ntcChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "SmallGCOk_CHANNEL", NotificationManager.IMPORTANCE_HIGH);
            ntcChannel.enableLights(true);
            ntcChannel.setLightColor(Color.WHITE);
            ntcChannel.enableVibration(true);
            ntcChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});

            assert nmtManager != null;
            ncbBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
            nmtManager.createNotificationChannel(ntcChannel);
        }

        assert nmtManager != null;
        nmtManager.notify(920, ncbBuilder.build());
    }


專案下載:https://ibf.tw/HFx5S

影片教學:

沒有留言:

張貼留言