Android鬧鐘 AlarmManager的使用和通知的使用
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TimePicker;
public class AlarmActivity extends Activity {
private static final String TAG = "AlarmActivity";
AlarmManager alarmManager;
Calendar calendar = Calendar.getInstance(Locale.CHINESE);
Button setTime;
Button setRing;
Button setOver;
Uri ringUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
setTime = (Button) findViewById(R.id.setTime);
setRing = (Button) findViewById(R.id.setRing);
setOver = (Button) findViewById(R.id.setOver);
//setTime();
//setRingtone();
setTimeAndRing();
}
private void setTimeAndRing(){
setTime.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
setTime();
}
});
setRing.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
setRingtone();
}
});
setOver.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
setAlarm(calendar);
}
});
}
//啟動鬧玲,設定鬧玲
private void setAlarm(Calendar calendar){
Intent intent = new Intent();
intent.setClass(this, AlarmBroadcastReceiver.class);
intent.putExtra("msg", "Get up!Get up!");
intent.putExtra("ringURI", ringUri.toString());
Log.d(TAG, ringUri.toString());
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(), pendingIntent);
}
//設定時間
private void setTime(){
Date date = new Date();
calendar.setTime(date);
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
new TimePickerDialog(this, new OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int hour, int minute) {
calendar.set(Calendar.HOUR,hour);
calendar.set(Calendar.MINUTE,minute);
}
}, hour, minute, true).show();
}
//設定鬧玲鈴聲
private void setRingtone(){
Intent intent = new Intent();
intent.setAction(RingtoneManager.ACTION_RINGTONE_PICKER);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, false);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "設定鬧玲鈴聲");
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_ALL);
Uri pickedUri = RingtoneManager.getActualDefaultRingtoneUri(this,RingtoneManager.TYPE_ALARM);
if (pickedUri!=null) {
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI,pickedUri);
ringUri = pickedUri;
}
startActivityForResult(intent, 1);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode!=RESULT_OK) {
return;
}
switch (requestCode) {
case 1:
//獲取選中的鈴聲的URI
Uri pickedURI = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
Log.i(TAG,pickedURI.toString());
RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM, pickedURI);
getName(RingtoneManager.TYPE_ALARM);
break;
default:
break;
}
}
private void getName(int type){
Uri pickedUri = RingtoneManager.getActualDefaultRingtoneUri(this, type);
Log.i(TAG,pickedUri.toString());
Cursor cursor = this.getContentResolver().query(pickedUri, new String[]{MediaStore.Audio.Media.TITLE}, null, null, null);
if (cursor!=null) {
if (cursor.moveToFirst()) {
String ring_name = cursor.getString(0);
Log.i(TAG,ring_name);
String[] c = cursor.getColumnNames();
for (String string : c) {
Log.i(TAG,string);
}
}
cursor.close();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.alarm, menu);
return true;
}
}
佈局檔案
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button android:id="@+id/setTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="設定時間"/>
<Button android:id="@+id/setRing"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/setTime"
android:text="設定鈴聲"/>
<Button android:id="@+id/setOver"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/setRing"
android:text="設定完成"/>
</RelativeLayout>
廣播接收鬧鈴資訊:
package com.zking.myalarm;
import java.io.IOException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.util.Log;
import android.widget.Toast;
public class AlarmBroadcastReceiver extends BroadcastReceiver {
Uri ringUri;
@Override
public void onReceive(Context context, Intent intent) {
String msg = intent.getStringExtra("msg");
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
MediaPlayer mp = new MediaPlayer();
String uri = intent.getStringExtra("ringURI");
if (uri!=null) {
ringUri = Uri.parse(uri);
Log.d("AlarmActivity", ringUri.toString());
}
try {
mp.setDataSource(context, ringUri);
mp.prepare();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
}
}
在manifest檔案中註冊廣播
<receiver android:name="com.zking.myalarm.AlarmBroadcastReceiver"></receiver>
功能作用
1.顯示接收到短訊息、即使訊息等資訊 (如QQ、微信、新浪、簡訊)
2.顯示客戶端的推送訊息(如有新版本釋出,廣告,推薦新聞等)
3.顯示正在進行的事物(例如:後臺執行的程式)(如音樂播放器、版本更新時候的下載進度等)
元素:
1. 標題 Title/Name
2. 大圖示 Icon/Photo
3. 內容文字
4. 內容資訊 MESSAGE
5. 小圖示 Secondary Icon
6. 通知的時間 Timestamp,預設為系統發出通知的時間,也可通過setWhen()來設定
狀態通知欄主要涉及到2個類: Notification 和 NotificationManager
Notification為通知資訊類,它裡面對應了通知欄的各個屬性
NotificationManager : 是狀態欄通知的管理類,負責發通知、清除通知等操作。
注意:NotificationManager 是一個系統Service,所以必須通過 getSystemService(NOTIFICATION_SERVICE)方法來獲取,方法如下。
第一步:獲取狀態通知欄管理:
- NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
第二步:例項化通知欄構造器NotificationCompat.Builder:
- NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
第三步:對Builder進行配置:
mBuilder.setContentTitle("測試標題")//設定通知欄標題- .setContentText("測試內容") /<span style="font-family: Arial;">/設定通知欄顯示內容</span>
- .setContentIntent(getDefalutIntent(Notification.FLAG_AUTO_CANCEL)) //設定通知欄點選意圖
- // .setNumber(number) //設定通知集合的數量
- .setTicker("測試通知來啦") //通知首次出現在通知欄,帶上升動畫效果的
- .setWhen(System.currentTimeMillis())//通知產生的時間,會在通知資訊裡顯示,一般是系統獲取到的時間
- .setPriority(Notification.PRIORITY_DEFAULT) //設定該通知優先順序
- // .setAutoCancel(true)//設定這個標誌當用戶單擊面板就可以讓通知將自動取消
- .setOngoing(false)//ture,設定他為一個正在進行的通知。他們通常是用來表示一個後臺任務,使用者積極參與(如播放音樂)或以某種方式正在等待,因此佔用裝置(如一個檔案下載,同步操作,主動網路連線)
- .setDefaults(Notification.DEFAULT_VIBRATE)//向通知新增聲音、閃燈和振動效果的最簡單、最一致的方式是使用當前的使用者預設設定,使用defaults屬性,可以組合
- //Notification.DEFAULT_ALL Notification.DEFAULT_SOUND 新增聲音 // requires VIBRATE permission
- .setSmallIcon(R.drawable.ic_launcher);//設定通知小ICON
第一步:獲取狀態通知欄管理:
- NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
第二步:例項化通知欄構造器NotificationCompat.Builder:
- NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
第三步:對Builder進行配置:
- mBuilder.setContentTitle("測試標題")//設定通知欄標題
- .setContentText("測試內容") /<span style="font-family: Arial;">/設定通知欄顯示內容</span>
- .setContentIntent(getDefalutIntent(Notification.FLAG_AUTO_CANCEL)) //設定通知欄點選意圖
- // .setNumber(number) //設定通知集合的數量
- .setTicker("測試通知來啦") //通知首次出現在通知欄,帶上升動畫效果的
- .setWhen(System.currentTimeMillis())//通知產生的時間,會在通知資訊裡顯示,一般是系統獲取到的時間
- .setPriority(Notification.PRIORITY_DEFAULT) //設定該通知優先順序
- // .setAutoCancel(true)//設定這個標誌當用戶單擊面板就可以讓通知將自動取消
- .setOngoing(false)//ture,設定他為一個正在進行的通知。他們通常是用來表示一個後臺任務,使用者積極參與(如播放音樂)或以某種方式正在等待,因此佔用裝置(如一個檔案下載,同步操作,主動網路連線)
- .setDefaults(Notification.DEFAULT_VIBRATE)//向通知新增聲音、閃燈和振動效果的最簡單、最一致的方式是使用當前的使用者預設設定,使用defaults屬性,可以組合
- //Notification.DEFAULT_ALL Notification.DEFAULT_SOUND 新增聲音 // requires VIBRATE permission
- .setSmallIcon(R.drawable.ic_launcher);//設定通知小ICON
- /**
- * 帶按鈕的通知欄
- */
- publicvoid showButtonNotify(){
- NotificationCompat.Builder mBuilder = new Builder(this);
- RemoteViews mRemoteViews = new RemoteViews(getPackageName(), R.layout.view_custom_button);
- mRemoteViews.setImageViewResource(R.id.custom_song_icon, R.drawable.sing_icon);
- //API3.0 以上的時候顯示按鈕,否則消失
- mRemoteViews.setTextViewText(R.id.tv_custom_song_singer, "周杰倫");
- mRemoteViews.setTextViewText(R.id.tv_custom_song_name, "七里香");
- //如果版本號低於(3。0),那麼不顯示按鈕
- if(BaseTools.getSystemVersion() <= 9){
- mRemoteViews.setViewVisibility(R.id.ll_custom_button, View.GONE);
- }else{
- mRemoteViews.setViewVisibility(R.id.ll_custom_button, View.VISIBLE);
- }
- //
- if(isPlay){
- mRemoteViews.setImageViewResource(R.id.btn_custom_play, R.drawable.btn_pause);
- }else{
- mRemoteViews.setImageViewResource(R.id.btn_custom_play, R.drawable.btn_play);
- }
- //點選的事件處理
- Intent buttonIntent = new Intent(ACTION_BUTTON);
- /* 上一首按鈕 */
- buttonIntent.putExtra(INTENT_BUTTONID_TAG, BUTTON_PREV_ID);
- //這裡加了廣播,所及INTENT的必須用getBroadcast方法
- PendingIntent intent_prev = PendingIntent.getBroadcast(this, 1, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
- mRemoteViews.setOnClickPendingIntent(R.id.btn_custom_prev, intent_prev);
- /* 播放/暫停 按鈕 */
- buttonIntent.putExtra(INTENT_BUTTONID_TAG, BUTTON_PALY_ID);
- PendingIntent intent_paly = PendingIntent.getBroadcast(this, 2, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
- mRemoteViews.setOnClickPendingIntent(R.id.btn_custom_play, intent_paly);
- /* 下一首 按鈕 */
- buttonIntent.putExtra(INTENT_BUTTONID_TAG, BUTTON_NEXT_ID);
- PendingIntent intent_next = PendingIntent.getBroadcast(this, 3, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
- mRemoteViews.setOnClickPendingIntent(R.id.btn_custom_next, intent_next);
- mBuilder.setContent(mRemoteViews)
- .setContentIntent(getDefalutIntent(Notification.FLAG_ONGOING_EVENT))
- .setWhen(System.currentTimeMillis())// 通知產生的時間,會在通知資訊裡顯示
- .setTicker("正在播放")
- .setPriority(Notification.PRIORITY_DEFAULT)// 設定該通知優先順序
- .setOngoing(true)
- .setSmallIcon(R.drawable.sing_icon);
- Notification notify = mBuilder.build();
- notify.flags = Notification.FLAG_ONGOING_EVENT;
- mNotificationManager.notify(notifyId, notify);
- }