8.1使用通知
當應用程序不在前臺是,通過通知向用戶發送提示消息.發送后,最上方的狀態欄會顯示通知的圖標.,下拉后可以看到詳細內容.
8.1.1通知的基本用法
通知可以由活動/服務/廣播接收器創建.
- 調用Context的getSystemService()獲得NotificationManager用于管理通知.
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
- 創建Notification對象用于儲存通知所需要的信息.三個參數分別是通知的圖標,通知的ticker內容,通知被創建的時間,單位是毫秒.
Notification notification = new Notification(R.drawable.icon, "This is ticker text",System.currentTimeMillis());
- 設定通知布局.第二個參數用于指定通知的標題內容,第三個參數用于指定通知的正文內容.
notification.setLatestEventInfo(context, "This is content title", "This is content text", null);
- 調用NotificationManager的notify()顯示通知.第一個參數是id,保證每個通知指定的id是不同的,第二個參數時Notification對象.
manager.notify(1,Notification);
示例(別信書上的...書上太老了):
public void onClick(View v){
switch (v.getId()){
case R.id.send_notice:
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification.Builder(this) .setAutoCancel(true)
.setContentTitle("title")
.setContentText("describe")
.setSmallIcon(R.mipmap.ic_launcher)
.setWhen(System.currentTimeMillis())
.build();
manager.notify(1,notification);
break;
default:
break;
}
}
- 通過PendingIntent實現通知的點擊效果.pendingIntent可以用于啟動活動,服務或發送廣播.通過getActivity()/getBroadcast()/getService().這幾個方法所接收的參數都是相同的,第一個參數依舊是 Context,不用多做解釋。第二個參數一般用不到,通常都是傳入 0 即可。第三個參數是一個 Intent 對象,我們可以通過這個對象構建出 PendingIntent 的“意圖”。第四個參數用于確定 PendingIntent 的行為,有FLAG_ONE_SHOT、 FLAG_NO_CREATE、 FLAG_CANCEL_CURRENT 和 FLAG_UPDATE_CURRENT 這四種值可選.
- FLAG_CANCEL_CURRENT:如果當前系統中已經存在一個相同的PendingIntent對象,那么就將先將已有的PendingIntent取消,然后重新生成一個PendingIntent對象。
- FLAG_NO_CREATE:如果當前系統中不存在相同的PendingIntent對象,系統將不會創建該PendingIntent對象而是直接返回null。
- FLAG_ONE_SHOT:該PendingIntent只作用一次,如果該PendingIntent對象已經觸發過一次,那么下次再獲取該PendingIntent并且再觸發時,系統將會返回一個SendIntentException,在使用這個標志的時候一定要注意哦。
- FLAG_UPDATE_CURRENT:如果系統中已存在該PendingIntent對象,那么系統將保留該PendingIntent對象,但是會使用新的Intent來更新之前PendingIntent中的Intent對象數據,例如更新Intent中的Extras。這個非常有用,例如之前提到的,我們需要在每次更新之后更新Intent中的Extras數據,達到在不同時機傳遞給MainActivity不同的參數,實現不同的效果。
示例:
Intent intent = new Intent(this,NotificationActifity.class);
PendingIntent pi = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_CANCEL_CURRENT);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification.Builder(this)
.setAutoCancel(true)
.setContentTitle("title")
.setContentText("describe")
.setContentIntent(pi)
.setSmallIcon(R.mipmap.ic_launcher)
.setWhen(System.currentTimeMillis())
.build();
manager.notify(1,notification);
8.1.2通知的高級技巧####
- Notification的sound屬性,用于通知發出是播放音頻,該屬性是一個URI對象.
Uri soundUri = Uri.fromFile(new File("/system/media/audio/ringtones/Basic_tone.ogg"));
notification.sound = soundUri;
- Notification的vibrate屬性,用于控制手機的震動.是一個長整形數組.毫秒為單位,數組下標為單數,靜止時長;下標為雙數,震動時長.
long[] vibrates = {0, 1000, 1000, 1000};
notification.vibrate = vibrates;
- Notification的ledARGB,ledOnMS,ledOffMS,flags.flags用于指定通知的一些行為,包括顯示LED.
示例(綠燈,亮一秒熄一秒):
- 使用默認設置:
notification.defaults = Notification.DEFAULT_ALL;
8.2接受和發送短信###
8.2.1接收短信
class MessageReceive extends BroadcastReceiver{
@Override
public void onReceive(Context context,Intent intent){
Bundle bundle = intent.getExtras();
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage[] messages = new SmsMessage[pdus.length];
for(int i=0;i<messages.length;i++){
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
String address = messages[0].getOriginatingAddress();
String fullMessage = "";
for(SmsMessage message : messages){
fullMessage += message.getMessageBody();
}
sender.setText(address);
content.setText(fullMessage);
}
}
注意:
Android設備接收到的SMS是以pdu形式的(protocol description unit)。所以從intent提取數據時就會遇到pdus。
8.2.2發送短信
有序廣播是可以被截斷的,而系統發出的短信廣播是一條有序廣播.先提高MessageReceive的優先級,再在onReceive()中調用abortBroadcast()中止即可.
示例:
sendFilter = new IntentFilter();
sendFilter.addAction("SENT_SMS_ACTION");
sendStatusReceiver = new SendStatusReceiver();
registerReceiver(sendStatusReceiver, sendFilter);
msgInput = (EditText) findViewById(R.id.msg_input);
send = (Button) findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SmsManager smsManager = SmsManager.getDefault();
Intent sentIntent = new Intent("SENT_SMS_ACTION");
PendingIntent pi = PendingIntent.getBroadcast(MainActivity.this, 0, sentIntent, 0); smsManager.sendTextMessage(to.getText().toString(), null, msgInput.getText().toString(), pi, null);
}
});
8.3調用攝像頭和相冊
8.3.1將程序運行到手機上
略...
8.3.1從相冊中選擇照片
略...
相信我,如果你習慣篩選自己的名字來輸出日志,千萬千萬記得把異常也用一樣的方式輸出 :)
8.4播放多媒體文件
8.4.1播放音頻
Android中播放音頻一般使用MediaPlayer實現.
常用方法:
- setDataSource():設置要播放的音頻文件的位置
- prepare():在開始播放之前調用這個方法完成準備工作
- start():開始或繼續播放音頻。
- pause(): 暫停播放音頻。
- reset(): 將 MediaPlayer 對象重置到剛剛創建的狀態。
- seekTo(): 從指定的位置開始播放音頻。
- stop(): 停止播放音頻。調用這個方法后的 MediaPlayer 對象無法再播放音頻。
- release(): 釋放掉與 MediaPlayer 對象相關的資源。
- isPlaying(): 判斷當前 MediaPlayer 是否正在播放音頻。
- getDuration(): 獲取載入的音頻文件的時長。
注意:
讀取SD卡文件需要獲取權限.
8.4.2播放視頻
Android中播放視頻一般使用VideoView實現.
- setVideoPath(): 設置要播放的視頻文件的位置。
- start(): 開始或繼續播放視頻。
- pause(): 暫停播放視頻。
- resume(): 將視頻重頭開始播放。
- seekTo(): 從指定的位置開始播放視頻。
- isPlaying(): 判斷當前是否正在播放視頻。
- getDuration(): 獲取載入的視頻文件的時長。