我是新来的,我希望得到一些关于我正在为朋友开发的应用程序的帮助。
我遇到的问题是我试图在后台线程中每隔15分钟创建一个Json请求,不会受到主进程的影响。因此,当主应用程序被杀死时,我仍然希望一个线程继续检查网站上的更新。问题是我在打印的通知中没有获得数据(来自Json请求)。如果我在主类中运行代码,我会打印数据。
请参阅我创建的服务的以下代码。 附:这是我试图开发的第一个应用程序,所以如果我有愚蠢的错误,我会提前对不起.. :)
public class MyService extends JobService {
BackgroundTask backgroundTask;
NotificationCompat.Builder notify;
private static final int notify_ID = 258799;
@Override
public boolean onStartJob(final JobParameters jobParameters) {
notify = new NotificationCompat.Builder(this);
notify.setAutoCancel(true);
backgroundTask = new BackgroundTask()
{
@Override
protected void onPostExecute(String s){
notify.setSmallIcon(R.drawable.ic_launcher_background);
notify.setTicker("This is a ticker");
notify.setWhen(System.currentTimeMillis());
notify.setContentTitle("Stream check");
notify.setContentText(s);
//Build notification
NotificationManager mn = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mn.notify(notify_ID,notify.build());
jobFinished(jobParameters, false);
}
};
backgroundTask.execute();
return true;
}
@Override
public boolean onStopJob(JobParameters jobParameters) {
return true;
}
//new background class on new thread
public class BackgroundTask extends AsyncTask<Void,Void,String>
{
String result;
String url = "www.google.com";
@Override
protected String doInBackground(Void... voids){
RequestQueue requestQueue= Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest objectRequest= new JsonObjectRequest(
Request.Method.GET,
url,
null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
//Log.e("Rest response: ",response.toString());
result = response.toString();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Rest error response: ", error.toString());
}
}
);
requestQueue.add(objectRequest);
return result;
}
}
}