我是android的新手.我哪知道之间的区别Intent和BroadcastReceiver.我有更多的困惑BroadcastReceiver比Intent.
请帮帮我.简单的代码将有所帮助.
Mac*_*rse 32
好的,我将以一个例子来解释它.
我们假设我想创建一个应用程序来检查它的网页上的地铁状态.如果地铁不能正常工作,我也想要系统通知.
我会有:
Activity显示结果.Service检查地铁是否正常工作并显示通知是否无效.Broadcast Receiver叫Alarm Receiver拨打服务每15分钟一班.我来告诉你一些代码:
/* AlarmReceiver.java */
public class AlarmReceiver extends BroadcastReceiver {
public static final String ACTION_REFRESH_SUBWAY_ALARM =
"com.x.ACTION_REFRESH_SUBWAY_ALARM";
@Override
public void onReceive(Context context, Intent intent) {
Intent startIntent = new Intent(context, StatusService.class);
context.startService(startIntent);
}
}
Run Code Online (Sandbox Code Playgroud)
说明:如您所见,您可以设置警报.当收到警报时,我们用一个intent来启动service.基本上intent是一个msg可以有动作,一个序列化的东西.
public class StatusService extends Service {
@Override
public void onCreate() {
super.onCreate();
mAlarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intentToFire = new Intent(AlarmReceiver.ACTION_REFRESH_ALARM);
mAlarmIntent = PendingIntent.getBroadcast(this, 0, intentToFire, 0);
}
@Override
public void onStart(Intent intent, int arg1) {
super.onStart(intent, arg1);
Log.d(TAG, "SERVICE STARTED");
setAlarm();
Log.d(TAG, "Performing update!");
new SubwayAsyncTask().execute();
stopSelf();
}
private void setAlarm() {
int alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;
mAlarms.setInexactRepeating(alarmType, SystemClock.elapsedRealtime() + timeToRefresh(),
AlarmManager.INTERVAL_HALF_DAY, mAlarmIntent);
}
}
Run Code Online (Sandbox Code Playgroud)
说明:
在service启动和:
AsyncTask负责更新通知的Activity粘贴它没有意义,AsyncTask但是当它完成它调用时:
private void sendSubwayUpdates(LinkedList<Subway> subways) {
Intent intent = new Intent(NEW_SUBWAYS_STATUS);
intent.putExtra("subways", subways);
sendBroadcast(intent);
}
Run Code Online (Sandbox Code Playgroud)
这创建了一个Intent具有特定NEW_SUBWAYS_STATUS动作的新动作,将意图放入地铁和sendBroadcast.如果有人有兴趣获得该信息,它将有一个接收器.
我希望我清楚自己.
PS:前几天有人以非常酷的方式解释了广播和意图.有人想分享他的啤酒,所以他发送了一个有意图采取行动的广播:"FREE_BEER"和额外的:"一杯啤酒".
| 归档时间: |
|
| 查看次数: |
11097 次 |
| 最近记录: |