Home android Unsubracted Service Android (Boot, Foreground, Sticky)

Unsubracted Service Android (Boot, Foreground, Sticky)

Author

Date

Category

The main tasks of the program include the execution of methods in the background, for which the Android Services is used.

You need to start Service in such a way that after closing the MainActivity service remained in working condition and could create notifications, as well as in the case of closing the system or reboot, restored yourself.

At the moment, the main problem is to maintain life in MyService after closing the user interface.

Autostart:

In AndroidManifest.xml were spelled out

& lt; use-permission android: name = "android.permission.Receive_Boot_Complete" / & gt;

& nbsp;

& lt; receiver android: name = "ru.package.bootreceiver" & gt;
    & lt; INTENT-FILTER & GT;
      & lt; Action Android: name = "Android.Intent.action.Boot_Completed" / & gt;
    & lt; / Intent-Filter & GT;
& lt; / receivers & gt;

in bootreceiver.java:

@ override
Public Void OnreCeive (Context Context, Intent Intent) {
  INTENT SERVICEINTENT = NEW INTENT (CONTEXT, MYSERVICE.CLASS);
  Context.startService (ServiceIntent);
}

Service:

In AndroidManifest.xml is written:

& lt; service
    Android: name = "ru.package.myService"
    Android: Enabled = "True"
    Android: Exported = "True"
    Android: Process = ": AnyProcessName" & gt;
& lt; / service & gt;

in MyService.java is the following code, with the exception of some parts (the most important elements are described in which errors can be solved to solve the task):

Public void oncreate () {
  super.oncreate ();
  notificationManager = (NotificationManager)
  This.GetSystemService (this.Notification_Service);
}

& nbsp;

Public Intent OnStartCommand (Intent Intent, Int Flags, Int Startid) {
  SendNotification ("Service Started", "Service", "Started");
  Return service.start_sticky;
}

& nbsp;

