Skip to content

Instantly share code, notes, and snippets.

@MrCrambo
Created February 10, 2020 15:34
Show Gist options
  • Save MrCrambo/0f29d6e0068dfaa9a1fcf557b1054fd3 to your computer and use it in GitHub Desktop.
Save MrCrambo/0f29d6e0068dfaa9a1fcf557b1054fd3 to your computer and use it in GitHub Desktop.
public class ForegroundService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("inputExtra");
createNotificationChannel();
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, YourActivity.class), 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service")
.setContentText(input)
.setSmallIcon(R.drawable.ic_stat_name)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
// here is the code you wanna run in background
return START_NOT_STICKY;
}
private void createNotificationChannel() {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT);
getSystemService(NotificationManager.class).createNotificationChannel(serviceChannel);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment