AlarmManager 定时提醒

原创 2015年07月07日 15:46:38

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

以下是代码部分:

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 = new  NotificationCompat.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;
    }

Layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/setting"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="设置" />


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dip"
            android:text="设置时间:" />

        <TextView
            android:id="@+id/time"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="10dip" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dip"
            android:text="现在时间:" />

        <TextView
            android:id="@+id/cur"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="10dip" />
    </LinearLayout>

</LinearLayout>

相关文章推荐

Android AlarmManager设置定时事件提醒

最近用到了AlarmManager,遇到了问题,当我设置多个定时器时,发现只有一个起作用,百思不得其解,后来在网上找到了原因,把人家的解决办法贴上: AlarmManager的常用方法有三个: (1...

AlarmManager(闹钟)+Notification(通知)

相信无论是上班一族还是学生一族,最离不开的就是闹钟了,早上起不起得来全靠它了,那么今天我们就来讲讲手机闹钟吧       我们来做个简单的小Demo       Demo截图如下: ...

Android闹钟AlarmManager-通知NotificationManager-自定义通知栏

一:闹钟AlarmManager和通知NotificationManager

使用AlarmManager 多次定时提醒

  • 2012年03月25日 18:46
  • 61KB
  • 下载

AlarmManager的使用-----闹钟/定时提醒功能

AlarmManager----全局定时器 顾名思义就是“提醒”,是Android中常用的一种系统级别的提示服务;...

AlarmManager定时提醒

  • 2015年07月07日 14:41
  • 635KB
  • 下载

AlarmManager 多次定时提醒

  • 2011年12月08日 22:28
  • 61KB
  • 下载

Android AlarmManager实现多个定时重复提醒

在移动开发中,我们经常需要实现一些定时提醒的功能,提醒功能有些定时的,像闹钟一样,有些是根据业务逻辑触发的,这里我主要说一下怎样实现多个定时提醒的实现方法。大言不惭的说下,我在做项目时遇到这个问题再中...

AlarmManager详解-----实现定时提醒

各位好,又几天没见了,我是一个Android菜鸟,这几天项目要做个定时提醒业务,在网上看了很多资料,大多数都是关于AlarmManager去实现(虽然我个人觉得用它去实现不够强大,和健壮,但是没办法,...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:AlarmManager 定时提醒
举报原因:
原因补充:

(最多只允许输入30个字)