Turn screen off programmatically - java

I'm working in an app that needs to to do any of this actions:
Lock the device
Put the device in sleep mode
Turn off the screen
How can I achieve this?
Found this option, but it requires the proximity sensor to be in "near" state to turn off the screen:
mWakeLock = mPowerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, "tag");
mWakeLock.acquire();
Thanks

If your app is a device admin you can lock the screen with DevicePolicyManager.lockNow()
You can use this snippet (after setting the Device Admin part):
DevicePolicyManager manager = ((DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE));
manager.lockNow();

Related

how to enable floating notification and lock screen notification in xamarin android(Java or Kotlin is okay)

I make simple notification android app using xamarin,
i want floating notification and lock screen notification
l add users permission in manifest, also i read all reference document about notification channel however i don't know how to enable floating notification and lock screen notification in code
outlook, gmail etc. some app enable all notification when it installed
above screenshot is my app
i want enable all notification when installed my app
necessarily Even if it is not in xamarin, a solution using kotlin or java is fine!
For floating notification, you should change Notification priority or NotificationChannel importance.
Android 5.0 - Android 7.1
Set notification priority to NotificationPriority.High or NotificationPriority.Max.
builder.SetPriority((int)NotificationPriority.High)
Set ringtone and vibrations. You can use SetDefaults.
// Turn on sound if the sound switch is on:
notification.Defaults |= NotificationDefaults.Sound;
// Turn on vibrate if the sound switch is on:
notification.Defaults |= NotificationDefaults.Vibrate;
Android 8.0 and higher
Set notification channel priority to NotificationImportance.High or NotificationImportance.Max.
var channel = new NotificationChannel(CHANNEL_ID1, name, NotificationImportance.Max)
{
Description = description
};
For lock notifications, you could set the Visibility.
Beginning with Android 5.0, the visibility setting is available to control how much notification content appears on the secure lock screen.
NotificationVisibility.Public – The full content of the notification
is displayed on the secure lock screen.
NotificationVisibility.Private – Only essential information is displayed on the secure lock screen (such as the notification icon and the name of the app that posted it), but the rest of the notification's details are hidden. All notifications default to NotificationVisibility.Private.

Is there possibility to "Auto-start" application when users become inactive?

I have to create an app, which detects user inactivity, and then start activity which displays some videos with WebView, and then when displaying with WebView is finished, it has to play videos from SDCard. I've already handled part with WebView and SDCard (with JavaScriptInterface etc.)
This application has to work with API 19 all the way to the newest one.
The question is - Is there a possibility to detect if user is inactive and start my application, or keep the app running in background, and then start activity in the foreground after the user becomes inactive for certain time?
I'm not trying to play ads, when user is not looking at his screen. Application is for my client, who have stores with all kind of electrical equipments, including smartphones. The goal is to play video presentations with hardware details specific for each smartphone (informations about processor, ram, camera, screen etc.).
In short: I have to make an app which is similar to "Demo Apps" created for example by Samsung (playing some kind of presentations on screen).
So far I've read and tested things like:
1) BroadcastReceiver with combination of ACTION_SCREEN_OFF / ACTION_SCREEN_ON events.
Receiver works properly, I can detect this event and then start activity, but... The screen is already off so i can't see the displayed activity - it's visible running in the foreground after unlocking the phone. Is there a way to unlock the phone when the event is received?
That's my code so far.
EventReceiver Class:
class EventReceiver: BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
StringBuilder().apply {
append("Action: ${intent.action}\n")
append("URI: ${intent.toUri(Intent.URI_INTENT_SCHEME)}\n")
toString().also { log ->
Log.d(TAG, log)
Toast.makeText(context, log, Toast.LENGTH_LONG).show()
}
}
if (intent.action == Intent.ACTION_SCREEN_OFF) {
val i = Intent(context, MainActivity::class.java)
context.startActivity(i)
}
}
}
MainActivity Class:
val br : BroadcastReceiver = EventReceiver()
val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION).apply {
addAction(Intent.ACTION_SCREEN_OFF)
addAction(Intent.ACTION_SCREEN_ON)
addAction(Intent.ACTION_BOOT_COMPLETED)
}
2) Foreground Services - I read that this is a great way to make some asyc stuff in the background and show notifications to user. Is there a way to start the activity with it?
3) Job Scheduler
4) Daydream / Dream Service - it actually works great with almost every API and manufacturer, but.. there's no way to set the app as Screen Saver on Huawei/Honor smartphones, at least from phone settings, I've read that this is possible with ADB etc. but this is not an option that I can use here.
It seems that none of these fullfill my expectations.

How force the app to opt out of battery saver mode when the service is ON?

The expected behavior is that the app will be running all the time when it's in ON state. Some phones put the app in background mode when the app is not active for some time. I want the app to be running all the time even its in standby mode(standby mode means when we press the home button the app will go to background. and it will run for some time).
I found following code and I tried that
PowerManager powerManager = (PowerManager) getApplicationContext().getSystemService(POWER_SERVICE);
String packageName = "org.traccar.client";
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Intent i = new Intent();
if (!powerManager.isIgnoringBatteryOptimizations(packageName)) {
i.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
i.setData(Uri.parse("package:" + packageName));
startActivity(i);
}
else{
i.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
i.setData(Uri.parse("package:" + packageName));
startActivity(i);
}
}
Even after working with the code the default state is Battery Saver(recommended)
I want the app in No Restriction mode once the app is opened, any solution for this?
The code you use is for battery optimization. Settings-->Batery-->Three Dots Menu Item (...)--->Battery Optimization-->(Choose an app from list)--->Optimize/ Don't optimize.
By choosing Don't optimize you are essentially bypassing Doze, not app standby.
Also be advised that doing this programmatically as you do may result in Google taking your app off the store. It is safer to do it manually following the path i described above.
More on Doze and App Standby here

onTaskRemoved not being called in service above android 6.please can some one give better alternative

I've been using onTaskRemoved() method in a Service to detect when an app was removed from the device's RECENT list by swiping it away. I preform some logging and some other operations that need to take place when this happens. It works perfectly. For android below 6... But background service is being killed after swiping off in android 6.
#Override
public void onTaskRemoved(Intent rootIntent) {
Log.e("ClearFromRecentSsss", "sttttts");
Intent intent = new Intent("in.com.example");
sendBroadcast(intent);
}
Some manufactures like xiaomi, Oppo have their own background strategy which is autostart. You need to redirect user to auto start activity and tell user to switch on:
Go like this and allow your app to autostart:
Settings > permissions > Autostart
Autostart setting varies by manufactures like in Xiaomi you can find it in their SecurityCenter app.
Autostart is blocking your service to restart, So turn it on manually and the check again . I'm afraid there is no inbuilt API to do so . So you need to redirect users to specified screen as per manufactures to turn auto start On. Have a look at Links below:
link1
link2

Using Power Manager

My app sets an alarm. While waiting for the alarm my phone closes the screen. When the alarm sounds the screen is dark so I press the power key and the screen lights up but I now have to touch the Lock button to access the app interface. I would prefer that the Lock has been disposed off when the user responds to the alarm so I tried to use the power manager. The alarm receiver starts a new activity so I initialised the power manager in the onCreate for this activity. However this causes a force close error. I call the power manager as follows
PowerManager pm = (PowerManager)cText.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK , TAG);
wl.acquire();
Any suggestions please.
Did add the uses permisson for power mananger in your manifest?
Since the person asking the question states that he "has to touch the lock" button I assume that he is speaking about the Key Guard. (Pattern, Pin etc). You cannot use the PowerManager API to disable this. Instead you should diable the KeyGuard
KeyguardManager keyguardManager =
(KeyguardManager) getSystemService(Activity.KEYGUARD_SERVICE);
KeyguardManager.KeyguardLock lock =
keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);
lock.disableKeyguard();
To My knowledge, this is the correct way to disable the Screen Lock.
You also need this Permission
<uses-permission android:name="android.permission.DISABLE_KEYGUARD"/>
You can take wl in Application context so once its initlize and set back to that and after that when you release that you will set null and check that it again if its null than init again other wise take it as it is.

Categories