Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Start foreground service
- Intent intent = new Intent(this, MyForeGroundService.class);
- intent.setAction(MyForeGroundService.ACTION_START_FOREGROUND_SERVICE);
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
- startForegroundService(intent);
- }else{
- startService(intent);
- }
- public class MyForeGroundService extends Service implements LocationListener {
- public MyForeGroundService() {
- }
- @Override
- public IBinder onBind(Intent intent) {
- // TODO: Return the communication channel to the service.
- throw new UnsupportedOperationException("Not yet implemented");
- }
- @Override
- public void onCreate() {
- super.onCreate();
- wakeLock();
- }
- @SuppressLint("InvalidWakeLockTag")
- public void wakeLock() {
- pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
- assert pm != null;
- wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "partialwl");
- wl.acquire();
- }
- public void stopWakeLock() {
- wl.release();
- }
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- if (intent != null) {
- String action = intent.getAction();
- switch (action) {
- case ACTION_START_FOREGROUND_SERVICE:
- wakeLock();
- startForegroundService();
- break;
- case ACTION_STOP_FOREGROUND_SERVICE:
- stopWakeLock();
- stopForegroundService();
- break;
- case ACTION_PLAY:
- Intent openMap= new Intent(this,Map.class);
- startActivity(openMap);
- break;
- case ACTION_PAUSE:
- break;
- }
- }
- return START_STICKY;
- }
- /* Used to build and start foreground service. */
- private void startForegroundService() {
- Log.d(TAG_FOREGROUND_SERVICE, "Start foreground service.");
- // Create notification default intent.
- Intent intent = new Intent(this,Map.class);
- PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
- // Create notification builder.
- NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
- //Go back to Map activity if user press at the notification
- builder.setContentIntent(pendingIntent)
- .setContentTitle("gEKOning...")
- .setContentText("Tap to open gEKOn app");
- builder.setWhen(System.currentTimeMillis());
- builder.setSmallIcon(R.mipmap.ic_launcher);
- Bitmap largeIconBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
- builder.setLargeIcon(largeIconBitmap);
- // Make the notification max priority.
- builder.setPriority(Notification.PRIORITY_MAX);
- // Make head-up notification.
- builder.setFullScreenIntent(pendingIntent, true);
- // Build the notification.
- Notification notification = builder.build();
- // Start foreground service.
- startForeground(1, notification);
- }
- private void stopForegroundService() {
- Log.d(TAG_FOREGROUND_SERVICE, "Stop foreground service.");
- // Stop foreground service and remove the notification.
- stopForeground(true);
- // Stop the foreground service.
- stopSelf();
- }
Add Comment
Please, Sign In to add comment