Android java выключить экран

программно выключить экран в Android

Можно ли программным образом отключить экран в андроиде, если он не выполняется автоматически через 1 минуту бездействия. возможно ли это сделать программно в android? Я нашел эти темы: Android: как включить и выключить экран программно? Включение и выключение экрана с программным обеспечением не работает на некоторых устройствах но после 1 минуты нет таймера.

1 ответ

Да, метод, который наилучшим образом используется в этом случае, заключается в программном выборе тайм-аута экрана.

Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 1000); 

1000 находится в миллисекундах, что означает 1 секунду, вы можете заменить его любым значением по желанию. Необходимое разрешение:

ОБНОВЛЕНИЕ Он перезапишет системную стоимость (Настройки/Дисплей/Сон), поэтому, возможно, вам нужно восстановить текущие настройки после завершения:

private static final int SCREEN_OFF_TIME_OUT = 13000; private int mSystemScreenOffTimeOut; private void setScreenOffTimeOut() < try < mSystemScreenOffTimeOut = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT); Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, SCREEN_OFF_TIME_OUT); >catch (Exception e) < Utils.handleException(e); >> private void restoreScreenOffTimeOut() < if (mSystemScreenOffTimeOut == 0) return; try < Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, mSystemScreenOffTimeOut); >catch (Exception e) < Utils.handleException(e); >> 

Таким образом, вы пытаетесь установить системное время экрана по умолчанию, а не только для вашего собственного приложения.

В конце концов, ваше приложение должно использовать системный порядок, чтобы отключить экран. Приложение само по себе не может выключить экран. Одна минута бездействия в вашем приложении равна одной минуте бездействия на экране, верно?

если мы используем Settings.System.SCREEN_OFF_TIMEOUT для установки тайм-аута экрана, то настройка по-прежнему переименовывается, даже если пользователь перешел из приложения.

Да, вот как это будет работать. в противном случае ему нужно еще обойтись, запланировав обработчик продолжительностью в одну минуту, установить тайм-аут экрана на 1 секунду, чтобы он быстро выключался. Затем используйте приемник вещания, чтобы получить ACTION_SCREEN_OFF и сбросить тайм-аут экрана на более старое значение.

Источник

How to turn Android device screen on and off programmatically?

This example demonstrate about How to turn Android device screen on and off programmatically.

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

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

Step 4 − Add the following code to src/DeviceAdmin

package app.tutorialspoint.com.sample ; import android.app.admin.DeviceAdminReceiver ; import android.content.Context ; import android.content.Intent ; import android.widget.Toast ; public class DeviceAdmin extends DeviceAdminReceiver < @Override public void onEnabled (Context context , Intent intent) < super .onEnabled(context , intent) ; Toast. makeText (context , "Enabled" , Toast. LENGTH_SHORT ).show() ; >@Override public void onDisabled (Context context , Intent intent) < super .onDisabled(context , intent) ; Toast. makeText (context , "Disabled" , Toast. LENGTH_SHORT ).show() ; >>

Step 5 − Add the following code to src/MainActivity

package app.tutorialspoint.com.sample ; import android.app.Activity ; import android.app.admin.DevicePolicyManager ; import android.content.ComponentName ; import android.content.Context ; import android.content.Intent ; import android.support.annotation. Nullable ; import android.support.v7.app.AppCompatActivity ; import android.os.Bundle ; import android.view.View ; import android.widget.Button ; import android.widget.Toast ; public class MainActivity extends AppCompatActivity < static final int RESULT_ENABLE = 1 ; DevicePolicyManager deviceManger ; ComponentName compName ; Button btnEnable , btnLock ; @Override protected void onCreate (Bundle savedInstanceState) < super .onCreate(savedInstanceState) ; setContentView(R.layout. activity_main ) ; btnEnable = findViewById(R.id. btnEnable ) ; btnLock = findViewById(R.id. btnLock ) ; deviceManger = (DevicePolicyManager) getSystemService(Context. DEVICE_POLICY_SERVICE ) ; compName = new ComponentName( this, DeviceAdmin. class ) ; boolean active = deviceManger .isAdminActive( compName ) ; if (active) < btnEnable .setText( "Disable" ) ; btnLock .setVisibility(View. VISIBLE ) ; >else < btnEnable .setText( "Enable" ) ; btnLock .setVisibility(View. GONE ) ; >> public void enablePhone (View view) < boolean active = deviceManger .isAdminActive( compName ) ; if (active) < deviceManger .removeActiveAdmin( compName ) ; btnEnable .setText( "Enable" ) ; btnLock .setVisibility(View. GONE ) ; >else < Intent intent = new 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 , RESULT_ENABLE ) ; >> public void lockPhone (View view) < deviceManger .lockNow() ; >@Override protected void onActivityResult ( int requestCode , int resultCode , @Nullable Intent data) < super .onActivityResult(requestCode , resultCode , data) ; switch (requestCode) < case RESULT_ENABLE : if (resultCode == Activity. RESULT_OK ) < btnEnable .setText( "Disable" ) ; btnLock .setVisibility(View. VISIBLE ) ; >else < Toast. makeText (getApplicationContext() , "Failed!" , Toast. LENGTH_SHORT ).show() ; >return; > > >

