notification(MainActivity.this, "提示 Title", "提示 Message");
private void notification(Context context, String title, String message){
final int notifyID = 1; // 通知的識別號碼
final NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
final Notification notification = new Notification
.Builder(context)
.setSmallIcon(R.drawable.ic_launcher) // 24 x 24 px
.setContentTitle(title)
.setContentText(message)
.build();
notificationManager.notify(notifyID, notification);
}
2 . 持續型( 常駐 )
private NotificationManager manager;
private Bitmap icon;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
icon = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
.
.
.
// 顯示客製化視窗
private void showCustomView() {
// 控制面板
RemoteViews remoteViews = new RemoteViews(getPackageName(),
R.layout.notification_design);
// 被觸發後發送對應的廣播
Intent intent = new Intent();
intent.setAction("i_am_hungry");
intent.putExtra("HELLO", "7");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
// 面板內的元件設置接收器(原因 : RemoteView沒有定義此方法)
remoteViews.setOnClickPendingIntent(R.id.imageView1, pendingIntent);
// 建立相關元件
NotificationCompat.Builder builder = new Builder(this);
builder.setContent(remoteViews)
// 狀態列的Icon
.setSmallIcon(R.drawable.music_icon)
// 提醒內的大型Icon
.setLargeIcon(icon)
// 是否持續顯示提醒
.setOngoing(true)
// 狀態列的條碼燈( 只會出現一次 )
.setTicker("123456");
manager.notify(7, builder.build());
}
如果要取消常駐型提醒
manager.cancelAll();
public class Rreciver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle0311 = intent.getExtras();
if(bundle0311!= null){
String aaa = bundle0311.getString("HELLO");
NotificationManager manager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
// 清除所以有的 Notification
// manager.cancelAll();
// 清除指定的 Notification
manager.cancel(Integer.parseInt(aaa));
}
}
}
記住,記得一定要加上監聽
<receiver android:name="Rreciver">
<intent-filter>
<action android:name="i_am_hungry" />
</intent-filter>
</receiver>
參考資料 : android notification 總結
參考資料 : Android--通知之Notification
參考資料 : Android 如何顯示通知訊息(Notifications)?
歡迎轉載,請註明出處。
沒有留言:
張貼留言