Note that there are some explanatory texts on larger screens.

plurals
  1. POAndroid Broadcast Receiver battery life every 10 mins or change, can it go in its own thread?
    primarykey
    data
    text
    <p>I would like to write an application (for research) that makes a timestamp every time the battery level changes. If I can't do that, I want to make it so it takes a battery reading every 10 or so minutes. </p> <p>I have this <code>BroadcastReceiver</code> code but I am not sure where to put it.</p> <p>My application keeps crashing with the following exception:</p> <blockquote> <p>java.lang.RuntimeException: Error receiving broadcast Intent { act=android.intent.action.BATTERY_CHANGED flg=0x60000000 (has extras) } in com.mdog.datareceive.Receive$1@43c9cd10</p> </blockquote> <p>In the <code>onCreate</code> of my activity I spawn 3 AsyncTask threads that do stuff in the background. Where would be a good place to put the broadcast receiver? </p> <p>I have tried in the <code>onCreate</code> and I have tried in a new method that gets called by one of the background tasks. I think the problem might be that the function the <code>BroadcastRecevier</code> code is in might be ending prematurely? </p> <p>Is there anyway I could put it in its own thread so that it just waits for broadcasts?</p> <p><strong>Code:</strong></p> <pre><code>batteryLevelTimeStamps = new LinkedList&lt;String&gt;(); BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver(){ @Override public void onReceive(Context context, Intent intent){ int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1); int level = -1; if (rawlevel &gt;= 0 &amp;&amp; scale &gt; 0) { level = (rawlevel * 100) / scale; } batteryLevel = level + "%"; batteryLevelTimeStamps.add("At time: " + new Date().toString() + " the battery level is:" +batteryLevel); out.print("At time: " + new Date().toString() + " the battery level is:" +batteryLevel + " in onCreate\n"); } }; IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); registerReceiver(batteryLevelReceiver, batteryLevelFilter); </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload