broadcast intert
1.QueryPreferences.java
package com.bignerdranch.android.photogallery;
import android.content.Context;
import android.preference.PreferenceManager;
public class QueryPreferences {
private static final String PREF_SEARCH_QUERY = "searchQuery";
private static final String PREF_LAST_RESULT_ID = "lastResultId";
private static final String PREF_IS_ALARM_ON = "isAlarmOn";
public static String getStoredQuery(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getString(PREF_SEARCH_QUERY, null);
}
public static void setStoredQuery(Context context, String query) {
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putString(PREF_SEARCH_QUERY, query)
.apply();
}
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();
}
public static boolean isAlarmOn(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean(PREF_IS_ALARM_ON, false);
}
public static void setAlarmOn(Context context, boolean isOn) {
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putBoolean(PREF_IS_ALARM_ON, isOn)
.apply();
}
}
2.PollServic.java
package com.bignerdranch.android.photogallery;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class PollService extends IntentService {
private static final String TAG = “PollService”;
private static final long POLL_INTERVAL_MS = TimeUnit.MINUTES.toMillis(15);
public static final String ACTION_SHOW_NOTIFICATION =
"com.bignerdranch.android.photogallery.SHOW_NOTIFICATION";
public static final String PERM_PRIVATE =
"com.bignerdranch.android.photogallery.PRIVATE";
public static final String REQUEST_CODE = "REQUEST_CODE";
public static final String NOTIFICATION = "NOTIFICATION";
public static Intent newIntent(Context context) {
return new Intent(context, PollService.class);
}
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();
}
QueryPreferences.setAlarmOn(context, isOn);
}
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;
}
public PollService() {
super(TAG);
}
@Override
protected void onHandleIntent(Intent intent) {
if (!isNetworkAvailableAndConnected()) {
return;
}
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);
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();
showBackgroundNotification(0, notification);
}
QueryPreferences.setLastResultId(this, resultId);
}
private void showBackgroundNotification(int requestCode, Notification notification) {
Intent i = new Intent(ACTION_SHOW_NOTIFICATION);
i.putExtra(REQUEST_CODE, requestCode);
i.putExtra(NOTIFICATION, notification);
sendOrderedBroadcast(i, PERM_PRIVATE, null, null,
Activity.RESULT_OK, null, null);
}
private boolean isNetworkAvailableAndConnected() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
boolean isNetworkAvailable = cm.getActiveNetworkInfo() != null;
boolean isNetworkConnected = isNetworkAvailable &&
cm.getActiveNetworkInfo().isConnected();
return isNetworkConnected;
}
}
3.NotificationReciver.java
package com.bignerdranch.android.photogallery;
import android.app.Activity;
import android.app.Notification;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationManagerCompat;
import android.util.Log;
public class NotificationReceiver extends BroadcastReceiver {
private static final String TAG = “NotificationReceiver”;
@Override
public void onReceive(Context c, Intent i) {
Log.i(TAG, "received result: " + getResultCode());
if (getResultCode() != Activity.RESULT_OK) {
// A foreground activity cancelled the broadcast
return;
}
int requestCode = i.getIntExtra(PollService.REQUEST_CODE, 0);
Notification notification = (Notification)
i.getParcelableExtra(PollService.NOTIFICATION);
NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(c);
notificationManager.notify(requestCode, notification);
}
}
4.NotificationReceiver.java
package com.bignerdranch.android.photogallery;
import android.app.Activity;
import android.app.Notification;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationManagerCompat;
import android.util.Log;
public class NotificationReceiver extends BroadcastReceiver {
private static final String TAG = “NotificationReceiver”;
@Override
public void onReceive(Context c, Intent i) {
Log.i(TAG, "received result: " + getResultCode());
if (getResultCode() != Activity.RESULT_OK) {
// A foreground activity cancelled the broadcast
return;
}
int requestCode = i.getIntExtra(PollService.REQUEST_CODE, 0);
Notification notification = (Notification)
i.getParcelableExtra(PollService.NOTIFICATION);
NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(c);
notificationManager.notify(requestCode, notification);
}
}
5.FlickrFetchr.java
package com.bignerdranch.android.photogallery;
import android.net.Uri;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class FlickrFetchr {
private static final String TAG = “FlickrFetchr”;
private static final String API_KEY = "7e5163077c561f346a16e89d6c4252de";
private static final String FETCH_RECENTS_METHOD = "flickr.photos.getRecent";
private static final String SEARCH_METHOD = "flickr.photos.search";
private static final Uri ENDPOINT = Uri
.parse("https://api.flickr.com/services/rest/")
.buildUpon()
.appendQueryParameter("api_key", API_KEY)
.appendQueryParameter("format", "json")
.appendQueryParameter("nojsoncallback", "1")
.appendQueryParameter("extras", "url_s")
.build();
public byte[] getUrlBytes(String urlSpec) throws IOException {
URL url = new URL(urlSpec);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = connection.getInputStream();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException(connection.getResponseMessage() +
": with " +
urlSpec);
}
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
}
out.close();
return out.toByteArray();
} finally {
connection.disconnect();
}
}
public String getUrlString(String urlSpec) throws IOException {
return new String(getUrlBytes(urlSpec));
}
public List<GalleryItem> fetchRecentPhotos() {
String url = buildUrl(FETCH_RECENTS_METHOD, null);
return downloadGalleryItems(url);
}
public List<GalleryItem> searchPhotos(String query) {
String url = buildUrl(SEARCH_METHOD, query);
return downloadGalleryItems(url);
}
private List<GalleryItem> downloadGalleryItems(String url) {
List<GalleryItem> items = new ArrayList<>();
try {
String jsonString = getUrlString(url);
Log.i(TAG, "Received JSON: " + jsonString);
JSONObject jsonBody = new JSONObject(jsonString);
parseItems(items, jsonBody);
} catch (IOException ioe) {
Log.e(TAG, "Failed to fetch items", ioe);
} catch (JSONException je) {
Log.e(TAG, "Failed to parse JSON", je);
}
return items;
}
private String buildUrl(String method, String query) {
Uri.Builder uriBuilder = ENDPOINT.buildUpon()
.appendQueryParameter("method", method);
if (method.equals(SEARCH_METHOD)) {
uriBuilder.appendQueryParameter("text", query);
}
return uriBuilder.build().toString();
}
private void parseItems(List<GalleryItem> items, JSONObject jsonBody)
throws IOException, JSONException {
JSONObject photosJsonObject = jsonBody.getJSONObject("photos");
JSONArray photoJsonArray = photosJsonObject.getJSONArray("photo");
for (int i = 0; i < photoJsonArray.length(); i++) {
JSONObject photoJsonObject = photoJsonArray.getJSONObject(i);
GalleryItem item = new GalleryItem();
item.setId(photoJsonObject.getString("id"));
item.setCaption(photoJsonObject.getString("title"));
if (!photoJsonObject.has("url_s")) {
continue;
}
item.setUrl(photoJsonObject.getString("url_s"));
items.add(item);
}
}
}
6.VisibleFragement.java
package com.bignerdranch.android.photogallery;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.widget.Toast;
public abstract class VisibleFragment extends Fragment {
private static final String TAG = “VisibleFragment”;
private BroadcastReceiver mOnShowNotification = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// If we receive this, we're visible, so cancel
// the notification
Log.i(TAG, "canceling notification");
setResultCode(Activity.RESULT_CANCELED);
}
};
@Override
public void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter(PollService.ACTION_SHOW_NOTIFICATION);
getActivity().registerReceiver(mOnShowNotification, filter,
PollService.PERM_PRIVATE, null);
}
@Override
public void onStop() {
super.onStop();
getActivity().unregisterReceiver(mOnShowNotification);
}
}
7.
注意:详细步骤请查看书本上面,因本人软件只能做到此步,若需要其他的步骤请自行解决哦。代码下面截图里面的程序是接着程序走的,只是不知道为什么编辑博客时是代码发出来代码部分变成了图片的样子但是没关系都是从那个位置连接往下的。