Running a repeating task in background on a real time application

后端 未结 2 994
青春惊慌失措
青春惊慌失措 2021-01-16 17:38

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

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-16 18:36

    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.

    public class YOURCLASS_Service extends Service {
        private long mStartTime = 0L;
        private final Handler mHandler = new Handler();
        private Runnable mUpdateTimeTask;
        private YOURAPP app;
    
        @Override
        public void onCreate() {
            super.onCreate();
            app = (YOURAPP) getApplicationContext();
        }
    
        @Override
        public void onDestroy() {
            Toast.makeText(this, "Service finished.", Toast.LENGTH_SHORT).show();
            stopLog ();
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            if (app.isRunning())
                return START_STICKY;
            try {
                File file = new File(Environment.getExternalStorageDirectory(), "yourlog.csv");
                OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(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 = new Runnable() {
                public void run() {
                    long millis = SystemClock.uptimeMillis() - mStartTime;
                    int seconds = (int) (millis / 1000);
                    int minutes = 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);
    
            Notification notification = new Notification(R.drawable.notification_icon, "App title", System.currentTimeMillis());
            Intent notificationIntent = new Intent(this, YOURCLASS.class);
            PendingIntent contentIntent = 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;
        }
    
        @Override
        public IBinder onBind(Intent arg0) {
            return null;
        }
    
        public void stopLog () {
                mHandler.removeCallbacks(mUpdateTimeTask);
        }
    }    
    

提交回复
热议问题