banner



How To Start And Stop A Service Android Studio

To beginning an android background service when the device boots, yous should create a broadcast receiver, and make it mind to android.intent.action.BOOT_COMPLETEDaction. Then in the custom broadcast receiver'due south onReceive method, y'all can start the groundwork service.

i. Method To Start Android Service When Device Boot Completed.

  1. There are ii methods to start an android service in the higher up onReceive method.
  2. Start the android service directly utilize intent. This is non a skilful choice considering the background service is e'er run, and it needs to utilize thread to brand the execution continue. This will price resources and create errors.
  3. Beginning a repeat alert, and make the alarm phone call the groundwork service when executing every interval time. This is a skilful choice because the warning is an android OS system-level service, it is controlled by android OS. It is run out of any application. And the background service will only execute when the alarm executes.

2. Offset Android Service When Boot Completed Example.

  1. Starting time any activity in your android project to install the BOOT_COMPLETED receiver on an android device. The below picture is the android example app execution screen. In that location are 4 buttons on the app's principal screen. Each button will implement a different method to kickoff the android service when the android device boots.
    run-any-activity-in-android-project-to-install-boot-completed-receiver-new
  2. Go to the Android Virtual Device Director window, click the green push button at the finish of the device line to shut down the android device, and restart it again, then you tin can see the Toast message ( such every bit "BootDeviceReceiver onReceive, action is android.intent.activity.BOOT_COMPLETED", "Outset service employ repeat alarm."  and "RunAfterBootService onStartCommand() method.") and debug log in android monitor log cat console.
  3. You tin also meet the debug log output in the android monitor log cat console.

3. Auto Offset Service Later on Device Boot Source Code.

  1. Beneath are the case android project source files.
    ./ ├── app │   ├── build.gradle │   ├── proguard-rules.pro │   └── src │       ├── chief │       │   ├── AndroidManifest.xml │       │   ├── java │       │   │   └── com │       │   │       └── dev2qa │       │   │           └── example │       │   │               ├── alarm │       │   │               │   └── service │       │   │               │       ├── BootDeviceReceiver.java │       │   │               │       └── RunAfterBootService.java

three.i BOOT_COMPLETED Activity Receiver.

  1. BootDeviceReceiver.java
    packet com.dev2qa.example.alarm.service;  import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import android.widget.Toast;  public class BootDeviceReceiver extends BroadcastReceiver {      private static concluding Cord TAG_BOOT_BROADCAST_RECEIVER = "BOOT_BROADCAST_RECEIVER";      @Override     public void onReceive(Context context, Intent intent) {          Cord activeness = intent.getAction();          String message = "BootDeviceReceiver onReceive, activeness is " + action;          Toast.makeText(context, bulletin, Toast.LENGTH_LONG).bear witness();          Log.d(TAG_BOOT_BROADCAST_RECEIVER, action);          if(Intent.ACTION_BOOT_COMPLETED.equals(action))         {             //startServiceDirectly(context);              startServiceByAlarm(context);         }     }      /* Offset RunAfterBootService service directly and invoke the service every 10 seconds. */     individual void startServiceDirectly(Context context)     {         attempt {             while (true) {                 String bulletin = "BootDeviceReceiver onReceive start service straight.";                  Toast.makeText(context, bulletin, Toast.LENGTH_LONG).show();                  Log.d(TAG_BOOT_BROADCAST_RECEIVER, message);                  // This intent is used to start groundwork service. The same service will be invoked for each invoke in the loop.                 Intent startServiceIntent = new Intent(context, RunAfterBootService.course);                 context.startService(startServiceIntent);                  // Current thread volition slumber one second.                 Thread.slumber(10000);             }         }catch(InterruptedException ex)         {             Log.eastward(TAG_BOOT_BROADCAST_RECEIVER, ex.getMessage(), ex);         }     }      /* Create an repeat Alarm that will invoke the background service for each execution fourth dimension.      * The interval time tin can be specified by your cocky.  */     private void startServiceByAlarm(Context context)     {         // Get alarm manager.         AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);          // Create intent to invoke the groundwork service.         Intent intent = new Intent(context, RunAfterBootService.class);         PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);          long startTime = System.currentTimeMillis();         long intervalTime = sixty*m;          String bulletin = "Start service use repeat alarm. ";          Toast.makeText(context, message, Toast.LENGTH_LONG).show();          Log.d(TAG_BOOT_BROADCAST_RECEIVER, message);          // Create repeat warning.         alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, startTime, intervalTime, pendingIntent);     } }

3.2 Background Service.

  1. RunAfterBootService.java
    packet com.dev2qa.case.alarm.service;  import android.app.Service; import android.content.Intent; import android.bone.IBinder; import android.util.Log; import android.widget.Toast;  public form RunAfterBootService extends Service {      private static concluding String TAG_BOOT_EXECUTE_SERVICE = "BOOT_BROADCAST_SERVICE";      public RunAfterBootService() {     }      @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();         Log.d(TAG_BOOT_EXECUTE_SERVICE, "RunAfterBootService onCreate() method.");      }      @Override     public int onStartCommand(Intent intent, int flags, int startId) {          String bulletin = "RunAfterBootService onStartCommand() method.";          Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).evidence();          Log.d(TAG_BOOT_EXECUTE_SERVICE, "RunAfterBootService onStartCommand() method.");          render super.onStartCommand(intent, flags, startId);     }      @Override     public void onDestroy() {         super.onDestroy();     } }

3.three Android Manifest Xml File.

  1. AndroidManifest.xml
    <?xml version="i.0" encoding="utf-eight"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"     parcel="com.dev2qa.case">      <!-- Example need below permission. -->     <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />      <awarding         android:allowBackup="true"         android:icon="@mipmap/ic_launcher"         android:label="@cord/app_name"         android:roundIcon="@mipmap/ic_launcher_round"         android:supportsRtl="true"         android:theme="@mode/AppTheme">                  <receiver             android:proper name=".alarm.service.BootDeviceReceiver"             android:enabled="true"             android:exported="truthful">             <intent-filter>                 <action android:name="android.intent.action.BOOT_COMPLETED"/>             </intent-filter>         </receiver>           <service             android:name=".alert.service.RunAfterBootService"             android:enabled="true"             android:exported="true"></service>     </awarding>  </manifest>

4. Question & Answer.

4.i How to launch an android activity from a foreground service when the android device boots up.

  1. My requirement is to start a foreground service when the android device boots up, and at the same fourth dimension, the foreground service will start an activity. I found this article from google but I find it can not implement my needs. How can I implement my needs?
  2. From android API version 29, you lot are not allowed to starting time an android activity from the background service, although you desire to start the android action from the foreground service, android treats foreground service equally a groundwork process also, so when your android version is bigger than android 10, this activity volition exist restricted. If you test your android app for a hard android device, and for some hard android devices, they may not let you to get-go the awarding when the android device boots up, then If you desire, you need some exclusive autostart permission on those android difficult devices.

Reference

  1. Android Broadcast Overview
  2. How To Register Android BroadcastReceiver Statically
  3. How To Create, Kickoff, Stop Android Background Service
  4. Android One Time / Repeat Alarm Example

How To Start And Stop A Service Android Studio,

Source: https://www.dev2qa.com/how-to-start-android-service-automatically-at-boot-time/

Posted by: elzyowestrim.blogspot.com

0 Response to "How To Start And Stop A Service Android Studio"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel