Android Notification主要用來提醒新訊息、提示訊息等
一般訊息通知不需要存取權限,但如果要震動的話,就需要在Manifest允許存取android.permission.VIBRATE這個權限
執行結果:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 自訂常數,代表通知訊息的ID | |
private final static int NOTI_ID = 0; | |
private NotificationManager nfm1; | |
Button btn_ok,btn_cancel; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
//呼叫Activity.getSystemService()取得NotificationManager物件 | |
nfm1 = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); | |
findView(); | |
} | |
private void findView() { | |
btn_ok = (Button) findViewById(R.id.btn_ok); | |
btn_ok.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View view) { | |
showNotification(); | |
} | |
}); | |
btn_cancel = (Button) findViewById(R.id.btn_cancel); | |
btn_cancel.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View view) { | |
nfm1.cancel(NOTI_ID); | |
} | |
}); | |
} | |
private void showNotification() { | |
Intent intent = new Intent(this, Notification.class); | |
PendingIntent pit = PendingIntent.getActivity(this,0,intent,0); | |
// 利用Notification.Builder建立Notification物件 | |
Notification no = new Notification.Builder(this) | |
// 通知訊息在狀態列的文字 | |
.setTicker("通知訊息列") | |
// 通知訊息在訊息面板的標題 | |
.setContentTitle("約會") | |
// 通知訊息在訊息面板的內容文字 | |
.setContentText("重要約會") | |
// 通知訊息的圖示 | |
.setSmallIcon(android.R.drawable.ic_menu_info_details) | |
// 點擊訊息面版後會自動移除狀態列上的通知訊息 | |
.setAutoCancel(true) | |
// 等待使用者向下撥動狀態列後點擊訊息面版上的訊息才會開啟指定Activity的畫面 | |
.setContentIntent(pit) | |
// API Level 16開始支援build(),並建議不要使用getNotification() | |
// .getNotification(); | |
.build(); | |
// 呼叫notify()發出通知訊息 | |
nfm1.notify(NOTI_ID,no); | |
//震動,須權限 | |
Vibrator vb1 = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE); | |
vb1.vibrate(1000); | |
} |
一般訊息通知不需要存取權限,但如果要震動的話,就需要在Manifest允許存取android.permission.VIBRATE這個權限
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<application | |
android:allowBackup="true" | |
android:icon="@mipmap/ic_launcher" | |
android:label="@string/app_name" | |
android:supportsRtl="true" | |
android:theme="@style/AppTheme"> | |
<activity android:name=".MainActivity"> | |
<intent-filter> | |
<action android:name="android.intent.action.MAIN" /> | |
<category android:name="android.intent.category.LAUNCHER" /> | |
</intent-filter> | |
</activity> | |
</application> | |
<uses-permission android:name="android.permission.VIBRATE"/> |
執行結果:
留言
張貼留言