长时间从服务器获取数据

时间:2016-05-24 09:01:36

标签: android multithreading android-asynctask

我需要使用能够在应用程序处于后台时从服务器获取数据的服务开发应用程序。当应用程序是后台时,我使用了一个线程以便长时间运行ThreadWorker()。 (之前我在我的应用程序中做了一个帖子:当应用程序为onStop()时,线程停止了,这对我不利。所以我决定去服务)

public class ServiceBG extends Service
{    
public class LocalBinder extends Binder {
    ServiceBG getService() {
        return ServiceBG.this;
    }
}


private final IBinder mBinder = new LocalBinder();

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return mBinder;
}

@Override
public void onCreate() {
    InitializeVariable();
}

private void InitializeVariable()
{
    this.mContext = this;
    this.working = false;
    this.canRun = true;
    this.serverCOM = new ServerCOM(myUrl,departmentID);
    ThreadWorker();
}

private void ThreadWorker()
{
    thread = new Thread(new Runnable() {
        @Override
        public void run() {
            int i=0 ;
            while (canRun)
            {                   
                try {
                    while (!serverCOM.hasActiveInternetConnection(mContext)) {
                        try {
                            Thread.sleep(4000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    list = serverCOM.GetFirmwareDeviceNameList();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                if(listDevice!=null) {
                    Log.d("serviceBG", String.valueOf(list.size()));

                    if (list.size() > 0) {


                        working = true;

                        Intent intent = new Intent();
                        intent.setAction(MY_ACTION);

                        intent.putExtra("DATAPASSED",list.get(0));

                        sendBroadcast(intent);
                        //complete action
                    }
                }

                try {
                    FirmwareUpdaterThread.sleep(4000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    });
    thread.start();

}



@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    //TODO do something useful
    return Service.START_STICKY;
}
}

我的ServerCOM对象是这样的:

 public class ServerCOM {
 public List<String> GetFirmwareDeviceNameList()
{
    AsyncGetNames asyncGetNames=new AsyncGetNames();
    asyncGetNames.execute(URL);
    try {
        this.NameList =asyncGetNames.get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    return this.NameList;
}

public boolean hasActiveInternetConnection(Context context) {
    if (isNetworkAvailable(context)) {
        try {
            HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
            urlc.setRequestProperty("User-Agent", "Test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500);
            urlc.connect();
            return (urlc.getResponseCode() == 200);
        } catch (IOException e) {
            Log.e(LOG_TAG, "Error checking internet connection", e);
        }
    } else {
        Log.d(LOG_TAG, "No network available!");

    }
    return false;
}

private boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivityManager  = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null;
}


 private class AsyncGetNames extends AsyncTask<String, String, List<String>>
{
    public AsyncGetNames()
    {
    }
    @Override
    public List<String> doInBackground(String... params){
        List<String> list = null;
        try {
            URL url = new URL(params[0]);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoInput(true);
            urlConnection.setRequestMethod("GET");
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("Accept", "*/*");
            InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
            //readStream(in);
            String resultString = Operations.convertStreamToString(inputStream);
            inputStream.close();

            String[] list1 = new Gson().fromJson(resultString, String[].class);
            list= Arrays.asList(list1);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
}
 }

当我启动此服务时,我可以从服务器获取数据。在大约半小时之后,该服务不再能够发送请求(我在Android Studio的Logcat中看到了这一点)。似乎请求线程进入休眠状态。这个线程和AsyncTask请求之间是否存在一些可能的交互?

0 个答案:

没有答案