Android - 有关Service类中AsyncTask的说明

时间:2018-02-02 03:54:00

标签: java android service android-asynctask

我每3秒运行一次服务任务,服务将执行asynctask以检查sqlite并将数据发送到服务器

代码myService.class

/* import foo.foo.foo */

public class myService extends Service {
    public Runnable mRunnable = null;
    private boolean mRunning = false;
    Handler mHandler = new Handler();
    IBinder mBinder = new LocalBinder();

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

    public class LocalBinder extends Binder {
        public myService getServerInstance() {
            return myService.this;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("Service"," onstart kepanggil ga?");
        mRunnable = new Runnable() {
            @Override
            public void run() {
                Log.d("Service","SERVICE RUN");
                SharedPreferences pref = getSharedPreferences("wit_player_shared_preferences", MODE_PRIVATE);
                String servcheck = pref.getString("serviceChecker", null);
                DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                int countFlagAuditID = db.getCountFlagAuditID();
                int countNeedToSend = db.getCountContact();
                if (countNeedToSend > 0){
                    Log.d("countNeedToSend : ", String.valueOf(countNeedToSend));
                    sending a = new sending();
                    try {
                        if(servcheck.equals("no")){
                            Log.d("Service","SERVICE TRY CALL SENDING");
                            a.execute().get();
                        }
                    } catch (InterruptedException | ExecutionException e) {
                        e.printStackTrace();
                    }
                }
                if (countFlagAuditID > 0){
                    Log.d("countFlagAuditID : ", String.valueOf(countFlagAuditID));
                    if(servcheck.equals("no")){
                        Log.d("Service","SERVICE TRY CALL SENDGET");
                        sendget b = new sendget();
                        b.execute();
                    }
                }
                db.close();
            mHandler.postDelayed(mRunnable, 3 * 1000);
            }
        };
        mHandler.postDelayed(mRunnable, 3 * 1000);
        return START_STICKY;
    }
    //async task
    private class sending extends AsyncTask<Void, Void, String >
    {
      @Override
      protected void onPreExecute() {
        Log.i("SENDING", "start sending");
        SharedPreferences pref = getSharedPreferences("wit_player_shared_preferences", MODE_PRIVATE);
        pref.edit().putString("serviceChecker", "yes").commit();
        if (serv.equals("yes")){
            Log.i("stop service", "service di stop");
            stopSelf();
        }
      }
      @Override
      protected String doInBackground(Void... params) {
      //send data to server
      }
      @Override
      protected void onPostExecute(String result) {
         SharedPreferences pref = getSharedPreferences("wit_player_shared_preferences", MODE_PRIVATE);
         pref.edit().putString("serviceChecker", "no").commit();
      }
    }
    private class sendget extends AsyncTask<Void, Void, String >
    {
      //execute post to server
    }
}

我有一个关于上述代码的问题列表:

  1. 让我的服务每3秒运行一次,我需要声明两次mHandler.postDelayed(mRunnable, 3 * 1000);,如果我宣布代码只有一个,服务会运行一次,为什么会这样?
  2. on sending asynctask我在stopSelf()上添加onPreExecute()表示该服务将停止,但为什么doInBackground()任务会继续运行?

1 个答案:

答案 0 :(得分:0)

尝试使用计时器而不是处理程序

private final Timer mTimer = new Timer();

mTimer.scheduleAtFixedRate(new LocationUpdateTask(), 0, 3000);

private class LocationUpdateTask extends TimerTask {
    @Override
    public void run() {

        try {
            //Do your stuff
        } catch (Exception e) {
            // TODO: handle exception

        } catch (ExceptionInInitializerError in) {

        }


    }
}