Prevent Android App Activity Screen From Sleeping programmatically

How to stay awake stop an Android device from going to sleep dynamically using FLAG KEEP SCREEN ON .

Stopping android app from sleeping is very much important functionality for all the android developer who wish to create and Mp3 player app, Media player app, gaming app or any kind of video playing application because these types of all apps requires screen to awaken so app users can enjoy their tasks on it because android mobile phones dose not support by default more than 15 minutes screen on time. So here is the complete step by step tutorial for Prevent Android App Activity Screen From Sleeping programmatically.

android-project-download-code-button

How to Prevent Android App Activity Screen From Sleeping programmatically.

Code for MainActivity.java file.

package com.android_examples.stayawakeapp_android_examplescom;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.WindowManager;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    }
}

Code for activity_main.xml layout file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.android_examples.stayawakeapp_android_examplescom.MainActivity"
    android:background="#FFF3E0">


    <TextView
        android:text="How To Stay Awake Android App Programmatically"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:id="@+id/textView"
        android:gravity="center"
        android:textSize="25dp"
        android:textStyle="bold"
        android:textColor="#FF9800"/>

</RelativeLayout>

Screenshot:

Prevent Android App Activity Screen From Sleeping programmatically

Click here to download Prevent Android App Activity Screen From Sleeping programmatically project with source code.

Leave a Reply

Your email address will not be published. Required fields are marked *