一、创建IntentService
首先使用IntentService创建服务。IntentService并不是Android唯一的可用服务,但是最常用的,创建一个名为pollService的IntentService子类,它就是用来轮询搜索结果的服务。
1.创建PollService(PollService.java)
private static final String TAG = "PollService";
public static Intent newIntent(Context context) {
return new Intent(context, PollService.class);
}
public PollService() {
super(TAG);
}
@Override
protected void onHandleIntent(Intent intent) {
Log.i(TAG,"Received an intent:" +intent)
}
2.在manifes配置文件中添加服务(AndroidManifest.xml)
<service android:name=".PollService" />
3.添加服务启动代码(PhotoGalleryFragment.java)
Intent i = pollService.newIntent(getActivity());
getActivity().startService();
二、服务的作用
1.检查后台的可用性(PollService.java)
if (!isNetworkAvailableAndConnected()) {
return;
}
private boolean isNetworkAvailableAndConnected() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
boolean isNetworkAvailable = cm.getActiveNetworkInfo() != null;
boolean isNetworkConnected = isNetworkAvailable &&
cm.getActiveNetworkInfo().isConnected();
return isNetworkConnected;
}
2.获取网络状态权限(AndroidManifest.xml)
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
三、查找最新返回结果
1.添加存储图片ID的preference常量(QueryPreferences.java)
private static final String PREF_LAST_RESULT_ID = "lastResultId";
public static String getLastResultId(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getString(PREF_LAST_RESULT_ID, null);
}
public static void setLastResultId(Context context, String lastResultId) {
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putString(PREF_LAST_RESULT_ID, lastResultId)
.apply();
2.检查最新返回结果(PollService.java)
String query = QueryPreferences.getStoredQuery(this);
String lastResultId = QueryPreferences.getLastResultId(this);
List<GalleryItem> items;
if (query == null) {
items = new FlickrFetchr().fetchRecentPhotos();
} else {
items = new FlickrFetchr().searchPhotos(query);
}
if (items.size() == 0) {
return;
}
String resultId = items.get(0).getId();
if (resultId.equals(lastResultId)) {
Log.i(TAG, "Got an old result: " + resultId);
} else {
Log.i(TAG, "Got a new result: " + resultId);
QueryPreferences.setLastResultId(this,resultId);
四、使用AlarmManager延迟运行服务
1.添加定时方法(PollService.java)
//Set interval to 1 minute
private static final long POLL_INTERVAL_MS = TimeUnit.MINUTES.toMillis(1);
public static void setServiceAlarm(Context context, boolean isOn) {
Intent i = PollService.newIntent(context);
PendingIntent pi = PendingIntent.getService(
context, 0, i, 0);
AlarmManager alarmManager = (AlarmManager)
context.getSystemService(Context.ALARM_SERVICE);
if (isOn) {
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime(), POLL_INTERVAL_MS, pi);
} else {
alarmManager.cancel(pi);
pi.cancel();
}
2.添加定时器启动代码(PhotoGalleryFragment.java)
PollService.setServiceAlarm(getActivity(),true);
3.添加isServiceAlarmOn方法(PollService.java)
public static boolean isServiceAlarmOn(Context context) {
Intent i = PollService.newIntent(context);
PendingIntent pi = PendingIntent
.getService(context, 0, i, PendingIntent.FLAG_NO_CREATE);
return pi != null;
}
4.添加服务开关(menu/fragment_photo_gallery.xml)
<item android:id="@+id/menu_item_toggle_polling"
android:title="@string/start_polling"
app:showAsAction="ifRoom" />
5.添加polling字符串资源(res/values/strings.xml)
<string name="start_polling">Start polling</string>
<string name="stop_polling">Stop polling</string>
<string name="new_pictures_title">New PhotoGallery Pictures</string>
<string name="new_pictures_text">You have new pictures in PhotoGallery.</string>
6.菜单项切换实现(PhotoGalleryFragment.java)
case R.id.menu_item_toggle_polling:
boolean shouldStartAlarm = !PollService.isServiceAlarmOn(getActivity());
PollService.setServiceAlarm(getActivity(), shouldStartAlarm);
getActivity().invalidateOptionsMenu();
return true;
7.菜单项切换(PhotoGalleryFragment.java)
MenuItem toggleItem = menu.findItem(R.id.menu_item_toggle_polling);
if (PollService.isServiceAlarmOn(getActivity())) {
toggleItem.setTitle(R.string.stop_polling);
} else {
toggleItem.setTitle(R.string.start_polling);
8.让选项菜单失效(PhotoGalleryFragment.java)
getActivity().invalidateOptionsMenu();
五、通知信息
1.添加newIntent静态方法(PhotoGalleryActivity.java)
public static Intent newIntent(Context context) {
return new Intent(context, PhotoGalleryActivity.class);
}
2.添加通知信息(PollService.java)
Resources resources = getResources();
Intent i = PhotoGalleryActivity.newIntent(this);
PendingIntent pi = PendingIntent
.getActivity(this, 0, i, 0);
Notification notification = new NotificationCompat.Builder(this)
.setTicker(resources.getString(R.string.new_pictures_title))
.setSmallIcon(android.R.drawable.ic_menu_report_image)
.setContentTitle(resources.getString(R.string.new_pictures_title))
.setContentText(resources.getString(R.string.new_pictures_text))
.setContentIntent(pi)
.setAutoCancel(true)
.build();
NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(this);
notificationManager.notify(0, notification);
}
3.使用更为合理的定时器常量(PollService.java)
private static final long POLL_INTERVAL_MS = TimeUnit.MINUTES.toMillis(15);
六、测试
由于没有秘钥,所以不能显示图片,得自己申请一个,放入代码中
申请秘钥之后的结果