DEV Community

Morteza moradi
Morteza moradi

Posted on

Logger Service

This is a simple example of how you can create a service that logs the date and time every 5 seconds. This service will also log when it's created and when it's stopped.

This example uses a Handler and Runnable to schedule the logging task every 5 seconds.

Please note that this is a simple example and doesn't handle all edge cases. For example, it doesn't handle the case where the device is rebooted or the app is force stopped.

`import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class LoggingService extends Service {
private static final String TAG = "LoggingService";
private Handler handler;
private Runnable runnable;
private SimpleDateFormat dateFormat;

@Override
public void onCreate() {
    super.onCreate();
    Log.d(TAG, "Service created");

    handler = new Handler();
    runnable = new Runnable() {
        @Override
        public void run() {
            logTime();
            handler.postDelayed(this, 5000);
        }
    };

    dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());

    logToFile("Service created at " + dateFormat.format(new Date()));
    handler.post(runnable);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();
    handler.removeCallbacks(runnable);
    logToFile("Service stopped at " + dateFormat.format(new Date()));
    Log.d(TAG, "Service stopped");
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

private void logTime() {
    String currentTime = dateFormat.format(new Date());
    logToFile("Current time: " + currentTime);
    Log.d(TAG, "Current time: " + currentTime);
}

private void logToFile(String message) {
    File file = new File(getFilesDir(), "log.txt");
    try (FileOutputStream fos = new FileOutputStream(file, true)) {
        fos.write((message + "\n").getBytes());
    } catch (IOException e) {
        Log.e(TAG, "Error writing to file", e);
    }
}
Enter fullscreen mode Exit fullscreen mode

}`
To start the service, you can use the following code in your activity:

Intent intent = new Intent(this, LoggingService.class);
startService(intent);

To stop the service, you can use the following code:

Intent intent = new Intent(this, LoggingService.class);
stopService(intent);

Remember to declare the service in your AndroidManifest.xml:

<service android:name=".LoggingService" />

Please note that starting from Android Oreo (API level 26), the system imposes restrictions on running background services when the app itself is not in the foreground. In such cases, you should consider using a foreground service.

Top comments (0)