Public Void SendNotification (String Ticker, String Title, String Text) {
  INTENT NOTIFICATIONINTENT = NEW INTENT (This, MainActivity.class);
  notificationintent.setaction (intent.action_main);
  notificationintent.addcategory (intent.category_launcher);
  PendingIntent ContentIntent = PendingIntent.getActivity (GetApplicationContext (), 0, NotificationIntent, PendingIntent.flag_update_Current);
  NotificationCompat.Builder Builder = New NotificationCompat.Builder (this);
  Builder.SetContentIntent (ContentIntent)
  .setongoing (TRUE) // Invulnerable
  .setticker (Ticker)
  .setcontentTitle (Title)
  .setContentText (Text)
  .setwhen (System.CurrentTimemillis ());
  Notification notification;
  if (android.os.build.version.sdk_int & lt; = 15) {
    Notification = Builder.getNotification (); // API 15 and Lower
  } else {
    notification = Builder.Build ();
  }
  StartForeGround (Default_Notification_ID, Notification);

& nbsp;

@ override
Public Ibinder Onbind (Intent Intent) {
  Return new binder ();
}
@Override
Public Void Onrebind (Intent Intent) {
  super.onrebind (Intent);
}
@Override
Public Boolean Onunbind (Intent Intent) {
  RETURN SUPER.ONUNBIND (INTENT);
}
@Override
Public void onestroy ()
{
  // Removing Any Notifications
  notificationmanager.cancel (default_notification_id);
  // Disabling Service.
  StopSelf ();
  super.ondestroy ();
}

MYSERVICE starts from MainActivity as follows:

Intent IntentService;

& nbsp;

@ override
PROTECTED VOID OnCreate (Bundle SavedInstanceState)
{
  InTentService = New Intent (this, myservice.class);
}

& nbsp;

Public void runservice () {
  Boolean Working = IsmyServiceRunning (MYSERVICE.CLASS);
  if (! Working) {
    StartService (IntentService);
  } else {
    StopService (IntentService);
  }
}

& nbsp;

Public Boolean IsmyServicERunning (class & lt;? & gt; serviceclass) {
  ActivityManager Manager = (ActivityManager) GetSystemService (Context.Activity_Service);
  For (ActivityManager.RunningServiceInfo Service: Manager.GetrunningServices (Integer.max_Value)) {
    if (serviceclass.getname (). Equals (service.service.getclassname ())) {
      RETURN TRUE;
    }
  }
  RETURN FALSE;
}

Please indicate the error allowed during programming, adding them by third-party materials (examples) or keywords to search.


Answer 1, Authority 100%

For adequate work of all the requirements for the “immortal” service, the requirements needed to uninstall the non-working version from the device, after which it is loaded with a fresh assembly. It was caused by it, most likely, it is permits. Building your program I started practically from scratch, so after the first installation application, the number of permissions was not enough to implement the functions of the “immortal” service. At the moment, the application uses only two permissions: notifications and autostart. This thought came across the full performance of the application on all other devices.

I will try to reflect in this answer all the code items necessary for the work of the “immortal” service.

Android Manifest:

& lt; use-permission android: name = "android.permission.Receive_Boot_Completed" / & gt;
& lt; service
  Android: name = ". MYSERVICE"
  Android: Enabled = "True"
  Android: Exported = "True" & gt;
& lt; / service & gt;
& lt; receiver
  Android: Name = ". MyReceiver"
  Android: Permission = "Android.permission.Receive_Boot_Completed"
  Android: Enabled = "True" & gt;
  & lt; INTENT-FILTER & GT;
    & lt; Action Android: name = "Android.Intent.action.Boot_Completed" / & gt;
    & lt; Action Android: name = "Android.Intent.action.QuickBoot_Poweron" / & gt;
    & lt; Action Android: name = "Android.Intent.action.Reboot" / & gt;
    & lt; Category Android: Name = "Android.intent.category.default" / & gt;
  & lt; / Intent-Filter & GT;
& lt; / receivers & gt;

MainActivity:

Public Class MainActivity Extends AppCompatactivity {
  INTENT INTENTSERVICE;
  PROTECTED VOID OnCreate (Bundle SavedInstanceState) {
    Super.ONCREATE (SavedInstanceState);
    InTentService = New Intent (this, myservice.class);
  }
  Public Void Click_Service (View V) {
    If (! ismyServicERunning (myservice.class)) {
      StartService (IntentService);
    } else {
      StopService (IntentService);
    }
  }
  Private Boolean IsmyServicerunning (Class & Lt;? & gt; serviceclass) {
    ActivityManager Manager = (ActivityManager) GetSystemService (Context.Activity_Service);
    For (ActivityManager.RunningServiceInfo Service: Manager.GetrunningServices (Integer.max_Value)) {
      if (serviceclass.getname (). Equals (service.service.getclassname ())) {
        RETURN TRUE;
      }
    }
    RETURN FALSE;
  }
}

MyService:

Public Class MyService Extends Service {
  Private NotificationManager NotificationManager;
  Public Static Final int default_notification_id = 101;
  Public void oncreate () {
    super.oncreate ();
    NotificationManager = (NotificationManager) This.getSystemService (This.Notification_Service);
  } 
Public Int OnStartCommand (Intent Intent, Int Flags, Int Startid) {
    // Send Foreground Notification
    SendNotification ("Tickker", "Title", "Text");
    // Task.
    dotask ();
    // return service.start_sticky;
    Return start_redeliver_intent;
  }
  // Send Custom Notification
  Public Void SendNotification (String Tickker, String Title, String Text) {
    // These Three Lines Makes Notification to Open Main Activity After Clicking On It
    INTENT NOTIFICATIONINTENT = NEW INTENT (This, MainActivity.class);
    notificationintent.setaction (intent.action_main);
    notificationintent.addcategory (intent.category_launcher);
    PendingIntent ContentIntent = PendingIntent.getActivity (GetApplicationContext (), 0, NotificationIntent, PendingIntent.flag_update_Current);
    NotificationCompat.Builder Builder = New NotificationCompat.Builder (this);
    Builder.SetContentIntent (ContentIntent)
      .setongoing (True) // CAN't be swipe out
      .setSmallicon (R.Mipmap.ic_launcher)
      //.setlargeicon(BitmapFactory.decodereesource(res, r.Drawable.Large)) // Big picture
      .setticker (Ticker)
      .setContentTitle (Title) // Title
      .setContentText (text) // Notification Text
      .setwhen (System.CurrentTimemillis ());
    Notification notification;
    if (android.os.build.version.sdk_int & lt; = 15) {
      Notification = Builder.getNotification (); // API-15 and Lower
    } else {
      notification = Builder.Build ();
    }
    StartForeGround (Default_Notification_ID, Notification);
  }
  @Override
  Public Ibinder Onbind (Intent Intent) {
    RETURN NULL;
  }
  @Override
  Public void onestroy () {
    super.ondestroy ();
    // Removing Any Notifications
    notificationmanager.cancel (default_notification_id);
    // Disabling Service.
    StopSelf ();
  }
}

MyReceiver:

Public Class MyReceiver Extends BroadcastReceiver {
  @Override
  Public Void OnreCeive (Context Context, Intent Intent) {
    INTENT INTENTSERVICE = NEW INTENT (CONTEXT, MYSERVICE.CLASS);
    Context.startService (IntentService);
  }
}

Thus, we get a service that automatically starts after the start of the system. The user interface can be called by clicking on a notification that cannot be removed from the notifications panel. After opening the user interface, the service can be disabled or enabled manually by pressing the corresponding button. In the case of closing the application, including the swipe applications from Recent Task Bar, the service will remain enabled and will continue its work.

The only possible way to finish the work of MyService without using the user interface is to close the Application process using the Force Stop in the application list or stop the process itself in the system settings menu.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions