Notification
使用步驟
第一步:獲取系統服務
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
第二步:創建Notification
創建方法一:使用遠程View
Notification noti = new Notification();
RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.通知布局文件);
noti.contentView = remoteViews;
創建方法二:Notification.Builder
Notification noti = new NotificationCompat.Builder(this)
.setContentTitle("標題")
.setContentText("content")
.setSubText("subText")
.setSmallIcon(R.mipmap.圖片)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.圖片))
.setVibrate(new long[]{300,300,300,300})//震動
.setAutoCancel(true)
.setLights(0ffff0000,1000,1000)
.build();
設置通知不能被取消:
mNotification.flags |= Notification.FLAG_NO_CLEAR;
方式二使用自定義布局:.setContent(remoteView)
消息的其他設置
大視圖通知:
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
mNotification.bigContentView = remoteViews;
}
flags:
// 設置flags
notification.flags |= Notification.FLAG_NO_CLEAR;
// 取消flags
notification.flags &= ~Notification.FLAG_NO_CLEAR;
// 判斷是否設置了
if ((notification.flags & Notification.FLAG_NO_CLEAR) != 0) {
}
設置屬性有兩種方式:1. 直接用相應的方法。 2. 通過flags(有些屬性只能通過flags)
PendingIntent使用
views.setOnClickPendingIntent(R.id.play, PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CUTTENT))
第三步:發送消息
manager.notify(0,noti); //參數1:標識 參數2:消息對象
擴展
activity的onNewIntent
方法
activity中的protected void onNewIntent(Intent intent)
方法是在活動假啟動的時候執行的。
當通知調用已經在任務棧頂的活動的時候,在這個方法內執行對通知的修改
@Override
protected void onNewIntent(Intent intent) {
Log.d("Intent", "onNewIntent--------------");
super.onNewIntent(intent);
String text = intent.getStringExtra("text");
Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT).show();
// 修改通知狀態
if (mNotification != null) {
mNotification.contentView.setImageViewResource(R.id.noti_play, android.R.drawable.ic_media_pause);
// 重新發送通知,并覆蓋原來的通知
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotification.defaults &= ~Notification.DEFAULT_VIBRATE; // 關閉震動
manager.notify(0, mNotification);
}
}
RemoteView
提供了一組基礎的操作用于跨進程更新它的界面,在android中的使用場景是通知欄和桌面小部件
作用:自定義通知欄和桌面小部件
構造方法
RemoteViews(String packageName, int layoutId) // getPackageName()
RemoteViews(RemoteViews landscape, RemoteViews portrait)
RemoteViews(Parcel parcel)
點擊事件
需要使用pendingIntent
remoteView.setOnClickPendingIntent(int viewId, PendingIntent pendingIntent)
參數1:遠程控件布局中的子控件的id
,
桌面小部件:AppWidgetProvider
1定義小部件的界面 在res/layout下創建xml
2定義小部件的配置信息 在res/xml下創建xml文件 四個主要參數
initialLayout 桌面小工具使用的初始化布局
minHeight minWidth 最小寬高
updatePeriodMillis 小部件自動更新周期 單位毫秒
3.定義小部件的實現類 extends AppWidgetProvider
onReceive onUpdate onWidgetUpdate onEnable onDisable onDeleted onReceive;
4.清單文件中聲明小部件
PendingIntent
等待意圖
pendingIntent表示在這個意圖會在不確定的時候發生其他功能和Intent一樣。