Thread vs Service vs Alarm vs SyncAdapter



Thread vs Service vs Alarm vs SyncAdapter

  • Create a Thread if you need to perform work outside your main thread, but only while the user is interacting with your application.
  • Create a Service if you need a component that can run in the background even when the user is not interacting with your application.
  • Alarms operate outside of your application, so you can use them to trigger events or actions even when your app is not running, and even if the device itself is asleep.
  • While efficiently coordinating usage of system resources, SyncAdapter provides a built-in framework to automate & synchronize data between an Android device and web servers based on a variety of triggers.


Usage Overview

    AsyncTask:
        FetchWeatherTask weatherTask = new FetchWeatherTask(getActivity());
        weatherTask.execute(location);
        :
        doInBackground() { contentProvider.bulkInsert(); }


    Service:
        Intent intent = new Intent(getActivity(), SunshineService.class);
        intent.putExtra(SunshineService.LOCATION_KEY, location);
        getActivity().startService(intent);
        :
        onHandleIntent() { contentProvider.bulkInsert(); }


    Alarm:
        alarmIntent.putExtra(SunshineService.LOCATION_KEY, location);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, PendingIntent.FLAG_ONE_SHOT); //getBroadcast(context, 0, i, 0);
        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 5000, pendingIntent);
        :
        static public class AlarmReceiver extends BroadcastReceiver {
            public void onReceive() { startService(); }
        }
        onHandleIntent() { contentProvider.bulkInsert(); }


    SyncAdapter:
        ContentResolver.requestSync(getSyncAccount(context),
                context.getString(R.string.content_authority), bundle);
        :
        onPerformSync() { contentProvider.bulkInsert(); }


No comments:

Post a Comment