Android:如何每5秒通过服务发送http请求

时间:2017-07-25 10:17:03

标签: java android json web-services android-service

我想每5秒钟从webservices请求json数据。因为我不想向用户展示,所以我在服务中做这些事情。代码中没有错误,但它没有按预期在日志中显示任何输出。

以下是代码:

protected void onHandleIntent(Intent intent) {

    final String driverId = intent.getStringExtra("DriverId");

    new Handler().postDelayed(new Runnable() {
        public void run() {
            HttpHandler sh = new HttpHandler();

            // making request to url and getting respose
            String jsonStr = sh.makeServiceCall(url + "?cno=" + driverId + "&lat=0&lon=79");

            Log.e("ServicesClass", "Response from url: " + jsonStr);

            if (jsonStr != null) {
                String temp = jsonStr;
                String finals = temp.replace("<string xmlns=\"http://tempuri.org/\">", "");
                Log.e(TAG, "Response from url at Service Class: " + jsonStr);

            } else {
                Log.e(TAG, "Response from url at Service Class: " + jsonStr);
            }
        }
    }, 5000);
}

makeServiceCall的代码:

public String makeServiceCall(String reqUrl){

        String response = null;

        try {

            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");

             //read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        }catch (MalformedURLException e){
            Log.e(TAG, "MalformedException: " +e.getMessage());
        }catch (ProtocolException e){
            Log.e(TAG, "Protocal Exception: " +e.getMessage());
        }catch (IOException e){
            Log.e(TAG, "IOException: " +e.getMessage());
        }catch (Exception e){
            Log.e(TAG, "Exception: " +e.getMessage());
        }
        return response;
    }

    private String convertStreamToString(InputStream is){

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = reader.readLine()) != null){

                sb.append(line).append('\n');
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                is.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

任何人都可以帮忙从代码中找出可能出错的地方吗?

1 个答案:

答案 0 :(得分:0)

使用闹钟管理器设置重复闹钟。

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent myIntent = new Intent(this, RepeatingService.class);
    PendingIntent pendingIntent = PendingIntent.getService(this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, 5000, 5000, pendingIntent);

RepeatingService使用IntentService,因为当作业完成时,它会自动停止。

class RepeatingService extends IntentService{

 override fun onHandleIntent(intent: Intent?) {
   // do your stuff like async or anyother task.
}

}