Step 6 − Add the following code to androidManifest.xml

Читайте также:  Html цвета во всех браузерах

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 Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –

Источник

Handling Screen OFF and Screen ON Intents

Haven’t posted in a while – sorry school has been busy. Any who, this little code snippet/example will be on how to deal with the Intent.ACTION_SCREEN_OFF and the Intent.ACTION_SCREEN_ON, which will come in nifty if you’re making an application that might need to save state or respond to the user’s screen going to sleep/waking up, etc.

First, unlike other broad casted intents, for Intent.ACTION_SCREEN_OFF and Intent.ACTION_SCREEN_ON you CANNOT declare them in your Android Manifest! I’m not sure exactly why, but they must be registered in an IntentFilter in your JAVA code. And so, for this example we are going to have a receiver called ScreenReceiver, and I’m going to walk you through the differences between implementing it in a Service vs. in an Activity.

So, the receiver will simply look like:

public class ScreenReceiver extends BroadcastReceiver < // thanks Jason public static boolean wasScreenOn = true; @Override public void onReceive(Context context, Intent intent) < if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) < // do whatever you need to do here wasScreenOn = false; >else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) < // and do whatever you need to do here wasScreenOn = true; >> >

Now, the first example will be for an Activity. Because of the life-cycle of an Activity, an Activity is actually easier to deal with as right before the screen turns off onPause() is called and right when the screen turns on onResume() is called, and so naturally we will handle the screen on/off events here:

public class ExampleActivity extends Activity < @Override protected void onCreate() < // initialize receiver IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); BroadcastReceiver mReceiver = new ScreenReceiver(); registerReceiver(mReceiver, filter); // your code >@Override protected void onPause() < // when the screen is about to turn off if (ScreenReceiver.wasScreenOn) < // this is the case when onPause() is called by the system due to a screen state change System.out.println("SCREEN TURNED OFF"); >else < // this is when onPause() is called when the screen state has not changed >super.onPause(); > @Override protected void onResume() < // only when screen turns on if (!ScreenReceiver.wasScreenOn) < // this is when onResume() is called due to a screen state change System.out.println("SCREEN TURNED ON"); >else < // this is when onResume() is called when the screen state has not changed >super.onResume(); > >

Now, note that in my onPause() and onResume() methods I run a check to see that the method was called DUE TO A SCREEN STATE CHANGE. This is important as often onPause() or onResume() will get called because of other reasons – i.e. a new activity is being started on top of this one, or an incoming call might be coming in, etc – and you want to make sure that your screen change logic is only called when the screen has actually changed.

Now, something to keep in mind, is that the order of events before the system screen turns off is:

Читайте также:  Php version in shell

Which is a little unintuitive as you’d think the receiver would get hit first – and so when you play around with setting booleans, etc, be aware of this little fact, and likewise when the screen turns on the order of events is:

And so again the order of events seems a little “backwards”.

Now, for a Service, it’s a little bit different since there is no onResume() or onPause() that gets called as the Service is always “running” in the background, and so instead what you’re going to have to do is modify your receiver a little to look like:

public class ScreenReceiver extends BroadcastReceiver < private boolean screenOff; @Override public void onReceive(Context context, Intent intent) < if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) < screenOff = true; >else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) < screenOff = false; >Intent i = new Intent(context, UpdateService.class); i.putExtra("screen_state", screenOff); context.startService(i); > >

And your service will look like:

public static class UpdateService extends Service < @Override public void onCreate() < super.onCreate(); // register receiver that handles screen on and screen off logic IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); BroadcastReceiver mReceiver = new ScreenReceiver(); registerReceiver(mReceiver, filter); >@Override public void onStart(Intent intent, int startId) < boolean screenOn = intent.getBooleanExtra("screen_state", false); if (!screenOn) < // your code >else < // your code >> >

