Last active
October 30, 2016 18:59
-
-
Save cosic/487ef46a9e7bf2fd85666396867e6091 to your computer and use it in GitHub Desktop.
Android Studio template for creating of Custom Service
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ${PACKAGE_NAME}; | |
import android.app.Service; | |
import android.content.Intent; | |
import android.os.IBinder; | |
#parse("File Header.java") | |
public class ${NAME} extends Service { | |
private int mServiceId; | |
private Reboot${NAME}BroadcastReceiver mReboot${NAME}BroadcastReceiver; | |
@Override | |
public void onCreate() { | |
super.onCreate(); | |
mReboot${NAME}BroadcastReceiver = new Reboot${NAME}BroadcastReceiver(); | |
registerReceiver(mReboot${NAME}BroadcastReceiver, new IntentFilter(Reboot${NAME}BroadcastReceiver.ACTION)); | |
} | |
@Override | |
public void onDestroy() { | |
unregisterReceiver(mReboot${NAME}BroadcastReceiver); | |
super.onDestroy(); | |
} | |
@Override | |
public int onStartCommand(Intent intent, int flags, int startId) { | |
Timber.d("Start ${NAME} id=%s", startId); | |
mServiceId = startId; | |
rebootService(); | |
return Service.START_STICKY; | |
} | |
private void rebootService() { | |
// TODO main code; | |
} | |
private void stopThisService() { | |
stopSelf(mServiceId); | |
} | |
@Override | |
public IBinder onBind(Intent intent) { | |
return null; | |
} | |
public static boolean isServiceRunning(Context context) { | |
return ServiceUtils.isServiceRunning(context, ${NAME}.class); | |
} | |
public static void startService(@NonNull Context context) { | |
if (isServiceRunning(context)) { | |
Intent intent = new Intent(Reboot${NAME}BroadcastReceiver.ACTION); | |
context.sendBroadcast(intent); | |
return; | |
} | |
context.startService(new Intent(context, ${NAME}.class)); | |
} | |
public static void stopService(@NonNull Context context) { | |
context.stopService(new Intent(context, ${NAME}.class)); | |
} | |
/** | |
* If you use static startService(...) method and service already started | |
* it doesn't get a new call of onStartCommand(...) method. | |
* Instead of will be called rebootService() method; | |
*/ | |
public final class Reboot${NAME}BroadcastReceiver extends BroadcastReceiver { | |
public static final String ACTION = BuildConfig.APPLICATION_ID + "Reboot${NAME}BroadcastReceiver.ACTION"; | |
@Override | |
public void onReceive(Context context, Intent intent) { | |
rebootService(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment