Skip to content

Instantly share code, notes, and snippets.

@Sardorbekcyber
Last active January 26, 2024 13:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sardorbekcyber/bbf36c84175a31f5c5c247e1a88db713 to your computer and use it in GitHub Desktop.
Save Sardorbekcyber/bbf36c84175a31f5c5c247e1a88db713 to your computer and use it in GitHub Desktop.
//Service
@Override
public void onCreate() {
LocalBroadcastManager
.getInstance(this)
.registerReceiver(new ServiceEchoReceiver(), new IntentFilter("ping"));
//do not forget to deregister the receiver when the service is destroyed to avoid
//any potential memory leaks
}
private class ServiceEchoReceiver extends BroadcastReceiver {
public void onReceive (Context context, Intent intent) {
LocalBroadcastManager
.getInstance(this)
.sendBroadcastSync(new Intent("pong"));
}
}
//Activity
bool serviceRunning = false;
protected void onCreate (Bundle savedInstanceState){
LocalBroadcastManager.getInstance(this).registerReceiver(pong, new IntentFilter("pong"));
LocalBroadcastManager.getInstance(this).sendBroadcastSync(new Intent("ping"));
if(!serviceRunning){
//run the service
}
}
private BroadcastReceiver pong = new BroadcastReceiver(){
public void onReceive (Context context, Intent intent) {
serviceRunning = true;
}
}
//Check if Service Activite
fun Context.isMyServiceRunning(serviceClass: Class<out Service>) = try {
(getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager)
.getRunningServices(Int.MAX_VALUE)
.any { it.service.className == serviceClass.name }
} catch (e: Exception) {
false
}
//Manifest
<receiver
android:name=".sam.receiver.BootCompleteReceiver"
android:enabled="true"
android:exported="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="android.intent.action.REBOOT" />
</intent-filter>
</receiver>
//BootCompletion Receiever
@AndroidEntryPoint
class BootCompleteReceiver: BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (Intent.ACTION_BOOT_COMPLETED == intent?.action) {
if (pref.getUserToken() != null) {
context?.checkAndRunForegroundService()
}
}
}
}
//Check and restart forground service
fun Context.checkAndRunForegroundService() {
if (!isServiceRunning(GetLocationService::class.java.name)) {
val intent = Intent(this, GetLocationService::class.java)
ContextCompat.startForegroundService(this, intent)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment