MediaStore简介
(一) AlarmManager的使用机制有的称呼为全局定时器,有的称呼为闹钟,它的作用和Timer有点相似,有两种用法:
1.在指定时长后执行某项操作
2.周期性的执行某项操作
(二) AlarmManager对象配合Intent使用,可以定时的开启一个Activity,发送一个BroadCast,或者开启一个Service
第一步:
package com.geek.clock;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TimePicker;
import android.widget.Toast;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
public int hour;
public int minute;
public AlarmManager am;
PendingIntent opIntent;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
am=(AlarmManager) getSystemService(Context.ALARM_SERVICE);
}
//单次闹钟
public void single(View view){
//时间对话框
Calendar c=Calendar.getInstance();
c.setTimeInMillis(System.currentTimeMillis());
TimePickerDialog tpd=new TimePickerDialog(MainActivity.this,new MyOnTimeSetListener() , c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), true);
tpd.show();
}
//重复闹钟
public void repetition(View view){
//时间对话框(用来设置时间)
Calendar c=Calendar.getInstance();
c.setTimeInMillis(System.currentTimeMillis());
TimePickerDialog tpd=new TimePickerDialog(MainActivity.this,new MyOnTimeSetListener() , c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), true);
tpd.show();
}
//取消闹钟
public void remove(View view){
am.cancel(opIntent);
Toast.makeText(MainActivity.this, "取消成功", 1000).show();
}
//监听
public class MyOnTimeSetListener implements OnTimeSetListener{
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// TODO Auto-generated method stub
//设置闹钟
Calendar calendar=Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(calendar.MINUTE, minute);
//发送广播
Intent intent=new Intent();
intent.setAction("com.geek.phonebroadcast");
opIntent=PendingIntent.getBroadcast(MainActivity.this, 1000, intent,0);
//设置一个单次闹钟
//am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), opIntent);
//设置一个重复闹钟
am.setRepeating(
AlarmManager.RTC_WAKEUP, //提醒类型
calendar.getTimeInMillis(), //
10000, //间隔
opIntent ); //
}
}
}