Wake the Android Screen after a timer fires - java

How can I have a timer fire a method to wake up the screen of an Android device?
I inserted this:
final Window win = getWindow();
win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
into the
#Override
protected void onCreate(Bundle savedInstanceState) {
method.
Additionally, I made a timer after a user clicks a button which runs the following program:
final int interval = 3000; // 3 Seconds
Handler handler = new Handler();
Runnable runnable = new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(), "Here", Toast.LENGTH_SHORT).show();
}
};
handler.postAtTime(runnable, System.currentTimeMillis()+interval);
handler.postDelayed(runnable, interval);
I want to be able to click the power button of my Android device to sleep it within the 3 second interval and have it wake up after the run() gets fired.
What do I call to trigger the screen to turn on?

This method also instantly turns on the screen:
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock TempWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK|PowerManager.ACQUIRE_CAUSES_WAKEUP, "TempWakeLock");
TempWakeLock.acquire();
TempWakeLock.release();

try to add to onCreate() :
PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG");
wakeLock.acquire();
To release the screen lock:
KeyguardManager keyguardManager = (KeyguardManager) getApplicationContext().getSystemService(Context.KEYGUARD_SERVICE);
KeyguardLock keyguardLock = keyguardManager.newKeyguardLock("TAG");
keyguardLock.disableKeyguard();
Add to the manifest:
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />

Related

How to reset android password programmatically

I'm trying to create an application that allow the user to lock his android device with a password from a website. So I must find a method to lock the device programmatically, it means is there anyone that have a code that allow me to set a password for the device and when I unlock my screen it demands to enter the code to access to the home? Basically, what I'm trying to create is a app where device owners can lock the device from the website. The android app will be calling an api every 10 min checking for lock command. Currently I'm struggling to lock device with this code.
Policies.xml
<?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android" >
<uses-policies>
<force-lock />
<reset-password/>
</uses-policies>
</device-admin>
MainActivity
lock.setOnClickListener(v -> {
//Keep the CPU running while screen is off
wakeLock.acquire();
SecureRandom secureRandom = new SecureRandom();
byte[] token = secureRandom.generateSeed(32);
DevicePolicyManager devicePolicyManager = (DevicePolicyManager) getApplicationContext().getSystemService(
DEVICE_POLICY_SERVICE);
if (devicePolicyManager != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
devicePolicyManager.setResetPasswordToken(compName, token);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
devicePolicyManager.resetPasswordWithToken(compName, "4321", token, 0);
}
}
//Lock the screen
deviceManger.lockNow() ;
//Wait 5 secs before starting the next activity
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(MainActivity.this,MainActivity2.class);
MainActivity.this.startActivity(intent);
//Release cpu
wakeLock.release();
}
},5000);
});

How to make a screen wake up when a notification is received?

For my app I'm trying to get it where the notification wakes up the screen and displays a view from the app. I can't figure how to get the app to wake up when its in a lock screen. I've tried a few things but none seem to work or they crash the app.
There is my solution:
createNotification(); //your implementation
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
boolean isScreenOn = Build.VERSION.SDK_INT >= 20 ? pm.isInteractive() : pm.isScreenOn(); // check if screen is on
if (!isScreenOn) {
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "myApp:notificationLock");
wl.acquire(3000); //set your time in milliseconds
}
More at PowerManager
This BroadCastReceiver Works For, your App Is in back ground State/ mobile In lock mode. That time when notification is recieved i have to redirect particular screen, for that one i added Intent code,
After receiving Notification this code helps to your requirement
public class FirebaseDataReceiver extends WakefulBroadcastReceiver {
private final String TAG = "FirebaseDataReceiver";
public void onReceive(Context context, Intent intent) {
PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
boolean isScreenOn = pm.isScreenOn();
if(isScreenOn==false)
{
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |PowerManager.ACQUIRE_CAUSES_WAKEUP |PowerManager.ON_AFTER_RELEASE,"MyLock");
wl.acquire(10000);
PowerManager.WakeLock wl_cpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"MyCpuLock");
wl_cpu.acquire(10000);
}
//Redirect particular screen after receiving notification, this is like ola driver app concept accepting driver request
intent = new Intent(context, MyTicketListActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
Also remember to specify the permission used in the AndroidManifest.xml:
<uses-permission android:name="android.permission.WAKE_LOCK" />
I faced a similar situation. It was required to show a notification screen for the user to accept or reject the notification, even when the screen is off. I fumbled with it for a while until now. The requirements demand the screen should be on and this can be achieved with a combination of flags for the window manager and the wake lock as shown below.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
boolean isScreenOn = pm.isScreenOn();
int flags = PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP
| PowerManager.ON_AFTER_RELEASE;
if (!isScreenOn) {
wakeLock = pm.newWakeLock(flags, "my_app:full_lock");
wakeLock.acquire(20000);
}
setContentView(R.layout.activity_incoming_request);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON |
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON |
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
...
startRingingPhone();
}
This code block will display the activity on the lock screen.
Put below code before notification creates,
PowerManager powerManager = (PowerManager) context.getSystemService(context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK |
PowerManager.ACQUIRE_CAUSES_WAKEUP |
PowerManager.ON_AFTER_RELEASE, "appname::WakeLock");
//acquire will turn on the display
wakeLock.acquire(1*60*1000L);
And make sure to set this permission in the manifest :
<uses-permission android:name="android.permission.WAKE_LOCK"/>

Android app don't work in sleep mode

I have app with timer. When I press the power button, my app going to sleep mode and stopped timer. What should I do to timer continue to working. Below my very simple code timer.
Thread t = new Thread(){
#Override
public void run() {
while (!isInterrupted()){
try {
Thread.sleep(1000);
i++;
Log.e("pokaz "," i "+i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
I solved my problem. I write this code in activity
PowerManager pm;
PowerManager.WakeLock wl;
pm = (PowerManager) getActivity().getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
wl.acquire();
and layout write this code
android:keepScreenOn="true"
but now my application is in background and version API is kitkat evrything is ok. When test my aplication in API lolipop and goes on sleep mode and next turn on phone I see message "unfortunately myApp has stopped". Why?
To work your app in background you need to use Service, IntentService or BroadCastReceiver.
And do your thread work inside Service.

IntentService not working

I am building an application whereby the notification will ring at a specific time and after which disappear if it is left unattended for 15 minutes. It works when i plug in my device and runs the code. However, once i unplug my device and runs the app, the notification works but it does not disappear after 15 minutes if it is left unattended. Please advice me how should i run the app like how it does when the device is plug into the computer. Also, it should work when the app is killed.
FYI, i'm using notification, alarmmanager, broadcast receiver and intentservice. Below is the snippet of my codes.
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Notification(context, "Wifi Connection On");
Intent background = new Intent(context, BackgroundService.class);
context.startService(background);
}
public void Notification(final Context context, String message) {
// notification codes
}
}
BackgroundService.java
public class BackgroundService extends IntentService {
public BackgroundService() {
super("BackgroundService");
}
#Override
protected void onHandleIntent(Intent intent) {
//countdown 15 minutes and cancel notification automatically
Timer timer=new Timer();
TimerTask task=new TimerTask() {
#Override
public void run() {
// Create Notification Manager
NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Dismiss Notification
notificationmanager.cancelAll();
}
};
timer.schedule(task, 900000);
}
}
Manifest.xml
<receiver android:name=".AlarmReceiver" android:process=":remote" />
<service android:name=".BackgroundService" />
Please provide me some suggestions. Thank you.
This service will run twice: first time it does nothing except rescheduling, second time it cancels notifications.
public class BackgroundService extends IntentService {
private static final int REQUEST_CODE = 42;
private static final String ACTION_CANCEL_NOTIFS = "CancelNotifications";
public BackgroundService() {
super("BackgroundService");
}
#Override
protected void onHandleIntent(Intent intent) {
if (intent != null && ACTION_CANCEL_NOTIFS.equals(intent.getAction())) {
NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationmanager.cancelAll();
}
else {
reschedule();
}
}
private void reschedule() {
final Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.MINUTE, 15);
final Intent serviceIntent = new Intent(this, getClass());
serviceIntent.setAction(ACTION_CANCEL_NOTIFS);
PendingIntent pendingIntent = PendingIntent.getService(this, REQUEST_CODE, serviceIntent, PendingIntent.FLAG_UPDATE_CURRENT);
final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
}
Explanation:
In your code, I assume, you start your service with startService(new Intent(this, BackgroundService.class)). This intent is passed as a parameter in onHandleIntent(Intent), which means you can access it from inside your service.
Intent allows you to pass additional data, such as action (useful for IntentFilters) or extras. Because you haven't set any, the first time around the execution goes to the else branch of onHandleIntent() method. AlarmManager is then scheduled to run your service in 15 minutes with serviceIntent. Note serviceIntent.setAction(ACTION_CANCEL_NOTIFS). So the second time around the execution goes to the if branch and cancels notifications.
A better approach would be creating a pending intent right from inside your activity instead of starting a service with startService. That would make your service simpler and more cohesive.
Service only runs when CPU is awake. If CPU gets off, service will not run.
SO to make your service to be run if phone goes to sleep, you need to aquire wake lock.
BackgroundService class
public class BackgroundService extends IntentService {
private PowerManager.WakeLock wl;
public BackgroundService() {
super("BackgroundService");
}
#Override
protected void onHandleIntent(Intent intent) {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Partial lock permission");
wl.acquire();
//countdown 15 minutes and cancel notification automatically
Timer timer=new Timer();
TimerTask task=new TimerTask() {
#Override
public void run() {
// Create Notification Manager
NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Dismiss Notification
notificationmanager.cancelAll();
wl.release();
}
};
timer.schedule(task, 900000);
}
}
If this does work out, try to give below permission in Android Manifest file
<uses-permission android:name="android.permission.WAKE_LOCK" />

skip the screenlock

protected void onPause()
{
super.onPause();
// If the screen is off then the device has been locked
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
boolean isScreenOn = powerManager.isScreenOn();
//screen locked
if (!isScreenOn) {
boolean pressed = onKeyDown(26, null);
//power button pressed
if(pressed){
//remove keyguard
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
//start intent
Intent i = new Intent(this, VoiceRecognitionActivity.class);
startActivity(i);
}
}
}
the above code does is when power button is pressed, the keyguard will be dismissed and the activity onpaused will be resumed.
However, the keyguard is not dimissed when i pressed the power button, and i have to unlock manually.
When i pressed the power button, the window of my activity flashed for a second and the keyguard window is shown.
If you want to prevent phone from turning screen off (and locking the phone in result) you should use WakeLock. You can use PowerManager.newWakeLock() with FLAG_KEEP_SCREEN_ON or even
FULL_WAKE_LOCK.
This code snippet may help:
final Window win = getWindow();
win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
// Turn on the screen unless we are being launched from the AlarmAlert
// subclass.
final boolean screenOff = getIntent().getBooleanExtra(SCREEN_OFF, false);
if (!screenOff) {
try {
// API 8+
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
| WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
} catch (final Throwable whocares) {
// API 7+
win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
}
}

Categories

Resources