免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2279 | 回复: 0
打印 上一主题 下一主题

Android广播事件机制及应用 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-08-08 13:27 |只看该作者 |倒序浏览
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):

  1. 01.package com.Reminder;

  2. 02.import java.util.Calendar;

  3. 03.

  4. 04.import android.app.Activity;

  5. 05.import android.app.AlarmManager;

  6. 06.import android.app.PendingIntent;

  7. 07.import android.content.Intent;

  8. 08.import android.os.Bundle;

  9. 09.import android.view.View;

  10. 10.import android.widget.Button;

  11. 11.

  12. 12./**

  13. 13.* trigger the Broadcast event and set the alarm

  14. 14.*/

  15. 15.public class ReminderSetting extends Activity {

  16. 16.   

  17. 17.    Button btnEnable;

  18. 18.   

  19. 19.    /** Called when the activity is first created. */

  20. 20.    @Override

  21. 21.    public void onCreate(Bundle savedInstanceState) {

  22. 22.        super.onCreate(savedInstanceState);

  23. 23.        setContentView(R.layout.main);

  24. 24.        

  25. 25.        /* create a button. When you click the button, the alarm clock is enabled */

  26. 26.        btnEnable=(Button)findViewById(R.id.btnEnable);

  27. 27.        btnEnable.setOnClickListener(new View.OnClickListener() {

  28. 28.            @Override

  29. 29.            public void onClick(View v) {

  30. 30.                setReminder(true);

  31. 31.            }

  32. 32.        });

  33. 33.    }

  34. 34.   

  35. 35.    /**

  36. 36.     * Set the alarm

  37. 37.     *

  38. 38.     * @param b whether enable the Alarm clock or not

  39. 39.     */

  40. 40.    private void setReminder(boolean b) {

  41. 41.        

  42. 42.        // get the AlarmManager instance

  43. 43.        AlarmManager am= (AlarmManager) getSystemService(ALARM_SERVICE);

  44. 44.        // create a PendingIntent that will perform a broadcast

  45. 45.        PendingIntent pi= PendingIntent.getBroadcast(ReminderSetting.this, 0, new Intent(this,MyReceiver.class), 0);

  46. 46.        

  47. 47.        if(b){

  48. 48.            // just use current time as the Alarm time.

  49. 49.            Calendar c=Calendar.getInstance();

  50. 50.            // schedule an alarm

  51. 51.            am.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pi);

  52. 52.        }

  53. 53.        else{

  54. 54.            // cancel current alarm

  55. 55.            am.cancel(pi);

  56. 56.        }

  57. 57.        

  58. 58.    }

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

  2. 02.import android.content.BroadcastReceiver;

  3. 03.import android.content.Context;

  4. 04.import android.content.Intent;

  5. 05.

  6. 06./**

  7. 07.* Receive the broadcast and start the activity that will show the alarm

  8. 08.*/

  9. 09.public class MyReceiver extends BroadcastReceiver {

  10. 10.

  11. 11.    /**

  12. 12.     * called when the BroadcastReceiver is receiving an Intent broadcast.

  13. 13.     */

  14. 14.    @Override

  15. 15.    public void onReceive(Context context, Intent intent) {

  16. 16.        

  17. 17.        /* start another activity - MyAlarm to display the alarm */

  18. 18.        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

  19. 19.        intent.setClass(context, MyAlarm.class);

  20. 20.        context.startActivity(intent);

  21. 21.        

  22. 22.    }

  23. 23.

  24. 24.}
复制代码
复制代码注意:创建完BroadcastReceiver后,需要在AndroidManifest.xml中注册:
  1. 01.<receiver android:name=".MyReceiver">     

  2. 02.       <intent-filter>

  3. 03.        <action android:name= "com.Reminder.MyReceiver" />

  4. 04.    </intent-filter>

  5. 05.</receiver>
复制代码
复制代码2.3 提醒功能       新建一个Activity,我们在这个Activity中通过Android的Notification对象来提醒用户。我们将添加提示音,一个TextView来显示提示内容和并一个button来取消提醒。      其中,创建Notification主要包括:        1)获得系统级得服务NotificationManager,通过 Context.getSystemService(NOTIFICATION_SERVICE)获得。       2)实例化Notification对象,并设置各种我们需要的属性,比如:设置声音。       3)调用NotificationManager的notify()方法显示Notification      详细代码如下:MyAlarm.java
  1. 01.package com.Reminder;

  2. 02.import android.app.Activity;

  3. 03.import android.app.Notification;

  4. 04.import android.app.NotificationManager;

  5. 05.import android.net.Uri;

  6. 06.import android.os.Bundle;

  7. 07.import android.provider.MediaStore.Audio;

  8. 08.import android.view.View;

  9. 09.import android.widget.Button;

  10. 10.import android.widget.TextView;

  11. 11.

  12. 12./**

  13. 13.* Display the alarm information

  14. 14.*/

  15. 15.public class MyAlarm extends Activity {

  16. 16.

  17. 17.    /**

  18. 18.     * An identifier for this notification unique within your application

  19. 19.     */

  20. 20.    public static final int NOTIFICATION_ID=1;

  21. 21.   

  22. 22.    @Override

  23. 23.    protected void onCreate(Bundle savedInstanceState) {

  24. 24.         super.onCreate(savedInstanceState);

  25. 25.         setContentView(R.layout.my_alarm);

  26. 26.        

  27. 27.        // create the instance of NotificationManager

  28. 28.        final NotificationManager nm=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);

  29. 29.        // create the instance of Notification

  30. 30.        Notification n=new Notification();

  31. 31.        /* set the sound of the alarm. There are two way of setting the sound */

  32. 32.          // n.sound=Uri.parse("file:///sdcard/alarm.mp3");

  33. 33.        n.sound=Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "20");

  34. 34.        // Post a notification to be shown in the status bar

  35. 35.        nm.notify(NOTIFICATION_ID, n);

  36. 36.        

  37. 37.        /* display some information */

  38. 38.        TextView tv=(TextView)findViewById(R.id.tvNotification);

  39. 39.        tv.setText("Hello, it's time to bla bla...");

  40. 40.        

  41. 41.        /* the button by which you can cancel the alarm */

  42. 42.        Button btnCancel=(Button)findViewById(R.id.btnCancel);

  43. 43.        btnCancel.setOnClickListener(new View.OnClickListener() {

  44. 44.            

  45. 45.            @Override

  46. 46.            public void onClick(View arg0) {

  47. 47.                nm.cancel(NOTIFICATION_ID);

  48. 48.                finish();

  49. 49.            }

  50. 50.        });

  51. 51.    }

  52. 52.   

  53. 53.}
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP