Skip to content

Commit

Permalink
use device admin for power-off & lockscreen when root access is not a…
Browse files Browse the repository at this point in the history
…vailable
  • Loading branch information
pgp committed Jan 9, 2024
1 parent 310743b commit 9f7fc32
Show file tree
Hide file tree
Showing 7 changed files with 296 additions and 7 deletions.
4 changes: 2 additions & 2 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ android {
applicationId "it.pgp.currenttoggles"
minSdkVersion 21 // for sdk 19 and lower, just use the great PowerToggles :)
targetSdkVersion 28 // do not raise this, otherwise wifi toggle won't work without root on api 29+
versionCode 125230305
versionName "1.2.5"
versionCode 126240109
versionName "1.2.6"
}

buildTypes {
Expand Down
12 changes: 12 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,18 @@
android:name="android.appwidget.provider"
android:resource="@xml/mainwidget_info" />
</receiver>

<receiver
android:name=".utils.deviceadmin.AdminReceiver"
android:label="@string/device_admin_lockscreen"
android:permission="android.permission.BIND_DEVICE_ADMIN">
<meta-data
android:name="android.app.device_admin"
android:resource="@xml/device_admin_lockscreen" />
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
</intent-filter>
</receiver>
</application>

</manifest>
35 changes: 30 additions & 5 deletions app/src/main/java/it/pgp/currenttoggles/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import android.app.Activity;
import android.app.NotificationManager;
import android.app.admin.DevicePolicyManager;
import android.bluetooth.BluetoothAdapter;
import android.content.ComponentName;
import android.content.ContentResolver;
Expand All @@ -15,6 +16,7 @@
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.PowerManager;
import android.provider.Settings;
import android.text.Html;
import android.util.Log;
Expand All @@ -28,6 +30,7 @@

import it.pgp.currenttoggles.utils.Misc;
import it.pgp.currenttoggles.utils.RootHandler;
import it.pgp.currenttoggles.utils.deviceadmin.AdminReceiver;
import it.pgp.currenttoggles.utils.oreoap.MyOnStartTetheringCallback;
import it.pgp.currenttoggles.utils.oreoap.MyOreoWifiManager;
import it.pgp.currenttoggles.utils.oreoap.PreOreoWifiManager;
Expand Down Expand Up @@ -65,7 +68,7 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
else Toast.makeText(this, "Please grant notifications permissions on Android 13 in order to show toast messages from widget", Toast.LENGTH_SHORT).show();
finishAffinity();
}
else if(requestCode == 1235) finishAffinity();
else if(requestCode == 1235 || requestCode == 1236) finishAffinity();
}

@Override
Expand All @@ -88,6 +91,13 @@ else if(extras.getString("HOTSPOT_OPTIONS") != null) {
startActivityForResult(options, 1235);
return;
}
else if(extras.getString("DEVICEADMIN_OPTIONS") != null) {
ComponentName admin = new ComponentName(getApplicationContext(), AdminReceiver.class);
Intent options = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
options.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, admin);
startActivityForResult(options, 1236);
return;
}
}
setContentView(R.layout.activity_main);
}
Expand Down Expand Up @@ -347,15 +357,30 @@ public static void toggleHotspot(Context context) {
}
}

public static void powerOffScreenViaDeviceAdmin(Context context) {
PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
if (pm.isScreenOn()) {
DevicePolicyManager policy = (DevicePolicyManager)context.getSystemService(Context.DEVICE_POLICY_SERVICE);
try {
policy.lockNow();
}
catch(Exception ex) {
postToast(context, "Device administrator capability is needed for powering off screen without root access");
Intent options = new Intent(context, MainActivity.class);
options.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
options.putExtra("DEVICEADMIN_OPTIONS", "");
context.startActivity(options);
}
}
}

