Created
February 10, 2020 15:34
-
-
Save MrCrambo/0f29d6e0068dfaa9a1fcf557b1054fd3 to your computer and use it in GitHub Desktop.
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
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