簡介
最近在看7.0的一些新特性,記錄下小知識(shí)方便之后使用。今天要說的就是狀態(tài)欄通知可直接回復(fù)的功能。(一定記得是7.0的新特性,在低版本上是不支持的)先來看效果圖。

notifition.gif
步驟
- 創(chuàng)建一個(gè)RemoteInput
- 創(chuàng)建一個(gè)PendingIntent, 這個(gè)PendingIntent指當(dāng)我們點(diǎn)擊”發(fā)送”的時(shí)候調(diào)用什么
- 創(chuàng)建一個(gè)直接回復(fù)的Action
- 創(chuàng)建notification
- 發(fā)送通知
- 拿到回復(fù)的內(nèi)容
- 處理
實(shí)現(xiàn)
- 創(chuàng)建一個(gè)RemoteInput
RemoteInput remoteInput = new RemoteInput.Builder(RESULT_KEY).setLabel("回復(fù)通知").build();
其中RESULT_KEY是獲取回復(fù)的內(nèi)容,setLabel設(shè)置的值就是EditText的hint值
- 創(chuàng)建一個(gè)PendingIntent。(這個(gè)就不過多介紹了)
Intent intent = new Intent(this, SendService.class);
PendingIntent pendingIntent = PendingIntent.getService(this,1,intent,PendingIntent.FLAG_CANCEL_CURRENT);
- 創(chuàng)建可回復(fù)的Action
NotificationCompat.Action action =
new NotificationCompat.Action.Builder(R.mipmap.ic_launcher,"回復(fù)",pendingIntent).addRemoteInput(remoteInput).build();
其中這個(gè)Builder需要傳遞四個(gè)參數(shù),第一個(gè)就是logo圖片,第二個(gè)類似于標(biāo)簽我們要點(diǎn)擊的。第三個(gè)就是要做的動(dòng)作intent.最后把我們創(chuàng)建的remoteInput加入進(jìn)來。
- 創(chuàng)建notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("請(qǐng)問需要銀行貸款嗎?")
.setContentText("您好,我是XX銀行的XX經(jīng)理, 請(qǐng)問你需要辦理銀行貸款嗎?")
.setColor(Color.CYAN)
.setPriority(Notification.PRIORITY_MAX) // 設(shè)置優(yōu)先級(jí)為Max,則為懸浮通知
.addAction(action) // 設(shè)置回復(fù)action
.setAutoCancel(true)
.setWhen(System.currentTimeMillis())
.setDefaults(Notification.DEFAULT_ALL) // 想要懸浮出來, 這里必須要設(shè)置
.setCategory(Notification.CATEGORY_MESSAGE);
- 發(fā)送通知
NotificationManager nm = getSystemService(NotificationManager.class);
Notification notification = buildNotification();
nm.notify(NOTIFICATION_ID,notification);
- 拿到回復(fù)的內(nèi)容
Bundle resultsFromIntent = RemoteInput.getResultsFromIntent(intent);
//根據(jù)key拿回復(fù)的內(nèi)容
if (null!=resultsFromIntent){
String resultString = resultsFromIntent.getString(MainActivity.RESULT_KEY);
//處理回復(fù)內(nèi)容
reply(resultString);
}
- 處理
private void reply(final String resultString) {
new Thread(new Runnable() {
@Override
public void run() {
SystemClock.sleep(1000);
Logger.e(SendService.class.getSimpleName(),resultString);
onReply();
}
}).start();
}
@TargetApi(Build.VERSION_CODES.M)
private void onReply() {
final NotificationManager nm = getSystemService(NotificationManager.class);
final Handler handler = new Handler(getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
// 更新通知為“回復(fù)成功”
Notification notification = new NotificationCompat.Builder(SendService.this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText("回復(fù)成功")
.build();
nm.notify(MainActivity.NOTIFICATION_ID, notification);
}
});
// 最后將通知取消
handler.postDelayed(new Runnable() {
@Override
public void run() {
nm.cancel(MainActivity.NOTIFICATION_ID);
}
}, 2000);
}