Android广播事件机制,并实现简单的定时提醒功能

  1.Android广播事件机制

     Android的广播事件处理类似于普通的事件处理。不同之处在于,后者是靠点击按钮这样的组件行为来触发,而前者是通过构建Intent对象,使用sentBroadcast()方法来发起一个系统级别的事件广播来传递信息。广播事件的接收是通过定义一个继承Broadcast Receiver的类实现的,继承该类后覆盖其onReceive()方法,在该方法中响应事件。Android系统中定义了很多标准的Broadcast Action来响应系统广播事件。例如:ACTION_TIME_CHANGED(时间改变时触发)。但是,我们也可以自己定义Broadcast Receiver接收广播事件。

  2.实现简单的定时提醒功能

     主要包括三部分部分:

     1) 定时 - 通过定义Activity发出广播

     2) 接收广播 - 通过实现BroadcastReceiver接收广播

     3)   提醒 - 并通过Notification提醒用户

     现在我们来具体实现这三部分:

    2.1 如何定时,从而发出广播呢?

       现在的手机都有闹钟的功能,我们可以利用系统提供的闹钟功能,来定时,即发出广播。具体地,在Android开发中可以用AlarmManager来实现。

       AlarmManager 提供了一种系统级的提示服务,允许你安排在某个时间执行某一个服务。

       AlarmManager的使用步骤说明如下:

       1)获得AlarmManager实例: AlarmManager对象一般不直接实例化,而是通过Context.getSystemService(Context.ALARM_SERVIECE) 方法获得

       2)定义一个PendingIntent来发出广播。

       3)调用AlarmManager的相关方法,设置定时、重复提醒等功能。

       详细代码如下(ReminderSetting.java):

package com.Reminder;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

/**
* trigger the Broadcast event and set the alarm
*/
public class ReminderSetting extends Activity {
   
    Button btnEnable;
   
   
/** Called when the activity is first created. */
    @Override
   
public void onCreate(Bundle savedInstanceState) {
       
super .onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
       
/* create a button. When you click the button, the alarm clock is enabled */
        btnEnable
= (Button)findViewById(R.id.btnEnable);
        btnEnable.setOnClickListener(
new View.OnClickListener() {
            @Override
           
public void onClick(View v) {
                setReminder(
true );
            }
        });
    }
   
   
/**
     * Set the alarm
     *
     *
@param b whether enable the Alarm clock or not
    
*/
   
private void setReminder( boolean b) {
       
       
// get the AlarmManager instance
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
       
// create a PendingIntent that will perform a broadcast
        PendingIntent pi = PendingIntent.getBroadcast(ReminderSetting. this , 0 , new Intent( this ,MyReceiver. class ), 0 );
       
       
if (b){
           
// just use current time as the Alarm time.
            Calendar c = Calendar.getInstance();
           
// schedule an alarm
            am.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pi);
        }
       
else {
           
// cancel current alarm
            am.cancel(pi);
        }
       
    }
}
 
     2.2 接收广播

       新建一个class 继承BroadcastReceiver,并实现onReceive()方法。当BroadcastReceiver接收到广播后,就会去执行OnReceive()方法。所以,我们在OnReceive()方法中加上代码,当接收到广播后就跳到显示提醒信息的Activity。具体代码如下( MyReceiver.java): 

package com.Reminder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

/**
* Receive the broadcast and start the activity that will show the alarm
*/
public class MyReceiver extends BroadcastReceiver {

   
/**
     * called when the BroadcastReceiver is receiving an Intent broadcast.
    
*/
    @Override
   
public void onReceive(Context context, Intent intent) {
       
       
/* start another activity - MyAlarm to display the alarm */
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setClass(context, MyAlarm.
class );
        context.startActivity(intent);
       
    }

}
 
   

    注意:创建完BroadcastReceiver后,需要在AndroidManifest.xml中注册:

<receiver android:name=".MyReceiver">    

       <intent-filter>
       
<action android:name= "com.Reminder.MyReceiver" />
   
</intent-filter>
</receiver>

 
    2.3 提醒功能

       新建一个Activity,我们在这个Activity中通过Android的Notification对象来提醒用户。我们将添加提示音,一个TextView来显示提示内容和并一个button来取消提醒。

      其中,创建Notification主要包括:

       1)获得系统级得服务NotificationManager,通过 Context.getSystemService(NOTIFICATION_SERVICE)获得。

       2)实例化Notification对象,并设置各种我们需要的属性,比如:设置声音。

       3)调用NotificationManager的notify()方法显示Notification

      详细代码如下:MyAlarm.java

package com.Reminder;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Audio;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

/**
* Display the alarm information
*/
public class MyAlarm extends Activity {

   
/**
     * An identifier for this notification unique within your application
    
*/
   
public static final int NOTIFICATION_ID = 1 ;
   
    @Override
   
protected void onCreate(Bundle savedInstanceState) {
        
super .onCreate(savedInstanceState);
         setContentView(R.layout.my_alarm);
       
       
// create the instance of NotificationManager
        final NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
       
// create the instance of Notification
        Notification n = new Notification();
       
/* set the sound of the alarm. There are two way of setting the sound */
         
// n.sound=Uri.parse("file: // /sdcard/alarm.mp3");
        n.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, " 20 " );
       
// Post a notification to be shown in the status bar
        nm.notify(NOTIFICATION_ID, n);
       
       
/* display some information */
        TextView tv
= (TextView)findViewById(R.id.tvNotification);
        tv.setText(
" Hello, it's time to bla bla... " );
       
       
/* the button by which you can cancel the alarm */
        Button btnCancel
= (Button)findViewById(R.id.btnCancel);
        btnCancel.setOnClickListener(
new View.OnClickListener() {
           
            @Override
           
public void onClick(View arg0) {
                nm.cancel(NOTIFICATION_ID);
                finish();
            }
        });
    }
   
}
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Android 后台定时提醒功能实现主要有两种方式: 1. 使用 AlarmManager AlarmManager 是 Android 系统提供的一种定时服务,可以在指定时间触发一个 PendingIntent。我们可以在 PendingIntent 中设置提醒通知的内容,然后在指定时间触发 PendingIntent 来发送提醒通知。 具体实现步骤如下: 1) 创建一个 PendingIntent,用于触发提醒通知的操作。 2) 创建一个 AlarmManager 对象,设置定时提醒的时间和重复间隔。 3) 在指定的时间触发 PendingIntent,发送提醒通知。 示例代码: ``` // 创建 PendingIntent Intent intent = new Intent(this, ReminderBroadcastReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0); // 创建 AlarmManager AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 10000, AlarmManager.INTERVAL_DAY, pendingIntent); ``` 2. 使用 JobScheduler JobScheduler 是 Android 5.0 引入的一种新的调度服务,可以在指定时间或条件下执行某个任务。我们可以在 JobScheduler 中设置提醒通知的内容,然后在指定时间触发 JobScheduler 来发送提醒通知。 具体实现步骤如下: 1) 创建一个 JobService,用于执行提醒通知的操作。 2) 创建一个 JobInfo 对象,设置定时提醒的时间和条件。 3) 将 JobInfo 对象传递给 JobScheduler,启动定时任务。 示例代码: ``` // 创建 JobInfo 对象 JobInfo jobInfo = new JobInfo.Builder(1, new ComponentName(this, ReminderJobService.class)) .setMinimumLatency(10000) .setPersisted(true) .build(); // 创建 JobScheduler JobScheduler jobScheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE); jobScheduler.schedule(jobInfo); ``` 以上两种方式均可以实现 Android 后台定时提醒功能,具体选择哪种方式根据实际需求来进行选择。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值