8.1 将程式運作到手機上
8.2 使用通知(Notification)
第一步,擷取通知管理器
NotificationManager manger = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new NotificationCompat.Builer(context).build();
如果是安卓8.0以上的系統,則要添加以下代碼
String channelId = "chat";
String channelName = "聊天消息";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {//
channel = new NotificationChannel(channelId,channelName,importance);//第二步
manager.createNotificationChannel(channel);//第三步
} else {
Log.d("MainActivity", "error ");
}
同時修改 Notification notification = new NotificationCompat.Builer(context, channelId)
第二步,建立一個Notification對象
Notification notification = new NotificationCompat.Builer(context)
.setContentTitle("This is content title")
.setContentText("This si content test)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.small_icon)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.large_icon))
.build();
第三步,調用NotificationManager的notify()方法
manager.notify(1, notification); 第一個參數表示第個通知的ID号,第二個參數表示Notification對象
第四步,産生點選進入活動效果
先建立一個NotificationActivity活動,
然後再,
Intent intent = new Intent(this, NotificationActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
第一個參數,表示上下文,第三個參數表示一個Intent對象,第二,四個一般傳0,0;
在原來的基礎上添加, setContentIntent(pi)
再點選會啟動intent;
第五步,點選,取消通知效果
方案一, 在基礎上添加,setAutoCanel(true)
方案二, intent活動中,onCreate添加如下代碼:
NotificationManager manaer= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.canel(1); 參數為通知的ID号
8.2.2 通知的進階技巧
.setSound(uri.fromFile(new File("/system/media/audio/ringtones/Luna.ogg")));
設定通知的聲音
setVibrate(new long[] {0,300,500,700});
振動:延遲0ms,然後振動300ms,在延遲500ms, 接着再振動700ms
還要添權重限
<uses-permission android :name=""android.permission.VIBRATE/>
setLights(color.GREEN, 5000, 1000)
設定顔色,第二,三參數表示,明,暗的時長,
如果不想設定,可以使用預設設定,如
setDefaults(NoticicationCompat.DEFAULT_ALL)
8.2.3 通知的進階功能
.setStyle("可以放很長的文本")
在通知時是可以顯示的
.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(
BitmapFactory.decodeResource(getResource(), R.drawable.big_image)))
在通知欄上顯示圖檔
.setPriority(NotificationCompat.PRIORITY_MAX)
将通知的重要程度設定到最高,手機會在任何時候顯示通知
8.3 調用攝像頭和相冊
8.4 播放多媒體檔案