BroadcastReceiver在android中是一特色功能.android系统的很多消息(如系统启动,新短信,来电话等)都通过BroadcastReceiver来分发.BroadcastReceiver的生命周期是短暂的,而且是消息一到达则创建执行完毕就立刻销毁的.为了说明这一点,我通过注册一个Alarm Service每7秒钟触发产生一次BroadcastReceive事件.
以下是BroadcastReceive的实现
- protected static final class AlarmReceiver extends BroadcastReceiver{
- public AlarmReceiver()
- {
-
- Log.i("AlarmReceiver.AlarmReceiver()", Calendar.getInstance().getTime().toLocaleString());
- Log.i("AlarmReceiver.AlarmReceiver() -> pid", String.valueOf(android.os.Process.myPid()));
- Log.i("AlarmReceiver.AlarmReceiver() -> tid", String.valueOf(android.os.Process.myTid()));
- }
- @Override
- public void onReceive(Context context, Intent intent) {
-
- Log.i("AlarmReceiver.onReceive()", Calendar.getInstance().getTime().toLocaleString());
- }
- }
protected static final class AlarmReceiver extends BroadcastReceiver{
public AlarmReceiver()
{
//查看类创建的进程id和线程id
Log.i("AlarmReceiver.AlarmReceiver()", Calendar.getInstance().getTime().toLocaleString());
Log.i("AlarmReceiver.AlarmReceiver() -> pid", String.valueOf(android.os.Process.myPid()));
Log.i("AlarmReceiver.AlarmReceiver() -> tid", String.valueOf(android.os.Process.myTid()));
}
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.i("AlarmReceiver.onReceive()", Calendar.getInstance().getTime().toLocaleString());
}
}
通过一个"Start"按钮和一个"Stop"按钮来控制消息.
- public void onClick(View arg0) {
-
- switch(arg0.getId()){
- case R.id.btnStart:
- Log.i("current pid", String.valueOf(android.os.Process.myPid()));
- Log.i("current tid", String.valueOf(android.os.Process.myTid()));
-
- ((AlarmManager)this.getSystemService(Context.ALARM_SERVICE))
- .setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 7*1000,
- PendingIntent.getBroadcast(this, 0, new Intent(this,AlarmReceiver.class), 0)
- );
- break;
- case R.id.btnStop:
- ((AlarmManager)this.getSystemService(Context.ALARM_SERVICE))
- .cancel(PendingIntent.getBroadcast(this, 0, new Intent(this,AlarmReceiver.class), 0));
- break;
- }
- }
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch(arg0.getId()){
case R.id.btnStart:
Log.i("current pid", String.valueOf(android.os.Process.myPid()));
Log.i("current tid", String.valueOf(android.os.Process.myTid()));
((AlarmManager)this.getSystemService(Context.ALARM_SERVICE))
.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 7*1000,
PendingIntent.getBroadcast(this, 0, new Intent(this,AlarmReceiver.class), 0)
);
break;
case R.id.btnStop:
((AlarmManager)this.getSystemService(Context.ALARM_SERVICE))
.cancel(PendingIntent.getBroadcast(this, 0, new Intent(this,AlarmReceiver.class), 0));
break;
}
}
打开logCat选择I,运行清理掉所有日志点击"Start"按钮
从上图可以看到AlarmReceiver类的实例是每触发一次就新建一次的,而且和程序是在同一个进程同一线程内.