Ali Elgazar
Ali Elgazar

Reputation: 777

Permission denied when running stat command from android

Hey guys I have the following code to inspect file stats in Android

Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("stat -c \"%x\" "+file.getAbsolutePath());
proc.waitFor();
int exitvalue=proc.exitValue();

When I run this on Huawei MT7-L09 running Android 4.4.2 it gives me permission denied error, even though this is in my manifest

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

The same code is also being run on an HTC One_m8 running android 6.0, but I don't get the permission denied error there, can anyone tell me what's going on?

Upvotes: 0

Views: 1447

Answers (1)

Patrick R
Patrick R

Reputation: 6857

we can use Os.stat - since api 21, it returns StructStat which contains field st_atime with Time of last access (in seconds).

example: if (Build.VERSION.SDK_INT >= 21) { try { StructStat stat = Os.stat("/path/to/my/file"); if (stat.st_atime != 0) { // stat.st_atime contains last access time, seconds since epoch } } catch (Exception e) { // deal with exception } }

-------> Other solution is to execute shell command stat :

Process p = Runtime.getRuntime().exec("stat -c \"%X\" /path/to/file"); p.waitFor(); BufferedReader reader = new BufferedReader(new InputStreamReader( p.getInputStream())); String line = reader.readLine(); long time_sec = 0; if (!TextUtils.isEmpty()) time_sec = Long.parseLong(line);

------>Third aproach would be to use NDK and call stat function from C or C++.

Upvotes: 3

Related Questions