How to turn Android device screen on and off programmatically using Kotlin?

Kotlin Apps/ApplicationsMobile Development

This example demonstrates how to turn an Android device screen on and off programmatically using Kotlin.

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:layout_margin="8dp">
   <TextView
      android:id="@+id/textView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="70dp"
      android:background="#008080"
      android:padding="5dp"
      android:text="TutorialsPoint"
      android:textColor="#fff"
      android:textSize="24sp"
      android:textStyle="bold" />
   <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:orientation="horizontal">
   <Button
      android:id="@+id/btnEnable"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:layout_weight="1"
      android:onClick="enablePhone"
      android:text="Enable" />
   <Button
      android:id="@+id/btnLock"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:layout_weight="1"
      android:onClick="lockPhone"
      android:text="Lock" />
   </LinearLayout>
</RelativeLayout>

Step 3 − Add the following code to src/MainActivity.kt

import android.app.admin.DevicePolicyManager
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.annotation.Nullable
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
   private val enableResult = 1
   lateinit var deviceManger: DevicePolicyManager
   lateinit var compName: ComponentName
   lateinit var btnEnable: Button
   lateinit var btnLock: Button
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      btnEnable = findViewById(R.id.btnEnable)
      btnLock = findViewById(R.id.btnLock)
      deviceManger = getSystemService(Context.DEVICE_POLICY_SERVICE) as DevicePolicyManager
      compName = ComponentName(this, DeviceAdmin::class.java)
      val active = deviceManger.isAdminActive(compName)
      if (active) {
         btnEnable.text = "Disable"
         btnLock.visibility = View.VISIBLE
      } else {
         btnEnable.text = "Enable"
         btnLock.visibility = View.GONE
      }
   }
   fun enablePhone(view: View) {
      val active = deviceManger.isAdminActive(compName)
      if (active) {
         deviceManger.removeActiveAdmin(compName)
         btnEnable.text = "Enable"
         btnLock.visibility = View.GONE
      } else {
         val intent = Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN)
         intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, compName)
         intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "You should enable the app!")
         startActivityForResult(intent, enableResult)
      }
   }
   fun lockPhone(view: View) {
      deviceManger.lockNow()
   }
   override fun onActivityResult(requestCode: Int, resultCode: Int, @Nullable data: Intent?) {
      super.onActivityResult(requestCode, resultCode, data)
      when (requestCode) {
         enableResult -> {
            if (resultCode == RESULT_OK) {
               btnEnable.text = "Disable"
               btnLock.visibility = View.VISIBLE
            } else {
               Toast.makeText(
               applicationContext, "Failed!",
               Toast.LENGTH_SHORT
               ).show()
            }
            return
         }
      }
   }
}

Step 4 − Create a new Kotlin class (DeviceAdmin.kt) and add the following code −

import android.app.admin.DeviceAdminReceiver
import android.content.Context
import android.content.Intent
import android.widget.Toast
class DeviceAdmin : DeviceAdminReceiver() {
   override fun onEnabled(context: Context, intent: Intent) {
      super.onEnabled(context, intent)
      Toast.makeText(context, "Enabled", Toast.LENGTH_SHORT).show()
   }
   override fun onDisabled(context: Context, intent: Intent) {
      super.onDisabled(context, intent)
      Toast.makeText(context, "Disabled", Toast.LENGTH_SHORT).show()
   }
}

Step 5 − Add the following code to res/xml/policies.xml

<?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
   <uses-policies>
      <force-lock />
   </uses-policies>
</device-admin>

Step 6 − Add the following code to androidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q2">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
      <receiver
         android:name=".DeviceAdmin"
         android:permission="android.permission.BIND_DEVICE_ADMIN" >
      <meta-data
         android:name= "android.app.device_admin"
         android:resource= "@xml/policies" />
      <intent-filter>
         <action android:name= "android.app.action.DEVICE_ADMIN_ENABLED" />
      </intent-filter>
   </receiver>
</application>
</manifest>

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.

raja
Published on 07-Sep-2020 14:51:40
Advertisements