我的应用程序每周二更新,如果用户未连接到互联网,则使用 setAlarm(-2) 。如果 data.json 文件不存在,那么这意味着用户第一次打开应用程序所以它只是设置了一个到了周二的新警报并更新了json。当应用程序运行时,所有工作都很棒,即使在后台工作也没问题,但如果应用程序没有运行(关闭),当警报被调用时,应用程序崩溃不幸。
BroadcastReceiver:
public class UpdateReceiver extends BroadcastReceiver {
private static long alarmTime = 0;
@Override
public void onReceive(Context context, Intent intent) {
alarmTime = NextTuesday.nextDayOfWeek(Calendar.TUESDAY).getTimeInMillis();
File file = context.getFileStreamPath("data.json");
if (!file.exists()) {
Toast.makeText(context, "FIRST BOOT", Toast.LENGTH_LONG).show();
if (isConnectedToInternet(context)) {
UpcomingFragment.getInstance().setAlarm(-1);
UpcomingFragment.getInstance().update();
} else {
//a day from now
UpcomingFragment.getInstance().setAlarm(-2);
}
} else {
Toast.makeText(context, "FILE EXISTS", Toast.LENGTH_LONG).show();
Intent intentMain = new Intent(context, MainActivity.class);
intentMain.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intentMain);
if (isConnectedToInternet(context)) {
UpcomingFragment.getInstance().setAlarm(-1);
UpcomingFragment.getInstance().update();
} else {
//a day from now
UpcomingFragment.getInstance().setAlarm(-2);
}
}
}
public static long getAlermTimeInMillis(){
return alarmTime;
}
private boolean isConnectedToInternet(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork= connectivityManager.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
}
NextTuesday类
public class NextTuesday {
public static Calendar nextDayOfWeek(int dow) {
Calendar date = Calendar.getInstance();
int diff = dow - date.get(Calendar.DAY_OF_WEEK);
if (!(diff > 0)) {
diff += 7;
}
date.add(Calendar.DAY_OF_MONTH, diff);
return date;
}
public static String dateInString(int day){
Calendar date = nextDayOfWeek(day);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String dateString = format1.format(date.getTime());
return dateString;
}
}
片段的setAlarm()
public void setAlarm(int i){
AlarmManager alarmMgr = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getActivity(), UpdateReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(getActivity(), 0, intent, 0);
if (i == 0) {
alarmTime = 0;
Toast.makeText(getActivity(), "Setting alarm for first time", Toast.LENGTH_LONG).show();
} else if (i == -2) {
alarmTime = new GregorianCalendar().getTimeInMillis()+24*60*60*1000; // a day
Toast.makeText(getActivity(), "NO WIFI RESTARTING AFTER A DAY" + alarmTime, Toast.LENGTH_LONG).show();
}else {
alarmTime = UpdateReceiver.getAlermTimeInMillis();
Toast.makeText(getActivity(), "Setting alarm for next tuesday", Toast.LENGTH_LONG).show();
}
// With setInexactRepeating(), you have to use one of the AlarmManager interval
// constants--in this case, AlarmManager.INTERVAL_DAY.
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, alarmTime,
AlarmManager.INTERVAL_DAY, alarmIntent);
}
更新()
public void update(){
// Formulate the request and handle the response.
try {
dataList.clear();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, (String) null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Toast.makeText(getActivity(), "LOADING FROM VOLLEY", Toast.LENGTH_LONG).show();
Log.e(TAG, "FROM VOLLEY");
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(getActivity().openFileOutput("data.json", Context.MODE_PRIVATE));
outputStreamWriter.write(response.toString());
outputStreamWriter.close();
sendJsonRequest();
} catch (IOException e) {
Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Error Fetching New Data. Check your Wi-Fi", Toast.LENGTH_LONG).show();
}
});
//remove cash
jsonObjectRequest.setShouldCache(false);
mRequestQueue.add(jsonObjectRequest);
} catch (Exception e){
Log.e(TAG, e.getMessage());
}
}
感谢任何类型的帮助,当应用程序崩溃时,不会打印堆栈跟踪。