Skip to content Skip to sidebar Skip to footer

Create Service To Detect Any Action From The User

I'm trying to create a service where I want to detect something about user, let's say when user lays the device on a table, the thing is that I have that action detected but I have

Solution 1:

First of all you need to decide whether you want the user to be aware of your running service or not. Take a review on Background Execution Limits in android Oreo:

To improve the user experience, Android 8.0 (API level 26) imposes limitations on what apps can do while running in the background.

So considering your case where it seems there are lots of work to do in many situations, it would be a better approach to use a foreground service. As android document says about foreground services:

A foreground service is a service that the user is actively aware of and is not a candidate for the system to kill when low on memory. A foreground service must provide a notification for the status bar, which is placed under the Ongoing heading. This means that the notification cannot be dismissed unless the service is either stopped or removed from the foreground.

Since you mentioned that you have the action detected I won't enter that part of your code. So you need to create a subclass of Service as you did and use the startService method to get it's onCreate called. One thing you need to notice is that the onCreate method of service is called once you call startService on that service for the first time, no matter how many times you call startService again the onCreate method won't get called and only the onStartCommand get called. We use that fact alongside that you could provide a string action within your intent to properly register and unregister your listener.

In MainActivity.java:

Stringaction="start";  // Or to unregister listener "stop"!finalIntentintent=newIntent(this, MyService.class);
intent.setAction(action);
startService(intent);

and then in MyService.java:

@OverridepublicvoidonCreate() {
    super.onCreate();
    // Do initialization or whatever here (executed once per service lifecycle)
}

@OverridepublicintonStartCommand(Intent intent, int flags, int startId) {
    if (intent.getAction().equals("start")) {
        // Register your listener or whatever
        showForegroundNotification();
    }
    if (intent.getAction().equals("stop")) {
        // Unregister your listener or whatever
        stopForeground(true);
        stopSelf();
    }

    return START_STICKY;
}

privatevoidshowForegroundNotification() {
    IntentmyServiceNotificationIntent=newIntent(this, MainActivity.class);
    myServiceNotificationIntent.setFlags(
            Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntentpendingIntent= PendingIntent
            .getActivity(this, MY_SERVICE_REQUEST_CODE,
                    myServiceNotificationIntent, MY_SERVICE_FLAG);

    Notificationnotification=newNotificationCompat.Builder(this)
            .setContentTitle(MY_SERVICE_NOTIFICATION_CONTENT_TITLE)
            .setTicker(MY_SERVICE_NOTIFICATION_TICKER)
            .setContentText(MY_SERVICE_NOTIFICATION_CONTENT_TEXT)
            .setSmallIcon(R.drawable.ic_whatever)
            .setContentIntent(pendingIntent)
            .setOngoing(true)
            .build();
    startForeground(MY_SERVICE_NOTIFICATION_ID, notification);
}

Finally don't forget to unregister your listener in onDestroy in case of android kill your service (which is very rare):

@OverridepublicvoidonDestroy() {
    super.onDestroy();
    // Unregister your listener
}

Solution 2:

You can register SensorManager inside service in OnStartCommand.Also try using startForeground as android os will kill your service when app is killed

Post a Comment for "Create Service To Detect Any Action From The User"