服务调用文件多次

时间:2018-11-03 15:28:29

标签: android service

服务每分钟调用一次位于服务器上的文件。该文件检查数据库中的某些内容。该服务运行良好,但今天疯狂地每秒多次调用该文件。我不知道怎么回事。有没有办法防止服务再次发疯?

这是服务

public class MyService  extends Service {

    private Handler mHandler = new Handler();


    @Override
    public void onCreate() {
    super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    ripeti.run();
    return START_STICKY;
    }

    @Override
    public void onDestroy() {
    mHandler.removeCallbacks(ripeti);
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
    return null;
    }




    public void callbackJsonread(){

    Response.Listener<String> responseListener = new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            // null
        }
    };

    JsonreadRequest jsonreadRequest = new JsonreadRequest(responseListener);
    RequestQueue queue = Volley.newRequestQueue(MyService.this);
    queue.add(jsonreadRequest);

    }

    private Runnable ripeti = new Runnable() {
    @Override
    public void run() {
        callbackJsonread();
        mHandler.postDelayed(this, 60000);
    }
    };


}

MainActivity调用服务的方式如下:

    boolean statusService = isServiceRunning(this, MyService.class);
    if (statusService) {
    // null
    } else {
        Intent intentService = new Intent(this, MyService.class);
        startService(intentService);
    }


public static boolean isServiceRunning(Context context, Class<?> serviceClass) {
    ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

0 个答案:

没有答案