简体   繁体   中英

Android - Explanation about AsyncTask in Service class

I've a task to running service every 3 second, the service will execute asynctask to checking sqlite and sending data into server

Code of 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
    }
}

I've a list of question about the code above:

  1. to let my service run every 3sec I need to declare twice of mHandler.postDelayed(mRunnable, 3 * 1000); , if I'm declare the code just one, the service will run once, why it can be like that?
  2. on sending asynctask I've add stopSelf() on onPreExecute() that mean the service will stop, but why doInBackground() task keep run?

Try to use timer instead of handler

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) {

        }


    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM