应用程序从服务关闭后,Android不会发出GET请求

时间:2018-04-08 17:49:08

标签: android service android-asynctask android-volley

首先对不起,如果之前已经提出过这样的问题。

我想创建一个应用程序,使GET request或简单Open A URL告诉服务器现在应用已关闭, 只需加载网址就不需要输出。

我已经尝试过:

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

  2. 我也尝试制作AsyncTask,但认真地说它很奇怪它也不起作用

  3. 只有简单的代码才能起作用:

    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;
                }
    
        }
    
    
    }
    

1 个答案:

答案 0 :(得分:0)

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

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

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

请确保您在Manifest中拥有互联网权限。

修改

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

您可以在网络请求完成后终止服务,即在onPostExecute的{​​{1}}内。