how to restart a non-rooted device? - java

After reading a lot of answers at SO and the android docs, it seems to be impossible to restart a device without root permission.
The app doesn't even ask me if I'd like to grand the permission.
// 1. Use permission in Manifest
<uses-permission android:name="android.permission.REBOOT" />
// 2. Request permission in MainActivity
if (ContextCompat.checkSelfPermission(this, Manifest.permission.REBOOT) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.REBOOT}, 1);
}
// 3. Restart on button click
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
pm.reboot(null);
Error:
java.lang.SecurityException: Neither user 10201 nor current process has android.permission.REBOOT.
Is there any workaround that I missed?
Thank you very much!
B.

No, you can't do this from your Android application without root permissions but you can do this from the terminal by using the command: "adb reboot". But if you can root your device then you can use the following code to reboot:
try {
Process process = Runtime.getRuntime().exec("adb reboot");
} catch (IOException e) {
e.printStackTrace();
}
And if this too get failed on a rooted device then you can try with this by asking for root permission(tried on android kitkat 4.4),
try{
List<String> envList = new ArrayList<String>();
Map<String, String> envMap = System.getenv();
for (String envName : envMap.keySet()) {
envList.add(envName + "=" + envMap.get(envName));
}
final String[] environment = (String[]) envList.toArray(new String[0]);
String command= "reboot";
Runtime.getRuntime().exec(
new String[]{"su", "-c", command},
environment).waitFor();
}catch(IOException e){
//catch exception
}

Related

W/System: A resource failed to call release. Broadcast receiver

When I try to get broadcast for incomming call:
BroadcastReceiver br = new MyBroadcastReceiver();
IntentFilter filter = new IntentFilter(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
filter.addAction(Intent.ACTION_SCREEN_OFF);
MainApplication.getAppContext().registerReceiver(br, filter);
I got an error when doing or receiving a call:
W/System: A resource failed to call release.
The ACTION_SCREEN_OFF works fine, but ACTION_PHONE_STATE_CHANGED do not. My APP has a webRTC connection open. In other APP that dosen't work with webRTC, ACTION_PHONE_STATE_CHANGED works fine.
I'm trying to make the audio back to speaker after a incomming call.
Some clue? Thanks!
The problem was that I haven't set uses-permission in the manifest.
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
And of course, you have to ask the user to use the PHONE_STATE.
React-native way:
(async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.READ_PHONE_STATE,
{
'title': 'ReactNativeCode Location Permission',
'message': 'ReactNativeCode App needs access to your phone state '
}
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
Alert.alert("Location Permission Granted.");
}
else {
Alert.alert("Location Permission Not Granted");
}
} catch (err) {
console.warn(err)
}
})()

How can i disable any android app such that it cannot be opened until i change/press some button in app?

