有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

后台异步任务中的java Json请求未返回数据

我是新来的,我想得到一些关于我正试图为朋友开发的应用程序的帮助

我遇到的问题是,我试图在后台线程中每隔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;
    }
}

}


共 (0) 个答案