Like Activity to stop Runable flow in IntentService
-
public class ChronometrService extends IntentService { public static final String ACTION_RESUME_CLICK = "resumeClick"; public static final String ACTION_STOP_SERVICE = "stopService"; public static final String RESPONSE_RESUME_CLICK = "responseResumeClick"; public static final String EXTRA_PARAM = "EXTRA_PARAM"; private static final String TAG = "ChronometrService"; private final Handler handler = new Handler(); private static long mTotalMilis; private long mLastMilis; private long mElapsedTime; private long mCurrentMilis; public ChronometrService() { super("ChronometrService"); } public static void resumeClick(Context context, long totalMilis) { mTotalMilis = totalMilis; Intent intent = new Intent(context, ChronometrService.class); intent.setAction(ACTION_RESUME_CLICK); context.startService(intent); } public static void stopService(Context context) { Intent intent = new Intent(context, ChronometrService.class); intent.setAction(ACTION_STOP_SERVICE); context.startService(intent); } @Override protected void onHandleIntent(Intent intent) { if (intent != null) { final String action = intent.getAction(); Log.d(TAG, action); switch (action) { case ACTION_RESUME_CLICK: mLastMilis = mElapsedTime = System.currentTimeMillis(); sendUpdatesToUI.run(); break; case ACTION_STOP_SERVICE: //todo stop method } } } private Runnable sendUpdatesToUI = new Runnable() { public void run() { mCurrentMilis = System.currentTimeMillis(); mElapsedTime = mCurrentMilis - mLastMilis; mLastMilis = mCurrentMilis; mTotalMilis += mElapsedTime; responseResumeClick(mTotalMilis); System.out.println(TAG + " mTotalMilis = " + mTotalMilis); handler.postDelayed(this, 100); // 0.1 seconds } }; public void responseResumeClick(long totalMilis) { Intent intent = new Intent(RESPONSE_RESUME_CLICK); intent.putExtra(EXTRA_PARAM, totalMilis); LocalBroadcastManager bm = LocalBroadcastManager.getInstance(this); bm.sendBroadcast(intent); } }
-
very simple:
case ACTION_STOP_SERVICE: handler.removeCallbacks(sendUpdatesToUI);