【3D技术宅公社】XR数字艺术论坛  XR技术讨论 XR互动电影 定格动画

 找回密码
 立即注册

QQ登录

只需一步,快速开始

调查问卷
论坛即将给大家带来全新的技术服务,面向三围图形学、游戏、动画的全新服务论坛升级为UTF8版本后,中文用户名和用户密码中有中文的都无法登陆,请发邮件到324007255(at)QQ.com联系手动修改密码

3D技术论坛将以计算机图形学为核心,面向教育 推出国内的三维教育引擎该项目在持续研发当中,感谢大家的关注。

查看: 1843|回复: 0

【转】Android广播事件机制及应用(实现简单的定时提醒功能)

[复制链接]
发表于 2013-2-26 15:53:22 | 显示全部楼层 |阅读模式
涉及的主要内容:1) AlarmManager 和 PendingIntent 2) BroadReceiver 3) Notification and NotificationManager

  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. Java代码  
  2. package com.Reminder;  
  3. import java.util.Calendar;  
  4.   
  5. import android.app.Activity;  
  6. import android.app.AlarmManager;  
  7. import android.app.PendingIntent;  
  8. import android.content.Intent;  
  9. import android.os.Bundle;  
  10. import android.view.View;  
  11. import android.widget.Button;  
  12.   
  13. /**
  14. * trigger the Broadcast event and set the alarm
  15. */  
  16. public class ReminderSetting extends Activity {  
  17.       
  18.     Button btnEnable;  
  19.       
  20.     /** Called when the activity is first created. */  
  21.     @Override  
  22.     public void onCreate(Bundle savedInstanceState) {  
  23.         super.onCreate(savedInstanceState);  
  24.         setContentView(R.layout.main);  
  25.          
  26.         /* create a button. When you click the button, the alarm clock is enabled */  
  27.         btnEnable=(Button)findViewById(R.id.btnEnable);  
  28.         btnEnable.setOnClickListener(new View.OnClickListener() {  
  29.             @Override  
  30.             public void onClick(View v) {  
  31.                 setReminder(true);  
  32.             }  
  33.         });  
  34.     }  
  35.       
  36.     /**
  37.      * Set the alarm  
  38.      *  
  39.      * @param b whether enable the Alarm clock or not  
  40.      */  
  41.     private void setReminder(boolean b) {  
  42.          
  43.         // get the AlarmManager instance   
  44.         AlarmManager am= (AlarmManager) getSystemService(ALARM_SERVICE);  
  45.         // create a PendingIntent that will perform a broadcast  
  46.         PendingIntent pi= PendingIntent.getBroadcast(ReminderSetting.this, 0, new Intent(this,MyReceiver.class), 0);  
  47.          
  48.         if(b){  
  49.             // just use current time as the Alarm time.   
  50.             Calendar c=Calendar.getInstance();  
  51.             // schedule an alarm  
  52.             am.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pi);  
  53.         }  
  54.         else{  
  55.             // cancel current alarm  
  56.             am.cancel(pi);  
  57.         }  
  58.          
  59.     }  
  60. }  
复制代码
  1. package com.Reminder;
  2. import java.util.Calendar;

  3. import android.app.Activity;
  4. import android.app.AlarmManager;
  5. import android.app.PendingIntent;
  6. import android.content.Intent;
  7. import android.os.Bundle;
  8. import android.view.View;
  9. import android.widget.Button;

  10. /**
  11. * trigger the Broadcast event and set the alarm
  12. */
  13. public class ReminderSetting extends Activity {
  14.    
  15.     Button btnEnable;
  16.    
  17.     /** Called when the activity is first created. */
  18.     @Override
  19.     public void onCreate(Bundle savedInstanceState) {
  20.         super.onCreate(savedInstanceState);
  21.         setContentView(R.layout.main);
  22.         
  23.         /* create a button. When you click the button, the alarm clock is enabled */
  24.         btnEnable=(Button)findViewById(R.id.btnEnable);
  25.         btnEnable.setOnClickListener(new View.OnClickListener() {
  26.             @Override
  27.             public void onClick(View v) {
  28.                 setReminder(true);
  29.             }
  30.         });
  31.     }
  32.    
  33.     /**
  34.      * Set the alarm
  35.      *
  36.      * @param b whether enable the Alarm clock or not
  37.      */
  38.     private void setReminder(boolean b) {
  39.         
  40.         // get the AlarmManager instance
  41.         AlarmManager am= (AlarmManager) getSystemService(ALARM_SERVICE);
  42.         // create a PendingIntent that will perform a broadcast
  43.         PendingIntent pi= PendingIntent.getBroadcast(ReminderSetting.this, 0, new Intent(this,MyReceiver.class), 0);
  44.         
  45.         if(b){
  46.             // just use current time as the Alarm time.
  47.             Calendar c=Calendar.getInstance();
  48.             // schedule an alarm
  49.             am.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pi);
  50.         }
  51.         else{
  52.             // cancel current alarm
  53.             am.cancel(pi);
  54.         }
  55.         
  56.     }
  57. }
复制代码
2.2 接收广播
       新建一个class 继承BroadcastReceiver,并实现onReceive()方法。当BroadcastReceiver接收到广播后,就会去执行OnReceive()方法。所以,我们在OnReceive()方法中加上代码,当接收到广播后就跳到显示提醒信息的Activity。具体代码如下( MyReceiver.java):  
  1. package com.Reminder;  
  2. import android.content.BroadcastReceiver;  
  3. import android.content.Context;  
  4. import android.content.Intent;  
  5.   
  6. /**
  7. * Receive the broadcast and start the activity that will show the alarm
  8. */  
  9. public class MyReceiver extends BroadcastReceiver {  
  10.   
  11.     /**
  12.      * called when the BroadcastReceiver is receiving an Intent broadcast.
  13.      */  
  14.     @Override  
  15.     public void onReceive(Context context, Intent intent) {  
  16.          
  17.         /* start another activity - MyAlarm to display the alarm */  
  18.         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  19.         intent.setClass(context, MyAlarm.class);  
  20.         context.startActivity(intent);  
  21.          
  22.     }  
  23.   
  24. }  
复制代码
  1. package com.Reminder;
  2. import android.content.BroadcastReceiver;
  3. import android.content.Context;
  4. import android.content.Intent;

  5. /**
  6. * Receive the broadcast and start the activity that will show the alarm
  7. */
  8. public class MyReceiver extends BroadcastReceiver {

  9.     /**
  10.      * called when the BroadcastReceiver is receiving an Intent broadcast.
  11.      */
  12.     @Override
  13.     public void onReceive(Context context, Intent intent) {
  14.         
  15.         /* start another activity - MyAlarm to display the alarm */
  16.         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  17.         intent.setClass(context, MyAlarm.class);
  18.         context.startActivity(intent);
  19.         
  20.     }

  21. }
复制代码
注意:创建完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
  1. package com.Reminder;  
  2. import android.app.Activity;  
  3. import android.app.Notification;  
  4. import android.app.NotificationManager;  
  5. import android.net.Uri;  
  6. import android.os.Bundle;  
  7. import android.provider.MediaStore.Audio;  
  8. import android.view.View;  
  9. import android.widget.Button;  
  10. import android.widget.TextView;  
  11.   
  12. /**
  13. * Display the alarm information  
  14. */  
  15. public class MyAlarm extends Activity {  
  16.   
  17.     /**
  18.      * An identifier for this notification unique within your application
  19.      */  
  20.     public static final int NOTIFICATION_ID=1;   
  21.       
  22.     @Override  
  23.     protected void onCreate(Bundle savedInstanceState) {  
  24.          super.onCreate(savedInstanceState);  
  25.          setContentView(R.layout.my_alarm);  
  26.          
  27.         // create the instance of NotificationManager  
  28.         final NotificationManager nm=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);  
  29.         // create the instance of Notification  
  30.         Notification n=new Notification();  
  31.         /* set the sound of the alarm. There are two way of setting the sound */  
  32.           // n.sound=Uri.parse("file:///sdcard/alarm.mp3");  
  33.         n.sound=Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "20");  
  34.         // Post a notification to be shown in the status bar  
  35.         nm.notify(NOTIFICATION_ID, n);  
  36.          
  37.         /* display some information */  
  38.         TextView tv=(TextView)findViewById(R.id.tvNotification);  
  39.         tv.setText("Hello, it's time to bla bla...");  
  40.          
  41.         /* the button by which you can cancel the alarm */  
  42.         Button btnCancel=(Button)findViewById(R.id.btnCancel);  
  43.         btnCancel.setOnClickListener(new View.OnClickListener() {  
  44.               
  45.             @Override  
  46.             public void onClick(View arg0) {  
  47.                 nm.cancel(NOTIFICATION_ID);  
  48.                 finish();  
  49.             }  
  50.         });  
  51.     }  
  52.       
  53. }  
复制代码
  1. package com.Reminder;
  2. import android.app.Activity;
  3. import android.app.Notification;
  4. import android.app.NotificationManager;
  5. import android.net.Uri;
  6. import android.os.Bundle;
  7. import android.provider.MediaStore.Audio;
  8. import android.view.View;
  9. import android.widget.Button;
  10. import android.widget.TextView;

  11. /**
  12. * Display the alarm information
  13. */
  14. public class MyAlarm extends Activity {

  15.     /**
  16.      * An identifier for this notification unique within your application
  17.      */
  18.     public static final int NOTIFICATION_ID=1;
  19.    
  20.     @Override
  21.     protected void onCreate(Bundle savedInstanceState) {
  22.          super.onCreate(savedInstanceState);
  23.          setContentView(R.layout.my_alarm);
  24.         
  25.         // create the instance of NotificationManager
  26.         final NotificationManager nm=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  27.         // create the instance of Notification
  28.         Notification n=new Notification();
  29.         /* set the sound of the alarm. There are two way of setting the sound */
  30.           // n.sound=Uri.parse("file:///sdcard/alarm.mp3");
  31.         n.sound=Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "20");
  32.         // Post a notification to be shown in the status bar
  33.         nm.notify(NOTIFICATION_ID, n);
  34.         
  35.         /* display some information */
  36.         TextView tv=(TextView)findViewById(R.id.tvNotification);
  37.         tv.setText("Hello, it's time to bla bla...");
  38.         
  39.         /* the button by which you can cancel the alarm */
  40.         Button btnCancel=(Button)findViewById(R.id.btnCancel);
  41.         btnCancel.setOnClickListener(new View.OnClickListener() {
  42.             
  43.             @Override
  44.             public void onClick(View arg0) {
  45.                 nm.cancel(NOTIFICATION_ID);
  46.                 finish();
  47.             }
  48.         });
  49.     }
  50.    
  51. }
复制代码
注:关于提示音设置(Notification.sound),可以参考:http://developer.android.com/guide/topics/ui/notifiers/notifications.html 中的相关部分。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

手机版|小黑屋|3D数字艺术论坛 ( 沪ICP备14023054号 )

GMT+8, 2024-6-29 05:35

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表