Android - Notification 使用
Android L ; Android Studio 14
使用過程
- NotificationManager - 用于提示的管理,例如發送、取消
- NotificationCompat.Builder - Builder模式構造notification;可參考《Effective Java》第2條
- Notification - 提示,能夠顯示在狀态欄和下拉欄上;構造執行個體能設定flags
NotificationDemo
本例意在記錄android notification的使用方法。
界面中放置了很多個按鈕,每個按鈕發送的提示并不完全相同。流程都一樣。
設定一個NotificationManager,
使用NotificationCompat.Builder來建立Notification;點選按鈕時NotificationManager.notify發送提示
其中有接收廣播發送notification的例子
build.gradle
部分代碼,最低API 19:
android {
compileSdkVersion 23
buildToolsVersion "23.0.1"
defaultConfig {
applicationId "com.rust.rustnotifydemo"
minSdkVersion 19
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
主要代碼
MainActivity.java
:
package com.rust.rustnotifydemo;
import android.app.NotificationManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v4.app.NotificationCompat;
import android.support.v7.widget.Toolbar;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
class notifyBroadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
NotificationManager nMgr =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent goHome = new Intent(Intent.ACTION_MAIN);
goHome.addCategory(Intent.CATEGORY_HOME);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.signal_horn_26px)
.setContentText("點選傳回桌面")
.setContentTitle("Go home")
.setTicker("來自廣播的提示")
.setContentIntent(PendingIntent.getActivity(context, 0, goHome, 0));
Notification notificationBroadcast = builder.build();
notificationBroadcast.flags |= Notification.FLAG_AUTO_CANCEL;
nMgr.notify(002, notificationBroadcast);/* id相同;此提示與 Notification 2 隻能顯示一個 */
}
}
public class MainActivity extends AppCompatActivity {
public static final String BroadcastNotify = "com.rust.notify.broadcast";
private EditText editContent;
private Button sendNotification;
private Button notifyButton1;
private Button notifyButton2;
private Button cleanButton;
private Button notifyBroadcast;
private int notificationId = 001;
private BroadcastReceiver notifyReceiver;
private InputMethodManager inputMgr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
IntentFilter filter = new IntentFilter(BroadcastNotify);
notifyReceiver = new notifyBroadcast();
registerReceiver(notifyReceiver, filter);
/* get the widgets */
editContent = (EditText) findViewById(R.id.et_content);
sendNotification = (Button) findViewById(R.id.btn_send_content);
notifyButton1 = (Button) findViewById(R.id.btn_notify_1);
notifyButton2 = (Button) findViewById(R.id.btn_notify_2);
notifyBroadcast = (Button) findViewById(R.id.btn_notify_broadcast);
cleanButton = (Button) findViewById(R.id.btn_clean_notification);
/* 構造一個Bitmap,顯示在下拉欄中 */
final Bitmap notifyBitmapTrain = BitmapFactory
.decodeResource(this.getResources(), R.drawable.train);
/* 管理器-用來發送notification */
final NotificationManager nMgr =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notifyButton1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(getApplicationContext(), MainActivity.class);
NotificationCompat.Builder nBuilder1 =
new NotificationCompat.Builder(getApplicationContext())
.setTicker("Notify 1 ! ")/* 狀态欄顯示的提示語 */
.setContentText("Go back to RustNotifyDemo")/* 下拉欄中的内容 */
.setSmallIcon(R.drawable.notification_small_icon_24)/* 狀态欄圖檔 */
.setLargeIcon(notifyBitmapTrain)/* 下拉欄内容顯示的圖檔 */
.setContentTitle("notifyButton1 title")/* 下拉欄顯示的标題 */
.setContentIntent(PendingIntent
.getActivity(getApplicationContext(), 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT));
/* 直接使用PendingIntent.getActivity();不需要執行個體 */
/* getActivity() 是 static 方法*/
Notification n = nBuilder1.build();/* 直接建立Notification */
n.flags |= Notification.FLAG_AUTO_CANCEL;/* 點選後觸發時間,提示自動消失 */
nMgr.notify(notificationId, n);
}
});
notifyButton2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
NotificationCompat.Builder nBuilder2 =
new NotificationCompat.Builder(getApplicationContext())
.setTicker("Notify 2 ! ")/* 狀态欄顯示的提示語 */
.setContentText("Notification 2 content")/* 下拉欄中的内容 */
.setSmallIcon(R.drawable.floppy_16px)/* 狀态欄圖檔 */
.setLargeIcon(notifyBitmapTrain)/* 下拉欄内容顯示的圖檔 */
.setContentTitle("title2");/* 下拉欄顯示的标題 */
nMgr.notify(notificationId + 1, nBuilder2.build());
/* 兩個id一樣的notification不能同時顯示,會被新的提示替換掉 */
}
});
sendNotification.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String content = editContent.getText().toString();
if (content.equals("")) {
content = "U input nothing";
}
NotificationCompat.Builder contentBuilder =
new NotificationCompat.Builder(getApplicationContext())
.setTicker(content)/* 狀态欄顯示的提示語 */
.setContentText("I can auto cancel")/* 下拉欄中的内容 */
.setSmallIcon(R.drawable.rain_32px)/* 狀态欄圖檔 */
.setLargeIcon(notifyBitmapTrain)/* 下拉欄内容顯示的圖檔 */
.setContentTitle("Edit title");/* 下拉欄顯示的标題 */
Notification n = contentBuilder.build();
nMgr.notify(notificationId + 2, n);
}
});
notifyBroadcast.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(BroadcastNotify);
sendBroadcast(i);
}
});
cleanButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
nMgr.cancel(notificationId);/* 根據id,撤銷notification */
}
});
}
/**
* 點選空白處,軟鍵盤自動消失
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null) {
inputMgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMgr.hideSoftInputFromWindow(
getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
return super.onTouchEvent(event);
}
@Override
protected void onDestroy() {
unregisterReceiver(notifyReceiver);
super.onDestroy();
}
}
MainActivity launchMode="singleInstance";便于傳回 activity
圖檔資源都是網絡下載下傳