Skip to content Skip to sidebar Skip to footer

Running A Repeating Task In Background On A Real Time Application

I'm writing an application which is continuously listening and checking the sensors (almost all available) and saving that data into the database in the device. I need to make som

Solution 1:

You can use AlarmManager to setup the repeating tasks (this is the Android prefered way of setting future/repeating tasks). To make the calculations use a Service (if you think calculations are going to be expensive, then think about moving them to a separate worker thread or use IntentService).

Regarding the wake lock (from the AlarmManager reference):

The Alarm Manager holds a CPU wake lock as long as the alarm receiver's onReceive() method is executing. This guarantees that the phone will not sleep until you have finished handling the broadcast. Once onReceive() returns, the Alarm Manager releases this wake lock. This means that the phone will in some cases sleep as soon as your onReceive() method completes. If your alarm receiver called Context.startService(), it is possible that the phone will sleep before the requested service is launched. To prevent this, your BroadcastReceiver and Service will need to implement a separate wake lock policy to ensure that the phone continues running until the service becomes available.

Solution 2:

This is a modified snippet of a service I wrote to log CPU frequency some time ago. It lacks the Application and the Activity part, but illustrates how I wrote the Service to keep logging every ten seconds. It does not log when the phone goes into deep sleep, so if you want to log without interruptions, then you will need to acquire PARTIAL_WAKE_LOCKs, but consider that battery life will be severely reduced by that.

publicclassYOURCLASS_ServiceextendsService {
    privatelongmStartTime=0L;
    privatefinalHandlermHandler=newHandler();
    private Runnable mUpdateTimeTask;
    private YOURAPP app;

    @OverridepublicvoidonCreate() {
        super.onCreate();
        app = (YOURAPP) getApplicationContext();
    }

    @OverridepublicvoidonDestroy() {
        Toast.makeText(this, "Service finished.", Toast.LENGTH_SHORT).show();
        stopLog ();
    }

    @OverridepublicintonStartCommand(Intent intent, int flags, int startId) {
        if (app.isRunning())
            return START_STICKY;
        try {
            Filefile=newFile(Environment.getExternalStorageDirectory(), "yourlog.csv");
            OutputStreamWriterout=newOutputStreamWriter(newFileOutputStream(file, false));
            out.write("Log title");
            out.close();
        } catch (java.io.IOException e) {
              stopLog ();
              Toast.makeText(this, "Error creating log file. Aborting.", Toast.LENGTH_SHORT).show();
        }

        mUpdateTimeTask = newRunnable() {
            publicvoidrun() {
                longmillis= SystemClock.uptimeMillis() - mStartTime;
                intseconds= (int) (millis / 1000);
                intminutes= seconds / 60;
                seconds     = seconds % 60;

                readYourSensors ();
                   if (!writeLog (str)) stopLog();
                   mHandler.postAtTime(this, mStartTime + (((minutes * 60) + seconds + 10) * 1000));
                   mHandler.postDelayed (mUpdateTimeTask, 10000);
        }};
        mStartTime = SystemClock.uptimeMillis();
        mHandler.removeCallbacks(mUpdateTimeTask);
        mHandler.postDelayed(mUpdateTimeTask, 100);

        Notificationnotification=newNotification(R.drawable.notification_icon, "App title", System.currentTimeMillis());
        IntentnotificationIntent=newIntent(this, YOURCLASS.class);
        PendingIntentcontentIntent= PendingIntent.getActivity(this, 0, notificationIntent, 0);
        notification.setLatestEventInfo(getApplicationContext(), "App title", "Please see /sdcard/yourlog.csv", contentIntent);
        startForeground(startId, notification);

        app.isRunning(true);
        return START_STICKY;
    }

    @Overridepublic IBinder onBind(Intent arg0) {
        returnnull;
    }

    publicvoidstopLog() {
            mHandler.removeCallbacks(mUpdateTimeTask);
    }
}    

Post a Comment for "Running A Repeating Task In Background On A Real Time Application"