Notification範例

YH Lin
Dec 19, 2020

--

這個例子來利用Notification來示範通知,

首先在layout 中配置三顆按鈕

再回到MainActivity中來實作這三顆按鈕

首先在onCreate()中先宣告一個NotificationManager 的變數mgr

mgr = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

因為在API26以上的notification都要使用NotificationChannel

因此在onCreate中還要加上

if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O)
{
NotificationChannel notificationChannel = new NotificationChannel("YH","custom",NotificationManager.IMPORTANCE_HIGH);
mgr.createNotificationChannel(notificationChannel);
}

在第一顆按鈕中,只是單純的秀出文字

先宣告一個NotificationCompat.Builder 的變數builder,設定ContentTitle,ContextText()

再利用mgr.notify 通知訊息發送

public void Test1(View view) {
builder = new NotificationCompat.Builder(this,CHANNEL_ID);
builder.setContentTitle("重要通知").setContentText("通知內容")
.setSmallIcon(R.drawable.ic_stat_name)
;

mgr.notify(1,builder.build());
}

第二顆按鈕,我們加上一個largeIcon

Bitmap largeIcon = BitmapFactory.decodeResource(getResources(),R.mipmap.yh);
builder = new NotificationCompat.Builder(this,CHANNEL_ID);
builder.setContentTitle("重要通知")
.setContentText("通知內容")
.setSmallIcon(R.drawable.ic_stat_name)
.setLargeIcon(largeIcon)
.setSubText("Sub Text")
.setTicker("Ticker");


mgr.notify(2,builder.build());

第三顆按鈕

設定 Intent resultIntent = new Intent(this,ResultActivit.class);

排程TaskStackBuilder stackBuilder

TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ResultActivit.class);
stackBuilder.addNextIntent(resultIntent);

設定resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);

public void Test3(View view) {
Intent resultIntent = new Intent(this,ResultActivit.class);
String title = "Hello Jacky";
String content = "This is a notification";
Email email = new Email(title,content);
Bundle bundle = new Bundle();
bundle.putSerializable("email",email);
resultIntent.putExtras(bundle);


TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ResultActivit.class);
stackBuilder.addNextIntent(resultIntent);

PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);

Bitmap largeIcon = BitmapFactory.decodeResource(getResources(),R.mipmap.yh);
builder = new NotificationCompat.Builder(this);
builder.setContentTitle("重要通知")
.setContentText("通知內容")
.setSmallIcon(R.drawable.ic_stat_name)
.setLargeIcon(largeIcon)
.setSubText("Sub Text")
.setChannelId("YH")
.setContentIntent(resultPendingIntent)
.setTicker("Ticker");


mgr.notify(3,builder.build());

}

MainActivity 添加

<activity android:name=".ResultActivit"

android:parentActivityName=".MainActivity"></activity>

--

--

No responses yet