And so this is pretty self explanatory. When the screen state changes, it will notify your ScreenReceiver and from there you can set the state information into an Intent and send that data to your Service which can then handle it appropriately.

Hopefully this was useful. Let me know if you have questions.

Share this:

Like this:

Great idea, but the onPause code in the Activity is broken. wasScreenOn will always be true on entering the function. As you indicated, “ExampleActivity.onPause() –> ScreenReceiver.onReceive()” is the order of events. Thus, whether you entered onPause as a result of letting the screen turn off, or you entered onPause by putting another activity on top of this one, wasScreenOn will always be true.

Hey Jason, Thanks for the catch. I think the fix is pretty simple – just initialize wasScreenOn to be TRUE. Then the rest of the logic works (correct me if I’m wrong). – jwei

How about monitoring user inactivity? Is there a system internal inactivity timer or do I need to poke a countdown timer thread from regular methods using event listeners? Many thanks for your article by the way! Very intuitive and clear.

Wow, your article is really come in handly. I was looking to turn off the shake sensor on my 9420 Thai Keyboard when the phone is locked and/or screen is off. Thank you so much,
Solution 9420

For the life of me, I can’t get this to work, I only need a simple check if the screen is currently on or off, is there something simpler to this? I tried your instructions, didn’t work, copying the codes, didn’t work, I am not sure where I am doing wrong… Can I just do a constant loop in my onCreate() under my Activity/Main class? such as onCreate()
while (true)
if (ScreenOn(or whatever is necessary to check it)
//do what i want here
else
//do anything else when screen is off
>
> Makes sense. :S
Morris Lee

Hey Morris, No you shouldn’t do that for several reasons. First the while(true) will be run on the main UI thread and will basically cause your application to get stuck – at which point the OS will make the user force close your app. I would suggest you read about the Activity life cycle – this is important to understand since it will allow you to check for various things (in this case a screen on boolean) at the appropriate times without having to do weird hacks like the one you proposed: http://developer.android.com/reference/android/app/Activity.html Hope this helps! – jwei

Читайте также:  Python selenium proxy geckodriver

This all works for most cases. I am making a game where if you press the HOME button(onPause) the game saves. Then when you bring the game back to the front the onResume will load it. (I do this so in case Android wants to erase all the variables i need to run the game while the user is using some other app) However, if the screen turns off i do not want onPause to run any code. And when the screen turns back on i don’t want onResume to run any code. (Because Android will not erase the game’s variables when the screen just gets turned off) Because you initialize wasScreenOn to be TRUE, only one part of the onPause code above will be used whether you press the HOME key or turn the screen off.
It does not make a difference if you initialize wasScreenOn to be false or true. The same problem happens. I solved the problem by making a few changes to onCreate() and onPause()
Everything else stays the same as above @Override
protected void onCreate() // initialize receiver
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter); //NEW
PowerManager pm =(PowerManager) getSystemService(Context.POWER_SERVICE); // your code
> @Override
protected void onPause() // when the screen is about to turn off
// Use the PowerManager to see if the screen is turning off
if (pm.isScreenOn() == false) // this is the case when onPause() is called by the system due to the screen turning off
System.out.println(“SCREEN TURNED OFF”);
> else // this is when onPause() is called when the screen has not turned off
>
super.onPause();
> Hope this helps

Service example above seems wrong. As You are registering receiver in Oncreate of service. And starting service from receiver… :).

Hey swapnil, Hm not sure what you mean? I don’t think I’m starting any “services” (I presume you mean Activities in my case) in my receiver… I’m just toggling a boolean. – jwei

how would one go about doing this from an AppWidgetProvider. I don’t use Service, instead i opted for java.util.timer for scheduling my updates. cheers
Dave.

I implemented your code in my application. Intent.ACTION_SCREEN_OFF fires when I manually hit the power button to turn off the screen but it does not fire when the screen saver timed out. Does this happen to anybody else?

My Eclipse reports an error with the following line BroadcastReceiver myReceiver = new ScreenReceiver(); It gives an error cannot convert from ScreenReceiver to BroadcastReceiver. Surly the line of code is fine, I don’t see anything wrong with it. The only change I made to ScreenReceiver was remove the static keyword as it’s not permitted. Any ideas?

I think the way it works is that your app has to be running when your app receives Intent.ACTION_SCREEN_OFF intent. But how can you invoke your app when the screen_off? Someone said there is no way due to google’s reason, is this true?

Wonderful job…
I need something else…maybe someone can help me…
I have an application that have to keep the screen on and avoid screen off and lock…itțs a timer… how can I do this ? thanks daniel

Источник

Оцените статью