Advertisement
slemos96

Untitled

Dec 4th, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.25 KB | None | 0 0
  1. package com.example.backgroundappexample;
  2.  
  3. import android.app.Notification;
  4. import android.app.NotificationManager;
  5. import android.app.PendingIntent;
  6. import android.app.Service;
  7. import android.content.Intent;
  8. import android.os.Binder;
  9. import android.os.Bundle;
  10. import android.os.IBinder;
  11.  
  12. public class BackgroundService extends Service {
  13.     private NotificationManager mNM;
  14. Bundle b;
  15. Intent notificationIntent;
  16. private final IBinder mBinder = new LocalBinder();
  17. private String newtext;
  18.  
  19. public class LocalBinder extends Binder {
  20.     BackgroundService getService() {
  21.         return BackgroundService.this;
  22.     }
  23. }
  24.  
  25. @Override
  26. public void onCreate() {
  27.     mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
  28.  
  29.     newtext = "BackGroundApp Service Running";
  30.  
  31.     Notification notification = new Notification(R.drawable.ic_launcher, newtext,System.currentTimeMillis());
  32.     PendingIntent contentIntent = PendingIntent.getActivity(BackgroundService.this, 0, new Intent(BackgroundService.this,   BackgroundAppExample.class), 0);
  33.     notification.setLatestEventInfo(BackgroundService.this,"BackgroundAppExample", newtext, contentIntent);
  34.     mNM.notify(R.string.local_service_started, notification);
  35.     notificationIntent = new Intent(this, BackgroundAppExample.class);
  36.     showNotification();    
  37. }
  38.  
  39. public int onStartCommand(Intent intent, int flags, int startId) {
  40.     return START_STICKY;
  41. }
  42. public void onDestroy() {
  43.     mNM.cancel(R.string.local_service_started);
  44.     stopSelf();
  45. }
  46. private void showNotification() {
  47.     CharSequence text = getText(R.string.local_service_started);
  48.  
  49.     Notification notification = new Notification(R.drawable.ic_launcher, text, System.currentTimeMillis());
  50.     PendingIntent contentIntent = PendingIntent.getActivity(this, 0,new Intent(this, BackgroundAppExample.class), 0);
  51.     notification.setLatestEventInfo(this, "BackgroundAppExample",newtext, contentIntent);
  52.     notification.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;    
  53.     notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
  54.  
  55.     mNM.notify(R.string.local_service_started, notification);
  56. }
  57. @Override
  58. public IBinder onBind(Intent intent) {
  59.     return mBinder;
  60.  }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement