【问题标题】:Android not make GET request after app closing from Service从服务关闭应用程序后,Android 不发出 GET 请求
【发布时间】:2018-09-18 03:21:36
【问题描述】:

首先抱歉,如果之前已经提出过此类问题。

我想制作一个应用程序,它可以创建一个GET request 或简单的Open A URL 来告诉服务器应用程序现在已关闭,不需要输出,只需加载 URL。

我已经尝试过的:

  1. 我使用了Volley,但不幸的是在这种情况下它不是一个解决方案。

  2. 我也尝试过让AsyncTask 成为朋友,但它很奇怪,它也不起作用

只有一行简单的代码行得通:

URL url = new URL("URL HERE"); 
InputStream stream = url.openStream();

但是导致NetworkException。我只想在应用关闭后从服务中执行一个 URL。

示例代码将不胜感激

提前致谢

更新部分

public class Service extends android.app.Service {

    public int isExecuted = 0;


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("rrLOG", "Service Started");
        checkClosing();
        return Service.START_NOT_STICKY;
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        super.onTaskRemoved(rootIntent);
        Log.e("rrLOG", "Service Stopped");
        updateServer(UPDATE_OFFLINE);
        stopSelf();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e("rrLOG", "Service Destroyed");
        updateServer(UPDATE_OFFLINE);
        stopSelf();
    }

    public void checkClosing(){

        new Timer().scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                if (Helper.isAppRunning(Service.this, getPackageName())) {
                    Log.i("rrLOG", "App Is Running");
                } else {
                    Log.i("rrLOG", "App Is Not Running");
                    updateServer(UPDATE_OFFLINE);
                    stopSelf();
                }
            }
        }, 0, 500);//put here time 1000 milliseconds=1 second

    }

    static class RequestTask extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... uri) {
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response;
            String responseString = null;
            try {
                response = httpclient.execute(new HttpGet(uri[0]));
                StatusLine statusLine = response.getStatusLine();
                if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    response.getEntity().writeTo(out);
                    responseString = out.toString();
                    out.close();
                } else{
                    //Closes the connection.
                    response.getEntity().getContent().close();
                    throw new IOException(statusLine.getReasonPhrase());
                }
            } catch (ClientProtocolException e) {
                //TODO Handle problems..
            } catch (IOException e) {
                //TODO Handle problems..
            }
            return responseString;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            //Do anything with response..
        }
    }

    public void updateServer(final String urlJsonArry) {

        Log.i("rrLOG", urlJsonArry);

        new RequestTask().execute(urlJsonArry);

    }


}

UPDATE2 部分

public class Service extends android.app.Service {

    public int isExecuted = 0;


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("rrLOG", "Service Started");
        checkClosing();
        return Service.START_NOT_STICKY;
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        //super.onTaskRemoved(rootIntent);
        Log.e("rrLOG", "Service Stopped");
        updateServer(UPDATE_OFFLINE);
    }

    @Override
    public void onDestroy() {
        //super.onDestroy();
        Log.e("rrLOG", "Service Destroyed");
        updateServer(UPDATE_OFFLINE);
    }

    public void checkClosing(){

        new Timer().scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                if (Helper.isAppRunning(Service.this, getPackageName())) {
                    Log.i("rrLOG", "App Is Running");
                } else {
                    Log.i("rrLOG", "App Is Not Running");
                    updateServer(UPDATE_OFFLINE);
                }
            }
        }, 0, 500);//put here time 1000 milliseconds=1 second

    }

    public class NetworkTask extends AsyncTask<Void,Void,String> {

        @Override
        protected String doInBackground(Void... voids) {
            Log.i("rrLOG", String.valueOf(isExecuted));
            URL url = null; //get URL from your uri object
            try {
                url = new URL(UPDATE_OFFLINE);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            try {
                InputStream stream = url.openStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Log.i("rrLOG", String.valueOf(url));
            return String.valueOf(url);
        }

        @Override
        protected void onPostExecute(String result) {
            Log.i("rrLOG", "onPostExecute");
            super.onPostExecute(result);
            stopSelf();
        }
    }


    public void updateServer(String urlJsonArry) {

        Log.i("rrLOG", urlJsonArry);

            if(isExecuted == 0) {
                new NetworkTask().execute();
                isExecuted = 1;
            }

    }


}

【问题讨论】:

标签: android service android-asynctask android-volley


【解决方案1】:

在 Android 中,每个网络请求都将在工作线程上进行。该线程与 UI 线程不同。您必须通过AsyncTask 在后台发出网络请求。示例如下:

public class NetworkTask extends AsyncTask<Void,Void,Void> {
    public Void doInBackground() {
        // Here you can make network request 
    }
} 

现在您可以在 Service 中发出此请求,因此即使您的活动被终止,网络请求也会通过。

请确保您在 Manifest 中拥有 Internet 权限。

编辑:

我检查了有问题的附加代码,您试图在触发网络请求的同时停止服务。如果你这样做,你的网络请求在被系统杀死之前甚至都不会完成。

您可以在网络请求完成后终止服务,即在 onPostExecuteAsyncTask 内。

【讨论】:

  • 好吧,兄弟,看来是我的错误.. 我还没有做出改变,我会做出改变,让我们看看会发生什么
  • 我注意到没有调用 onPostExecute 我通过 Log.i 进行检查
  • 检查 UPDATE2 部分
  • 还有什么特殊需要,你不想通过Timer调用你的updateServer方法吗?
  • 我只是想准确地向服务器发送响应,我不想让那个应用错过一个镜头
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-09
  • 2011-12-27
相关资源
最近更新 更多