0

How do I grant access to my android app to read the CPU temp files in the internal storage files? I have been trying to get this working for quite a while now and have not made any progress. Below I have included the current methods I have for accessing the CPU temp files. I have also included my AndroidManifest.xml file.

Error I am receiving when trying to read the CPU temp:

2023-03-03 23:21:12.178  5266-5266  System.err              com.example.racestats                W  java.io.FileNotFoundException: /sys/devices/virtual/thermal/thermal_zone0/temp: open failed: EACCES (Permission denied)
2023-03-03 23:21:12.179  5266-5266  System.err              com.example.racestats                W      at libcore.io.IoBridge.open(IoBridge.java:574)
2023-03-03 23:21:12.179  5266-5266  System.err              com.example.racestats                W      at java.io.RandomAccessFile.<init>(RandomAccessFile.java:289)
2023-03-03 23:21:12.179  5266-5266  System.err              com.example.racestats                W      at java.io.RandomAccessFile.<init>(RandomAccessFile.java:152)
2023-03-03 23:21:12.179  5266-5266  System.err              com.example.racestats                W      at com.example.racestats.MainActivityKt.getCpuTemperature(MainActivity.kt:171)
2023-03-03 23:21:12.180  5266-5266  System.err              com.example.racestats                W      at com.example.racestats.MainActivityKt.cpuTemperature$lambda$0(MainActivity.kt:157)
2023-03-03 23:21:12.180  5266-5266  System.err              com.example.racestats                W      at com.example.racestats.MainActivityKt.$r8$lambda$vjQE1RADCplWY99vEEfe1Z4FocA(Unknown Source:0)
2023-03-03 23:21:12.180  5266-5266  System.err              com.example.racestats                W      at com.example.racestats.MainActivityKt$$ExternalSyntheticLambda0.onClick(Unknown Source:4)
2023-03-03 23:21:12.180  5266-5266  System.err              com.example.racestats                W      at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:175)
2023-03-03 23:21:12.180  5266-5266  System.err              com.example.racestats                W      at android.os.Handler.dispatchMessage(Handler.java:106)
2023-03-03 23:21:12.180  5266-5266  System.err              com.example.racestats                W      at android.os.Looper.loopOnce(Looper.java:201)
2023-03-03 23:21:12.180  5266-5266  System.err              com.example.racestats                W      at android.os.Looper.loop(Looper.java:288)
2023-03-03 23:21:12.180  5266-5266  System.err              com.example.racestats                W      at android.app.ActivityThread.main(ActivityThread.java:7872)
2023-03-03 23:21:12.180  5266-5266  System.err              com.example.racestats                W      at java.lang.reflect.Method.invoke(Native Method)
2023-03-03 23:21:12.180  5266-5266  System.err              com.example.racestats                W      at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
2023-03-03 23:21:12.180  5266-5266  System.err              com.example.racestats                W      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
2023-03-03 23:21:12.181  5266-5266  System.err              com.example.racestats                W  Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied)
2023-03-03 23:21:12.181  5266-5266  System.err              com.example.racestats                W      at libcore.io.Linux.open(Native Method)
2023-03-03 23:21:12.181  5266-5266  System.err              com.example.racestats                W      at libcore.io.ForwardingOs.open(ForwardingOs.java:563)
2023-03-03 23:21:12.181  5266-5266  System.err              com.example.racestats                W      at libcore.io.BlockGuardOs.open(BlockGuardOs.java:274)
2023-03-03 23:21:12.181  5266-5266  System.err              com.example.racestats                W      at libcore.io.ForwardingOs.open(ForwardingOs.java:563)
2023-03-03 23:21:12.181  5266-5266  System.err              com.example.racestats                W      at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:7758)
2023-03-03 23:21:12.181  5266-5266  System.err              com.example.racestats                W      at libcore.io.IoBridge.open(IoBridge.java:560)
2023-03-03 23:21:12.181  5266-5266  System.err              com.example.racestats                W      ... 14 more

Kotlin Code:

/**
     * This function will set the CPU Temp in are UI and will handles all things associated with the CPU temp.
     */
    fun cpuTemperature(activity: Activity, callback: (Float) -> Unit) {
        val permissionCheck = ContextCompat.checkSelfPermission(activity, Manifest.permission.MANAGE_EXTERNAL_STORAGE)
    
        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.MANAGE_EXTERNAL_STORAGE)) {
                Toast.makeText(activity, "This permission is required to access the CPU temperature.", Toast.LENGTH_LONG).show()
            }
    
            val alertDialogBuilder = AlertDialog.Builder(activity)
            alertDialogBuilder.setTitle("Permission Request")
            alertDialogBuilder.setMessage("The app needs access to external storage to read the CPU temperature. Do you allow this permission?")
            alertDialogBuilder.setPositiveButton("Allow") { _, _ ->
                ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.READ_INTERNAL_STORAGE), 1)
                ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
                getCpuTemperature(callback)
            }
            alertDialogBuilder.setNegativeButton("Deny") { dialog, _ ->
                dialog.dismiss()
                // set cpu temp to be invisible
            }
            alertDialogBuilder.show()
        } else {
            getCpuTemperature(callback)
        }
    }
    
    fun getCpuTemperature(callback: (Float) -> Unit) {
        return try {
            val reader = RandomAccessFile("/sys/devices/virtual/thermal/thermal_zone0/temp", "r")
            val line: String = reader.readLine()
            if (line != null) {
                val temp = line.toFloat()
                println(temp / 1000.0f)
                callback(temp / 1000.0f)
            } else {
                println(51.0f)
                callback(51.0f)
            }
        } catch (e: Exception) {
            println("about to look for temp")
            e.printStackTrace()
            println("Temp is below")
            println(0.0f)
            callback(0.0f)
        }
    }

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:requestLegacyExternalStorage="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.RaceStats"

        tools:targetApi="31">

        <activity
            android:name=".TopSpeed"
            android:exported="false">
            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
    </application>

</manifest>
Alex
  • 238
  • 4
  • 14
  • Unclear if you've seen/tried: [How to get CPU temperature in Android](https://stackoverflow.com/a/64457961/295004) also you should mention what device/OS version you are testing on. – Morrison Chang Mar 04 '23 at 06:44
  • You cannot grant access. You just have no access. Use File.exists() and File.canRead() before you try to read. – blackapps Mar 04 '23 at 06:51
  • All the permissions you mentioned are not usable for the path you tried. – blackapps Mar 04 '23 at 07:58
  • @MorrisonChang I did try that and I got the same error. – Alex Mar 05 '23 at 06:42
  • @blackapps then what permissions should I be using for that path? – Alex Mar 05 '23 at 06:42
  • You still don't mention which device / OS version you are testing on. Do realize that the paths in the list I linked to may vary by device / OS version. You may want to install [Termux](https://f-droid.org/en/packages/com.termux/) and see what paths are valid based on this thread: https://www.reddit.com/r/termux/comments/g5vkm8/can_termux_get_the_temperature_of_the_phones_soc/ – Morrison Chang Mar 05 '23 at 07:04
  • We do not see you using File.exists() and File.canRead() before you try to read. – blackapps Mar 05 '23 at 07:49

0 Answers0