步骤:解析json并存入数据库,

每三小时后台刷新一次数据;

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

一天通知一次。

 

效果图: 后台任务 随笔

 

 

解析json

package com.example.admin.quakereport.utils;

import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;

import com.example.admin.quakereport.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.DecimalFormat;


import com.example.admin.quakereport.data.QuakeContact.QuakeEntry;

public class QueryUtils {

private static final String LOG_TAG = QueryUtils.class.getSimpleName();

public static ContentValues[] fetchEarthquakeData(Context context,String requestUrl){
URL url = createUrl(context,requestUrl);
String jsonResponse = null;
try
{ jsonResponse = makehttpRequest(url);
}catch (IOException e){
Log.e(LOG_TAG,"Error in making http request",e); }
ContentValues[] values = extractEarthquakes(context,jsonResponse);
return values;
}


private static URL createUrl(Context context,String mUrl) {
URL url = null;
String format="format",getjson="geojson",limit="limit",limit_number="10",minmag="minmag",Orderby="orderby";
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
String minMagnitude = sharedPreferences.getString(context.getString(R.string.settings_min_magnitude_key), context.getString(R.string.settings_min_magnitude_default));
String orderBy = sharedPreferences.getString(context.getString(R.string.settings_order_by_key), context.getString(R.string.settings_order_by_default));
Uri uri= Uri.parse(mUrl).buildUpon()
.appendQueryParameter(format, getjson)
.appendQueryParameter(limit, limit_number)
.appendQueryParameter(minmag, minMagnitude)
.appendQueryParameter(Orderby, orderBy)
.build();
try {
url=new URL(uri.toString());
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Problem building the URL ", e);
}
return url;
}

private static String makehttpRequest(URL url)throws IOException {
String jsonResponse = "";
if (url == null) {
return jsonResponse;
}

HttpURLConnection urlConnection = null;
InputStream inputStream = null;

try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("GET");
urlConnection.connect();

if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e(LOG_TAG, "Error in connection!! Bad Response ");
}

} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
} finally {
{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
}
return jsonResponse;
}

private static String readFromStream(InputStream inputStream)throws IOException{
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();

while (line != null) {
output.append(line);
line = reader.readLine();
}
}

return output.toString();
}


private static ContentValues[] extractEarthquakes(Context context,String earthquakeJSON){
final String getJsonArray="features",jsObject="properties",double_magnituede="mag",String_location="place"
,String_time="time",String_url="url";
ContentValues[] quakeContentValues=null;

if (TextUtils.isEmpty(earthquakeJSON)) {
return null;
}

try {
JSONObject baseJsonResponse = new JSONObject(earthquakeJSON);
JSONArray featureArray = baseJsonResponse.getJSONArray(getJsonArray);
quakeContentValues=new ContentValues[featureArray.length()];
for (int i = 0; i < featureArray.length(); i++) {
JSONObject currentEarthquake = featureArray.getJSONObject(i);
JSONObject properties = currentEarthquake.getJSONObject(jsObject);

double magnitude = properties.getDouble(double_magnituede);
DecimalFormat magnitudeFormat = new DecimalFormat("0.0");
String formattedMagnitude=magnitudeFormat.format(magnitude);
String location = properties.getString(String_location);

long time = properties.getLong(String_time);
String url = properties.getString(String_url);
ContentValues quakeValues=new ContentValues();
quakeValues.put(QuakeEntry. COLUMN_MAGNITUDE,formattedMagnitude);
quakeValues.put(QuakeEntry.COLUMN_LOCATION,location);
quakeValues.put(QuakeEntry.COLUMN_TIME,time);
quakeValues.put(QuakeEntry.COLUMN_URL,url);
quakeContentValues[i]=quakeValues;
}

}catch (JSONException e){
Log.e(LOG_TAG,"Error in fetching data",e);
}
return quakeContentValues;
}

}


存入数据库
package com.example.admin.quakereport.sync;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.format.DateUtils;

import com.example.admin.quakereport.R;
import com.example.admin.quakereport.data.QuakeContact;
import com.example.admin.quakereport.utils.NotificationUtils;
import com.example.admin.quakereport.utils.QueryUtils;

public class QuakeSyncTask {

private static final String USGS_REQUEST_URL = "https://earthquake.usgs.gov/fdsnws/event/1/query";
synchronized public static void syncQuake(Context context){
ContentValues[] values=QueryUtils.fetchEarthquakeData(context,USGS_REQUEST_URL);
if (values!=null&&values.length!=0){
ContentResolver resolver=context.getContentResolver();
resolver.delete(QuakeContact.QuakeEntry.CONTENT_URI,null,null);
resolver.bulkInsert(QuakeContact.QuakeEntry.CONTENT_URI,values);
}

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
if (sharedPreferences.getBoolean(context.getString(R.string.settings_notifications_key), true)) {
long timeSinceLastNotification=getEllapsedTimeSinceLastNotification(context);
boolean oneDayPassedSinceLastNotification = false;
if (timeSinceLastNotification >=DateUtils.DAY_IN_MILLIS) {
oneDayPassedSinceLastNotification = true;
if (oneDayPassedSinceLastNotification){
NotificationUtils.notifyUserOfNewQuake(context);
}
}
}

}

private static long getEllapsedTimeSinceLastNotification(Context context) {
long lastNotificationTimeMillis = getLastNotificationTimeInMillis(context);
long timeSinceLastNotification = System.currentTimeMillis() - lastNotificationTimeMillis;
return timeSinceLastNotification;
}

private static long getLastNotificationTimeInMillis(Context context) {
String lastNotificationKey = context.getString(R.string.pref_last_notification);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
long lastNotificationTime = sp.getLong(lastNotificationKey, 0);
return lastNotificationTime;
}
}


定时刷新

package com.example.admin.quakereport.sync;

import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.SystemClock;


public class AlramIntentService extends IntentService {

public AlramIntentService() {
super("AlramIntentService");
}


@Override
protected void onHandleIntent(Intent intent) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
QuakeSyncTask.syncQuake(AlramIntentService.this);
return null;
}
}.execute() ;

AlarmManager alarmManager=(AlarmManager)getSystemService(Context.ALARM_SERVICE);
long triggerAtTime=SystemClock.elapsedRealtime()+3*60*60*1000;
Intent i=new Intent(this,AlarmReceiver.class);
PendingIntent pendingIntent=PendingIntent.getBroadcast(this,0,i,0);
alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pendingIntent);

}
}



package com.example.admin.quakereport.sync;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;


public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
intent=new Intent(context,AlramIntentService.class);
context.startService(intent);
}
}

Github项目源码:https://github.com/NeoWu55/Android-QuakeReport.git 分支:Backgroud_task

 
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