您的位置:首页 > 移动开发 > Android开发

关于android中PendingIntent.getBroadcase的注册广播

2013-11-25 11:30 567 查看
使用语句

[java] view plaincopy

PendingIntent intent= PendingIntent.getBroadcast(Context context, int requestCode, Intent intent, int flags)

获得PendingIntent,浏览了各类文章,大多数说了这种方法,但是基本上也就是止步于此,可是还有最重要的没有谈及,如何区别多个已注册的PendingIntent呢,看了一下PendingIntent.getBroadcast的javadoc,第四个参数flags意为标记,初步认为flags是标识各个PendingIntent的,于是在测试中设置了个全局变量

[java] view plaincopy

public static int currentIntent=0;

然后用currentIntent++作为第四个参数传递进去,测试,注册了两个监听,等待时间的到来,bingo,居然可以了,目测已经可以。可是继续深入时问题来了,我要传递参数怎样?正解做法就是在第三个参数中设置

[java] view plaincopy

intent.setExtra(String key,String value); //设置传递的参数

然后在自己实现的Receiver里用传进来的参数Intent intent实现

[java] view plaincopy

intent.getIntegerExtra(String key);

就可以获得参数,可以真正在实现的时候发现,在receiver里始终取不到参数,再经过一番查找,发现要把PendingIntent.getBroadcast的第四个参数设置于PendingIntent.FLAG_UPDATE_CURRENT,设置后测试,果然可以,可是这样问题又出来了,又要如何区别注册的intent呢?再次查看getBroadcast的javadoc,几个参数都没有说明如何区别要注册的PendingIntent,反而看到第二个参数的说明很神奇,就是这个参数目前为保留状态,仍未用到,无奈中,继续search各种说法,才发现,用requestCode来区别居然是可以的(可是为什么javadoc要说该参数未被使用呢?不解;估计用于区分PendingIntent的方法就是其中任意一个参数不同便可以区分了)代码如下:

设置监听

[java] view plaincopy

Intent setAlertIntent=new Intent(this,AlertReceiver.class);

setAlertIntent.putExtra("try", "i'm just have a try");

PendingIntent pendingIntent=PendingIntent.getBroadcast(this, alarmCount++, setAlertIntent,PendingIntent.FLAG_UPDATE_CURRENT);



AlarmManager alarmManager=(AlarmManager)getSystemService(ALARM_SERVICE);

alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

Receiver中获取传递的数据:

[java] view plaincopy

public void onReceive(Context context, Intent intent) {

// TODO Auto-generated method stub

Bundle bundle= intent.getExtras();

if(bundle==null){

Toast.makeText(context,"nothing", Toast.LENGTH_LONG).show();

}else{

Set<String> set=bundle.keySet();

for(String item:set){

System.out.println(item);

System.out.println(".............");

}

Toast.makeText(context,bundle.getCharSequence("try"), Toast.LENGTH_LONG).show();

}



}

转载:http://blog.csdn.net/huang_hws/article/details/7327670
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: