Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save virendersran01/9c1323e20ba422bb970b92e97d5478b7 to your computer and use it in GitHub Desktop.
Save virendersran01/9c1323e20ba422bb970b92e97d5478b7 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