banner



How To Create A Service In Android

A sample foreground service

In this tutorial, we will learn near foreground service and how to create a foreground service in an android awarding.

A foreground service is a service, which works exactly same as a normal service (background service) and the simply difference is, it has a notification fastened to information technology in the notification tray of the device.

The primary advantage of having a foreground service is its higher priority than its background version. Android Bone implemented restriction to groundwork execution to salve battery and memory usages, i.e., it kills to the lowest degree used apps (or processes) to retain the retention and bombardment.

With Foreground service, app gets following advantages,

  1. Higher priority hence less likely to be killed past OS
  2. Indication to user about important task under processing.
  3. Quick Access to the app similar controls in music player apps.

Normally, apps run long tasks in services.  In which some of them are urgent similar sending or uploading files to server, such tasks are safe to run in a foreground service.

Let's come across how to create a foreground service and showtime it. The below code snippet will create a foreground service with a notification.

Notification will have a button to open app. When app opens, current timestamp value passed to the MainActivity and shows it on the UI.

Step 1: Create a Foreground Service

package com.devdeeds.foregroundservice  import android.app.* import android.content.Context import android.content.Intent import android.graphics.Color import android.os.Build import android.os.Handler import android.os.IBinder import android.util.Log import androidx.core.app.NotificationCompat   /** @author Jayakrishnan P.K  * Created by Devdeeds.com on 21/3/18.  */  class FService : Service() {      private val mHandler: Handler? = Handler()      individual lateinit var mRunnable: Runnable       override fun onCreate() {         super.onCreate()         startForegroundService()     }      override fun onBind(p0: Intent?): IBinder? {         return naught;     }      override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {          Log.d(TAG, "ON Outset COMMAND")          if (intent != nix) {              when (intent.activity) {                  ACTION_STOP_FOREGROUND_SERVICE -> {                     stopService()                 }                  ACTION_OPEN_APP -> openAppHomePage(intent.getStringExtra(KEY_DATA))             }         }         return START_STICKY;     }       private fun openAppHomePage(value: Cord) {          val intent = Intent(applicationContext, MainActivity::grade.java)         intent.putExtra(KEY_DATA, value)         intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)         startActivity(intent)      }       private fun createNotificationChannel() {         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {              val chan = NotificationChannel(                 CHANNEL_ID,                 CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT             )              chan.lightColor = Colour.BLUE             chan.lockscreenVisibility = NotificationCompat.VISIBILITY_PRIVATE             val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager             service.createNotificationChannel(chan)          }     }      /* Used to build and start foreground service. */     private fun startForegroundService() {          //Create Notification aqueduct for all the notifications sent from this app.         createNotificationChannel()          // Offset foreground service.         startFService()           mRunnable = Runnable {              notifyNextEvent()             mHandler?.postDelayed(mRunnable, ONE_MIN_MILLI)  //echo         };          // Schedule the task to echo after one second         mHandler?.postDelayed(             mRunnable, // Runnable             ONE_MIN_MILLI // Filibuster in milliseconds         )      }      individual fun startFService() {          val clarification = getString(R.string.msg_notification_service_desc)         val title = String.format(             getString(R.string.title_foreground_service_notification),             getString(R.string.app_name)         )          startForeground(SERVICE_ID, getStickyNotification(title, description))         IS_RUNNING = truthful     }       private fun getStickyNotification(title: Cord, message: String): Notification? {          val pendingIntent = PendingIntent.getActivity(applicationContext, 0, Intent(), 0)          // Create notification builder.         val builder = NotificationCompat.Architect(applicationContext, CHANNEL_ID)         // Make notification evidence big text.         val bigTextStyle = NotificationCompat.BigTextStyle()         bigTextStyle.setBigContentTitle(title)         bigTextStyle.bigText(bulletin)         // Set big text style.         builder.setStyle(bigTextStyle)         builder.setWhen(System.currentTimeMillis())         builder.setSmallIcon(R.drawable.ic_stat_name)         //val largeIconBitmap = BitmapFactory.decodeResource(resources, R.drawable.ic_alarm_on)         //builder.setLargeIcon(largeIconBitmap)         // Make the notification max priority.         architect.priority = NotificationCompat.PRIORITY_DEFAULT          // Make head-up notification.         builder.setFullScreenIntent(pendingIntent, true)           // Add together Open App button in notification.         val openAppIntent = Intent(applicationContext, FService::form.java)         openAppIntent.action = ACTION_OPEN_APP         openAppIntent.putExtra(KEY_DATA, "" + Organisation.currentTimeMillis())         val pendingPlayIntent = PendingIntent.getService(applicationContext, 0, openAppIntent, 0)         val openAppAction = NotificationCompat.Activity(             android.R.drawable.ic_menu_view,             getString(R.string.lbl_btn_sticky_notification_open_app),             pendingPlayIntent         )         builder.addAction(openAppAction)           // Build the notification.         render builder.build()      }       individual fun notifyNextEvent() {          NotificationHelper.onHandleEvent(             getString(R.cord.title_gen_notification),             getString(R.cord.description_gen_notification),             applicationContext         )     }       private fun stopService() {         // Stop foreground service and remove the notification.         stopForeground(truthful)         // Stop the foreground service.         stopSelf()          IS_RUNNING = false     }       override fun onDestroy() {         IS_RUNNING = false         mHandler?.removeCallbacks(null)     }      companion object {          const val TAG = "FOREGROUND_SERVICE"           const val ACTION_STOP_FOREGROUND_SERVICE = "ACTION_STOP_FOREGROUND_SERVICE"          const val ACTION_OPEN_APP = "ACTION_OPEN_APP"         const val KEY_DATA = "KEY_DATA"          individual const val CHANNEL_ID: String = "1001"         private const val CHANNEL_NAME: String = "Upshot Tracker"         private const val SERVICE_ID: Int = 1         private const val ONE_MIN_MILLI: Long = 60000  //1min          var IS_RUNNING: Boolean = simulated     } }              

Notifications generated past the app will be sending with an interval of i minute.

Step two: Add Foreground Service In AndroidManifest XML File

<?xml version="one.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"     package="com.devdeeds.foregroundservice">      <uses-permission android:name="android.permission.WAKE_LOCK" />     <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />     <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />      <application         android:allowBackup="true"         android:icon="@mipmap/ic_launcher"         android:characterization="@string/app_name"         android:roundIcon="@mipmap/ic_launcher_round"         android:supportsRtl="true"         android:theme="@mode/AppTheme">         <activity android:proper noun=".MainActivity">             <intent-filter>                 <activeness android:name="android.intent.action.Master" />                  <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>         </activity>          <service             android:proper name=".FService"             android:enabled="true"             android:exported="fake" />           <receiver             android:proper noun=".AutoStartUpBootReceiver"             android:enabled="truthful"             android:exported="false">             <intent-filter>                 <activity android:proper noun="android.intent.activeness.BOOT_COMPLETED" />                 <action android:name="android.intent.action.QUICKBOOT_POWERON" />             </intent-filter>         </receiver>      </awarding>  </manifest>              

Where android.permission.WAKE_LOCK is for waking the app screen on the event of notification.

android.permission.RECEIVE_BOOT_COMPLETED is for restarting the service on device reboot. Please refer complete source lawmaking for the reference.

Step iii: Commencement Foreground Service From Activity

package com.devdeeds.foregroundservice  import android.content.Intent import android.bone.Build import android.bone.Package import android.widget.TextView import androidx.appcompat.app.AppCompatActivity   course MainActivity : AppCompatActivity() {      override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         setContentView(R.layout.activity_main)           //Start service         if (!FService.IS_RUNNING) {             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {                 startForegroundService(Intent(applicationContext, FService::grade.java))             } else {                 startService(Intent(applicationContext, FService::form.coffee))             }         }           //Show data sent from service to view on click         if (intent != nil && intent.getStringExtra(FService.KEY_DATA) != cipher) {             findViewById<TextView>(R.id.txtValueView).text = intent.getStringExtra(FService.KEY_DATA)         }     } }              

In the activity, it receives information via intent and shows it in a TextView.

This example demonstrates how to communicate a foreground service with activeness via a notification.

Yous tin can observe the complete project source code in Github project.

  • Was this tutorial helpful for you ?
  • yes   no

We apply cookies on our website to give you the most relevant experience past remembering your preferences and echo visits. Past clicking "Accept All", you consent to the use of ALL the cookies. Nonetheless, you may visit "Cookie Settings" to provide a controlled consent.

Copyright © 2021 devdeeds.com. All Rights Reserved.

How To Create A Service In Android,

Source: https://devdeeds.com/kotlin-android-foreground-service/

Posted by: merrillfrenjudipt.blogspot.com

0 Response to "How To Create A Service In Android"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel