Run code in background thread in Android service

public class MyAndroidService extends Service { private static final String TAG = MyAndroidService.class.getSimpleName(); public static boolean isRunning = false; private boolean runFlag = false; private MyAndroidThread thread; @Override public void onCreate() { super.onCreate(); thread = new MyAndroidThread(); } public int onStartCommand(Intent intent, int flags, int startId) { Log.e(TAG, "[onStartCommand]"); isRunning = true; if (!runFlag) { this.runFlag = true; this.thread.start(); } return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); Log.e(TAG, "[onDestory]"); isRunning = false; this.runFlag = false; if (thread != null) this.thread.interrupt(); this.thread = null; } public class MyAndroidThread extends Thread { public MyAndroidThread() { super("MyAndroidThread"); } @Override public void interrupt() { super.interrupt(); // STOP SERVER REQUESTS HERE, UNREGISTER USER, DO LOGOUT, ETC. } @Override public void run() { if (MyAndroidService.this.runFlag) { Log.e(TAG, "[MyAndroidThread]: this is running in background Java thread"); // RUN CODE IN BACKGROUND HERE: COMMUNICATE WITH SERVER, LOGIN/REGISTER USER, ETC. } } } }
Normally an Android service runs in the main UI thread, this means that if you want to run code in background in a service you can either use a Java thread or you can switch to using an Intent Service.

#android #java #code #hint #threads #service

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.