How to Fetch Currently Running Tasks in Android Programmatically?
Last Updated :
23 Jan, 2022
Android devices run several tasks in the background for providing a seamless experience to the users. Importantly, tracking background and foreground usages is important as it directly impacts the battery life and static memory, i.e. RAM. One can enable the developer option in the settings to track all the background tasks and services. However, one can even programmatically find out the same. So in this article, we will show you how you could programmatically fetch currently running tasks in Android. Follow the below steps once the IDE is ready.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. We added a TextView to display the list of running tasks.
XML
<? xml version = "1.0" encoding = "utf-8" ?>
< RelativeLayout
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity" >
< TextView
android:id = "@+id/text_view"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:scrollbars = "vertical" />
</ RelativeLayout >
|
Step 3: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. In the main code, primarily, we shall be using the ActivityManager to get the list of running tasks.
Kotlin
package org.geeksforgeeks.currentlyrunningapps
import android.app.ActivityManager
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import java.util.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super .onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val mTextView = findViewById<TextView>(R.id.text_view)
val mActivityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val mRecentTasks: List<ActivityManager.RunningTaskInfo> = Objects.requireNonNull(mActivityManager).getRunningTasks(Int.MAX_VALUE)
var mString = ""
for (i in mRecentTasks.indices){
mString = mString + " " + mRecentTasks[i].baseActivity?.toShortString() + " " + mRecentTasks[i].id + "\n\n"
}
mTextView.text = mString
}
}
|
Output:
You can see the list of running tasks as shown below.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...