public static void turnOffAndLockScreen(Context context) {
int exitCode = -1;
try {
exitCode = RootHandler.executeCommandAndWaitFor("input keyevent KEYCODE_POWER",null,true,null);
}
catch(IOException e) {
e.printStackTrace();
}
if(exitCode != 0) postToast(context, "Unable to turn off screen");
catch(IOException ignored) {}
if(exitCode != 0) powerOffScreenViaDeviceAdmin(context);
}

public void toggle(View v) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package it.pgp.currenttoggles.utils.deviceadmin;

import android.app.admin.DeviceAdminReceiver;
import android.content.Context;
import android.content.Intent;

public class AdminReceiver extends DeviceAdminReceiver {
public static final String ACTION_DISABLED = "device_admin_disabled";
public static final String ACTION_ENABLED = "device_admin_enabled";

@Override
public void onDisabled(Context context, Intent intent) {
super.onDisabled(context, intent);
LocalBroadcastManager.getInstance(context).sendBroadcast(
new Intent(ACTION_DISABLED));
}
@Override
public void onEnabled(Context context, Intent intent) {
super.onEnabled(context, intent);
LocalBroadcastManager.getInstance(context).sendBroadcast(
new Intent(ACTION_ENABLED));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
package it.pgp.currenttoggles.utils.deviceadmin;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

public final class LocalBroadcastManager {
private static final class ReceiverRecord {
final IntentFilter filter;
final BroadcastReceiver receiver;
boolean broadcasting;
boolean dead;

ReceiverRecord(IntentFilter _filter, BroadcastReceiver _receiver) {
filter = _filter;
receiver = _receiver;
}

@Override
public String toString() {
StringBuilder builder = new StringBuilder(128);
builder.append("Receiver{");
builder.append(receiver);
builder.append(" filter=");
builder.append(filter);
if (dead) builder.append(" DEAD");
builder.append("}");
return builder.toString();
}
}

private static final class BroadcastRecord {
final Intent intent;
final ArrayList<ReceiverRecord> receivers;

BroadcastRecord(Intent _intent, ArrayList<ReceiverRecord> _receivers) {
intent = _intent;
receivers = _receivers;
}
}

private static final String TAG = "LocalBroadcastManager";
private static final boolean DEBUG = false;

private final Context mAppContext;

private final HashMap<BroadcastReceiver, ArrayList<ReceiverRecord>> mReceivers = new HashMap<>();
private final HashMap<String, ArrayList<ReceiverRecord>> mActions = new HashMap<>();

private final ArrayList<BroadcastRecord> mPendingBroadcasts = new ArrayList<>();

static final int MSG_EXEC_PENDING_BROADCASTS = 1;

private final Handler mHandler;

private static final Object mLock = new Object();
private static LocalBroadcastManager mInstance;

public static LocalBroadcastManager getInstance(Context context) {
synchronized(mLock) {
if(mInstance == null) mInstance = new LocalBroadcastManager(context.getApplicationContext());
return mInstance;
}
}

private LocalBroadcastManager(Context context) {
mAppContext = context;
mHandler = new Handler(context.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
switch(msg.what) {
case MSG_EXEC_PENDING_BROADCASTS:
executePendingBroadcasts();
break;
default:
super.handleMessage(msg);
}
}
};
}

public void registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
synchronized (mReceivers) {
ReceiverRecord entry = new ReceiverRecord(filter, receiver);
ArrayList<ReceiverRecord> filters = mReceivers.get(receiver);
if(filters == null) {
filters = new ArrayList<>(1);
mReceivers.put(receiver, filters);
}
filters.add(entry);
for(int i=0; i<filter.countActions(); i++) {
String action = filter.getAction(i);
ArrayList<ReceiverRecord> entries = mActions.get(action);
if(entries == null) {
entries = new ArrayList<>(1);
mActions.put(action, entries);
}
entries.add(entry);
}
}
}

public void unregisterReceiver(BroadcastReceiver receiver) {
synchronized(mReceivers) {
ArrayList<ReceiverRecord> filters = mReceivers.remove(receiver);
if(filters == null) return;
for(int i=filters.size()-1; i>=0; i--) {
final ReceiverRecord filter = filters.get(i);
filter.dead = true;
for(int j=0; j<filter.filter.countActions(); j++) {
final String action = filter.filter.getAction(j);
final ArrayList<ReceiverRecord> receivers = mActions.get(action);
if(receivers != null) {
for(int k=receivers.size()-1; k>=0; k--) {
ReceiverRecord rec = receivers.get(k);
if(rec.receiver == receiver) {
rec.dead = true;
receivers.remove(k);
}
}
if(receivers.size() <= 0) mActions.remove(action);
}
}
}
}
}

public boolean sendBroadcast(Intent intent) {
synchronized (mReceivers) {
final String action = intent.getAction();
final String type = intent.resolveTypeIfNeeded(mAppContext.getContentResolver());
final Uri data = intent.getData();
final String scheme = intent.getScheme();
final Set<String> categories = intent.getCategories();

boolean debug = DEBUG || ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
if(debug) Log.v(TAG, "Resolving type " + type + " scheme " + scheme + " of intent " + intent);

ArrayList<ReceiverRecord> entries = mActions.get(intent.getAction());
if(entries != null) {
if(debug) Log.v(TAG, "Action list: " + entries);

ArrayList<ReceiverRecord> receivers = null;
for(int i=0; i<entries.size(); i++) {
ReceiverRecord receiver = entries.get(i);
if(debug) Log.v(TAG, "Matching against filter " + receiver.filter);

if(receiver.broadcasting) {
if(debug) Log.v(TAG, " Filter's target already added");
continue;
}

int match = receiver.filter.match(action, type, scheme, data, categories, "LocalBroadcastManager");
if(match >= 0) {
if(debug) Log.v(TAG, " Filter matched! match=0x" + Integer.toHexString(match));
if(receivers == null) receivers = new ArrayList<>();
receivers.add(receiver);
receiver.broadcasting = true;
}
else {
if(debug) {
String reason;
switch(match) {
case IntentFilter.NO_MATCH_ACTION: reason = "action"; break;
case IntentFilter.NO_MATCH_CATEGORY: reason = "category"; break;
case IntentFilter.NO_MATCH_DATA: reason = "data"; break;
case IntentFilter.NO_MATCH_TYPE: reason = "type"; break;
default: reason = "unknown reason"; break;
}
Log.v(TAG, " Filter did not match: " + reason);
}
}
}

if(receivers != null) {
for(int i=0; i<receivers.size(); i++) receivers.get(i).broadcasting = false;
mPendingBroadcasts.add(new BroadcastRecord(intent, receivers));
if(!mHandler.hasMessages(MSG_EXEC_PENDING_BROADCASTS))
mHandler.sendEmptyMessage(MSG_EXEC_PENDING_BROADCASTS);
return true;
}
}
}
return false;
}

public void sendBroadcastSync(Intent intent) {
if(sendBroadcast(intent)) executePendingBroadcasts();
}

private void executePendingBroadcasts() {
for(;;) {
final BroadcastRecord[] brs;
synchronized(mReceivers) {
final int N = mPendingBroadcasts.size();
if(N <= 0) return;
brs = new BroadcastRecord[N];
mPendingBroadcasts.toArray(brs);
mPendingBroadcasts.clear();
}
for(int i=0; i<brs.length; i++) {
final BroadcastRecord br = brs[i];
final int nbr = br.receivers.size();
for(int j=0; j<nbr; j++) {
ReceiverRecord rec = br.receivers.get(j);
if(!rec.dead) rec.receiver.onReceive(mAppContext, br.intent);
}
}
}
}
}

1 change: 1 addition & 0 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
<resources>
<string name="app_name">CurrentToggles</string>
<string name="device_admin_lockscreen">Device admin for lockscreen</string>
</resources>
6 changes: 6 additions & 0 deletions app/src/main/res/xml/device_admin_lockscreen.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?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>

0 comments on commit 9f7fc32

Please sign in to comment.