AlarmManager 定时提醒

之前写了一个AlarmManager+Service的轮询Demo,今天写个AlarmManager的新用法,定时器,说白了就是设置一个闹钟。
原理:设置一个定时器,到了定是时间,系统会发出广播,我们自己接收处理就OK了。
Demo:http://download.csdn.net/detail/hello_12413/8876463
效果图:
AlarmManager 定时提醒
文章图片

以下是代码部分:
MainActivity.java:

package com.example.alarmreceiverdemo; import java.util.Calendar; import android.app.Activity; import android.app.AlarmManager; import android.app.DatePickerDialog; import android.app.DatePickerDialog.OnDateSetListener; 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.os.Handler; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.DatePicker; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; import com.example.alarmreceiverdemo.utils.DateFormatUtils; public class MainActivity extends Activity implements OnClickListener {private Button setting; private TextView time; private TextView curTime; private StringBuilder builder; private PendingIntent mTimedMessagePendingIntent = null; private AlarmManager mAlarmManager; private int timedYear; private int timedMonth; private int timedDay; private int timedHour; private int timedMinute; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); setting = (Button) findViewById(R.id.setting); time = (TextView) findViewById(R.id.time); curTime = (TextView) findViewById(R.id.cur); builder = new StringBuilder(); setting.setOnClickListener(this); handler.sendEmptyMessage(0); }// 发送定时任务 private void sendTimedMessage() { Intent intent = new Intent(this, AlarmReceiver.class); intent.setAction("alarmBroadcastReceiverAction"); mTimedMessagePendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0); // 设置定时时间 Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, timedYear); calendar.set(Calendar.MONTH, timedMonth); calendar.set(Calendar.DAY_OF_MONTH, timedDay); calendar.set(Calendar.HOUR_OF_DAY, timedHour); calendar.set(Calendar.MINUTE, timedMinute); if (calendar.getTimeInMillis() <= System.currentTimeMillis()) { Toast.makeText(this, "请重新设置时间", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "成功设置定时时间", Toast.LENGTH_SHORT).show(); mAlarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), mTimedMessagePendingIntent); } }Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { curTime.setText(DateFormatUtils.getTime()); handler.sendEmptyMessageDelayed(0, 1 * 1000); }; }; // 日期选择器监听器 OnDateSetListener dateSetListener = new OnDateSetListener() {@Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { timedYear = year; timedMonth = monthOfYear; timedDay = dayOfMonth; builder.append(year); builder.append("-"); builder.append(monthOfYear < 10 ? ("0" + monthOfYear) : monthOfYear); builder.append("-"); builder.append(dayOfMonth < 10 ? ("0" + dayOfMonth) : dayOfMonth); builder.append("\t"); showTimeDialog(); } }; // 时间选择器监听器 // 时间选择器监听器 OnTimeSetListener timeSetListener = new OnTimeSetListener() {@Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) {timedHour = hourOfDay; timedMinute = minute; builder.append(hourOfDay < 10 ? ("0" + hourOfDay) : hourOfDay); builder.append(":"); builder.append(minute < 10 ? ("0" + minute) : minute); time.setText(builder.toString()); sendTimedMessage(); } }; // 显示日期选择器 private void showDataDialog() { Calendar c = Calendar.getInstance(); DatePickerDialog datePickerDialog = new DatePickerDialog(this, dateSetListener, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)); datePickerDialog.show(); }// 显示时间选择器 public void showTimeDialog() { Calendar c = Calendar.getInstance(); TimePickerDialog timePickerDialog = new TimePickerDialog(this, timeSetListener, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), true); timePickerDialog.show(); }@Override public void onClick(View v) { switch (v.getId()) { case R.id.setting: builder.delete(0, builder.length()); showDataDialog(); break; default: break; } } }

广播接收器(记的在AndroidManifest.xml注册)
package com.example.alarmreceiverdemo; import com.example.alarmreceiverdemo.utils.NotificationHelper; import com.example.alarmreceiverdemo.utils.PhoneUtils; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; /** * @project AlarmReceiverDemo * @ClassName AlarmReceiver.java * @Description 接收广播 * @author xugang * @date 2015-7-7 下午12:16:00 */ public class AlarmReceiver extends BroadcastReceiver {public final static String action = ""; @Override public void onReceive(Context context, Intent intent) { String act = intent.getAction(); Toast.makeText(context, "定是时间到:" + act, Toast.LENGTH_SHORT).show(); NotificationHelper.showNotification(context, PhoneUtils.getIntent(),context.getString(R.string.app_name), "定时时间到"); } }

发送通知:
public class NotificationHelper { /** * 发通知 * * @param context * @param intent * @param title * @param content */ public static void showNotification(Context context, Intent intent, String title, String content) { NotificationCompat.Builder mBuilder = newNotificationCompat.Builder(context).setSmallIcon(R.drawable.ic_launcher).setContentTitle(title).setContentText(content); mBuilder.setWhen(System.currentTimeMillis()); PendingIntent pendingintent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(pendingintent); Notification notification = mBuilder.build(); notification.flags = Notification.FLAG_AUTO_CANCEL; notification.defaults |= Notification.DEFAULT_ALL; NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); // mId allows you to update the notification later on. mNotificationManager.notify((int) System.currentTimeMillis(), notification); } }

得到打开本应用的Intent:
public static Intent getIntent() { Intent intent = new Intent("android.intent.action.MAIN"); intent.addCategory("android.intent.category.LAUNCHER"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); intent.setComponent(ComponentName.unflattenFromString("com.example.alarmreceiverdemo/.MainActivity")); return intent; }

【AlarmManager 定时提醒】Layout:

    推荐阅读