I am trying to build a parental control app. So now i want to disable or lock app (like Whatsapp, Facebook, etc). I have tried using PackageManager.setComponentEnabledSetting(). But it is throwing java.lang.SercurityException.
So how can I make a parental control app such that I can disable any app I want without root.
my code is
pm.setComponentEnabledSetting(new ComponentName(temp.activityInfo.packageName,
temp.activityInfo.name+".class"),
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
my error was this
java.lang.SecurityException: Permission Denial: attempt to change component state from pid=11537, uid=10067, package uid=10029
You must add below permissions to manifest.
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS"/>
but , these permissions are for System apps and you can not use. :(
You can not write a app to lock or close another app.this is a policy in Google.
for lock a app you must check running apps repeatedly, if specific app is open,then show a activity over that.
while(!Thread.currentThread().isInterrupted())
{
String topActivity = getFrontApp();
if(topActivity.isEmpty())
{
threadSleep(500);
continue;
}
if(topActivity.equals("lockApp"))
{
showLockActivity();
}
threadSleep(500);
}
// for Api21+ need permission
public static String getFrontApp()
{
if (Build.VERSION.SDK_INT >= 21)
{
UsageStatsManager usageManager = SystemMaster.getUsageStatsManager();
long now = System.currentTimeMillis();
List<UsageStats> localList = usageManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, now - 900_000L, now);
String str = "";
if (localList != null)
{
SortedMap<Long,UsageStats> mySortedMap = new TreeMap<>();
for(UsageStats usageStats : localList)
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
if(!mySortedMap.isEmpty())
str = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
return str;
}
else
{
ActivityManager am = (ActivityManager) getApplication().getSystemService(Context.ACTIVITY_SERVICE);
return am.getRunningTasks(1).get(0).topActivity.getPackageName();
}
above code is very simple , for real app must write more.

How to record data while app is not in focus?

I've created an app that records data usage of an app and writes it to a file on the phones sd card. Now I'm trying to allow this process to run in the background through the use of adb. I want to be able to send a signal/broadcast to the app to write the current data usage. And later be able to send a second signal that writes the data usage and the new time. So that one can look at how much data the app has used.
So far I've tried using adb and sending broadcasts to the app and it seems to be working however I am not able to save the file to the sd card through the use of mediascanner.
This is the function that is run when I send "adb -d shell am broadcast -n com.axel.datatracking/.IntentReceiver --es --start 'com.linku.android.mobile_emergency.app.activity' " to the app.
public void startLog(Context context, SimplifiedAppInfo selectedApp) {
int i = 0;
String name = "dataFile.csv";
Log.d("update", "sort of works maybe");
// make the file if it already exists increment the name by 1
try {
testFile = new File(context.getExternalFilesDir(null), name);
while(testFile.exists()) {
i++;
name = this.makeFileName(i);
testFile = new File(context.getExternalFilesDir(null), name);
}
Log.d("filename", name);
testFile.createNewFile();
} catch (IOException e) {
Log.d("broke", "Unable to write my dood");
}
// try to write to the file
try {
fOut = new FileOutputStream(testFile);
BufferedWriter writer = new BufferedWriter(new FileWriter(testFile, true));
startingDown = selectedApp.getDownbytes();
startingUp = selectedApp.getUpbyts();
startingTime = System.currentTimeMillis();
writer.write("data,up,down\n");
writer.write("Initial,"+selectedApp.getUpbyts()+","+selectedApp.getDownbytes()+"\n");
writer.close();
// refresh the data file
//MediaScannerConnection.scanFile(context, new String[]{this.testFile.toString()}, null, null);
} catch (IOException e) {
Log.d("broke", "cant write to the file");
}
}
This is the function to write the end results that is run by "adb -d shell am broadcast -n com.axel.datatracking/.IntentReceiver --es --end 'com.linku.android.mobile_emergency.app.activity' "
public void endLog(Context context, SimplifiedAppInfo selectedApp) {
// write end results to file
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(testFile, true));
writer.write("End,"+selectedApp.getUpbyts()+","+selectedApp.getDownbytes()+"\n");
float effectiveDown = selectedApp.getDownbytes() - startingDown;
float effectiveUp = selectedApp.getUpbyts() - startingUp;
writer.write("Effective,"+effectiveUp+","+effectiveDown+"\n");
float timePassed = ((float) ((System.currentTimeMillis() - startingTime)/1000));
float avgUp = effectiveUp/timePassed;
float avgDown = effectiveDown/timePassed;
writer.write("Average bytes/sec,"+avgUp+","+avgDown+"\n");
writer.close();
fOut.close();
//MediaScannerConnection.scanFile(context, new String[]{this.testFile.toString()},null, null);
} catch (IOException e) {
Log.d("broke", "the write dont work");
}
}
Broadcast receivers components are not allowed to bind to services.
Edit: I'm open to other solutions besides using a broadcast receiver I just need to be able to log the data while outside of the app and focusing on another app, from the terminal.
Register receiver in manifest and then make some Receiver class, example:
public class CustomReceiver extends BroadcastReceiver {
#Override
public final void onReceive(Context context, Intent intent){
//// here you can start your own service or do logic here
}
here is how to register receiver in Manifest just pick different intent filter:
<receiver android:name="com.example.example.CustomReceiver ">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
And onReceive going to be called whenever phone action will be triggered.
I would advice to read documentation about Intents because Android has a lot of restrictions, per

How to change permissions to incoming file in linux using JAVA

Objective
I want that whenever someone uploads a file (name is Accounts 0998.csv) in /opt/file/incoming directory. Its permissions gets change to chmod 664 i.e rw-rw-r
I am using linux.
I want to automate this process so I am writing a java program but its working
package com.reader.file;
import java.io.File;
import java.io.IOException;
public class GrantPermission
{
public static void main( String[] args )
{
try {
File file = new File("/opt/file/Accounts 0998.csv");
if(file.exists()){
System.out.println("File exists.");
//using PosixFilePermission to set file permissions 664
Set<PosixFilePermission> perms = new
HashSet<PosixFilePermission>();
//add owners permission
perms.add(PosixFilePermission.OWNER_READ);
perms.add(PosixFilePermission.OWNER_WRITE);
//add group permissions
perms.add(PosixFilePermission.GROUP_READ);
perms.add(PosixFilePermission.GROUP_WRITE);
//add others permissions
perms.add(PosixFilePermission.OTHERS_READ);
Files.setPosixFilePermissions(file.toPath(), perms);
} catch (IOException e) {
e.printStackTrace();
}
}
else{
System.out.println("File does not exists.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Additional Information
I am using WSO2 ESB it first search for a file then If file exists then I want to change its permission (via using Class mediator i.e JAVA) and then move it to another directory but my GOAL is change file permissions to rw-rw-r
You can use NIO.2 if you are using java7 or later.
See:
How do i programmatically change file permissions?
//if you need rw-rw-r permissions
public void setPermission(File file) throws IOException{
Set<PosixFilePermission> perms = new HashSet<>();
perms.add(PosixFilePermission.OWNER_READ);
perms.add(PosixFilePermission.OWNER_WRITE);
perms.add(PosixFilePermission.OTHERS_READ);
perms.add(PosixFilePermission.OTHERS_WRITE);
perms.add(PosixFilePermission.GROUP_READ);
Files.setPosixFilePermissions(file.toPath(), perms);
}

Add android.permission.MANAGE_USB permission to existing system application

We have an application installed on a rooted device as a system application. The latter doesn't have the android.permission.MANAGE_USB and we want to add it to a newer version so that the permission is given to the user automatically. I have followed the post:
bypass android usb host permission confirmation dialog
More specifically, the answer marked as correct from the user d_d_t.
Why doesn't it work? I mean, I have taken this newer version, directly installed it as our original system application and it works perfectly! But when I update the existing version with no usb permission with the newer version it just doesn't work. The new one is just an update. Same certificate and all.
I'm at a loss. Any thoughts?
Our code below:
AndroidManifest.xml.
<uses-permission
android:name="android.permission.MANAGE_USB"
android:protectionLevel="signature" />
Java class.
try {
PackageManager pm = getApplicationContext().getPackageManager();
ApplicationInfo ai = pm.getApplicationInfo(getApplicationContext().getPackageName(), 0);
if (ai != null) {
UsbManager manager = (UsbManager) getApplicationContext().getSystemService(Context.USB_SERVICE);
IBinder b = ServiceManager.getService(Context.USB_SERVICE);
IUsbManager service = IUsbManager.Stub.asInterface(b);
HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
while (deviceIterator.hasNext()) {
UsbDevice device = deviceIterator.next();
if (device.getVendorId() == 0x0403) {
service.grantDevicePermission(device, ai.uid);
service.setDevicePackage(device,getApplicationContext().getPackageName(), 0);
}
}
}
} catch (Exception e) {
Log.e("UsbReceiver", "exception " + e);
e.printStackTrace();
}

Categories