【问题标题】:Android: How to send http request via service every 5 secondsAndroid:如何通过服务每 5 秒发送一次 http 请求
【发布时间】:2017-12-31 04:54:41
【问题描述】:

我想每 5 秒后从 web 服务请求 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();
    }

谁能帮忙从代码中找出可能出错的地方?

【问题讨论】:

  • 您可以为此使用 Intent 服务,并且您不需要为此使用 asyncTask
  • 我使用了intentService,检查编辑过的帖子,但同样的问题存在。
  • 有什么问题
  • 如您所见,我正在记录 Log.e("ServicesClass", "Response from url:" + jsonStr);但在 logcat 中没有可见的日志,这意味着代码没有执行或其他我无法弄清楚的东西
  • makeServiceCall() 中添加日志记录或设置断点并单步执行。您需要缩小问题所在的范围。从您发布的代码中看不出任何明显的东西。

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


【解决方案1】:

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

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

}

【讨论】:

  • 请检查已编辑的帖子,我使用了 intentService 但存在同样的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-22
  • 2012-03-23
  • 2023-04-07
  • 2018-07-12
  • 2021-01-17
  • 1970-01-01
相关资源
最近更新 更多