如何使服务不断循环?

时间:2018-06-18 16:39:26

标签: java android service

我有一个由BroadcastReceiver启动的服务,它在启动完成时激活。所以服务开始了,我的onStartCommand上有以下内容

public int onStartCommand(Intent intent, int flags, int startId) {
    mQueue = Volley.newRequestQueue(getApplicationContext());

      //FROM NOW ON I WANT IT TO LOOP CONSTANTLY
            JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, API.getDeviceTypes(), null, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                    try {
                        processResponse(response);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("mytag", "Error de response");
                    error.printStackTrace();
                }
            });

            mQueue.add(request);
          // LOOP TILL HERE



    return START_STICKY;
}

我希望服务能够不断地或至少每3分钟或更长时间发出一次请求。我怎样才能做到这一点? 截至目前,服务开始正常,但当然它只执行一次这些行。

2 个答案:

答案 0 :(得分:1)

AlarmManager 可用于定期执行任务:

假设我们想在每3分钟后执行一项任务。

  

setRepeating()允许以精确的重复时间安排警报。

AlarmManager mgr=(AlarmManager)ctxt.getSystemService(Context.ALARM_SERVICE);
mgr.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
                              180000+System.currentTimeMillis(),
                                  getPendingIntent(ctxt));

你可以获得待定意图

// Specify ur receiver
    private PendingIntent getPendingIntent(Context ctxt) {
        Intent i=new Intent(ctxt, APIReceiver.class);
        return(PendingIntent.getBroadcast(ctxt, 0, i, 0));
    }

您可以致电:

停止闹钟管理器
public void stopAlarmManager()
{          
    if(alarmMgr != null)
       alarmMgr.cancel(pendingIntent);
}

答案 1 :(得分:1)

  

根据您的要求使用Handler不要使用Thread它会阻止   主要UI线程

private Handler handler;
private Runnable runnable;


public int onStartCommand(Intent intent, int flags, int startId) {
      handler = new Handler();
        if (runnable != null) {
            runnable = null;
        }
        runnable = new Runnable() {
            @Override
            public void run() {
                // do your stuff here, called every 3 second
                mQueue = Volley.newRequestQueue(getApplicationContext());

      //FROM NOW ON I WANT IT TO LOOP CONSTANTLY
            JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, API.getDeviceTypes(), null, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                    try {
                        processResponse(response);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("mytag", "Error de response");
                    error.printStackTrace();
                }
            });

            mQueue.add(request);
                h.postDelayed(this, 3000);
            }
        };

// start it with:
handler.post(runnable);

 return START_STICKY;


}

并且不要忘记根据需要在onDestroy()或onstop中删除处理程序回调

    handler.removeCallbacks(runnable);
    handler.removeMessages(0);

从这里阅读为什么处理程序更好 difference between Thread and Handler