2

I am using IntentService before to make my ActivityRecognition work in the background for location updates but since Android 9+ IntentService deprecated and it's no longer working in recent Android versions. So I tried to use WorkManager but I am a bit confused about how I can migrate from IntentService to WorkManager because WorkManager doesn't have any return method like service.

Start Of IntentService Like this (ActivityRecognition)

Intent ActivityRec_intent = new Intent(this, Activity_Recognized_Service.class);
            PendingIntent pendingIntent = PendingIntent.getService(this, 0, ActivityRec_intent, PendingIntent.FLAG_UPDATE_CURRENT);
            activityRecognitionClient.requestActivityUpdates(timeInLong,pendingIntent);

IntentService

public class Activity_Recognized_Service extends IntentService  {
    /**
     * Creates an IntentService.  Invoked by your subcl ass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public static final String TAG = "###RECOGNISED SRVCE###";
    Timer timer;
    LocationRequest mLocationRequest;
    static int detectedActivity;


    public Activity_Recognized_Service() {
        super("Activity_Recognized_Service");
    }

    public Activity_Recognized_Service(String name) {
        super(name);
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        Log.d(TAG, "On Handle Intent");
        if (ActivityRecognitionResult.hasResult(intent)) {
            Log.d(TAG, "ActivityRecognition Has Result");
            ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
            Log.d(TAG,"BackGround Service Starting");
            handleDetectedActivities(result.getProbableActivities(),this);

        }
    }
    private void handleDetectedActivities(List<DetectedActivity> probableActivities, Context mContext) {
        Intent notificationIntent=new Intent("Notification");

        for (DetectedActivity activity : probableActivities) {
            switch (activity.getType()) {
                case DetectedActivity.IN_VEHICLE:
                    Log.d(TAG, "In Vehicle " + activity.getConfidence());
                    Log.d(TAG, "In Vehicle " + detectedActivity);
                    Log.d(TAG,"Location Resquest Value "+mLocationRequest);
                    if (activity.getConfidence() >= 75 && activity.getType()!=detectedActivity) {
                        NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);
                        builder.setContentText("In Vehicle");
                        builder.setSmallIcon(R.drawable.demo_x);
                        builder.setContentTitle("demo");
                        NotificationManagerCompat.from(mContext).notify(0, builder.build());
                         // 10 min   5 hours= hours * 60 min*60 sec* 1000 milliseconds
                        setTimer(10);
                        detectedActivity=activity.getType();
                        //userSate = "In Vehicle ";


                    }
                    break;
                case DetectedActivity.ON_BICYCLE:
                    Log.d(TAG, "On Bicycle " + activity.getConfidence());
                    Log.d(TAG, "On Bicycle " + detectedActivity);
                    Log.d(TAG,"Location Resquest Value "+mLocationRequest);
                    if (activity.getConfidence() >= 75 && activity.getType()!=detectedActivity) {

                        NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);
                        builder.setContentText("On Bicycle");
                        builder.setSmallIcon(R.drawable.demo_x);
                        builder.setContentTitle("demo");
                        // builder.setVibrate(new long[] {1000,1000,1000,1000,1000,1000} );
                        NotificationManagerCompat.from(mContext).notify(0, builder.build());
                        /*notificationIntent.putExtra("Activity","On Bicycle");
                        LocalBroadcastManager.getInstance(mContext).sendBroadcast(notificationIntent);*/
                         //7 min 5 hours= hours * 60 min*60 sec* 1000 milliseconds
                        setTimer(5);
                        //requestLocatonSetting(6*60*1000,6*60*1000,LocationRequest.PRIORITY_HIGH_ACCURACY); //TEST
                        detectedActivity=activity.getType();
                        //userSate = "On Bicycle ";

                    }
                    break;
                case DetectedActivity.ON_FOOT:
                    Log.d(TAG, "On Foot " + activity.getConfidence());
                    Log.d(TAG, "On Foot " + detectedActivity);
                    Log.d(TAG,"Location Resquest Value "+mLocationRequest);
                    if (activity.getConfidence() >= 75 && activity.getType()!=detectedActivity) {
                        //Send Notification To User
                        NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);
                        builder.setContentText("On Foot");
                        builder.setSmallIcon(R.drawable.demo_x);
                        builder.setContentTitle("demo");
                        // builder.setVibrate(new long[] {1000,1000,1000,1000,1000,1000} );
                        //builder.setLights(Color.WHITE,3000,3000);
                        NotificationManagerCompat.from(mContext).notify(0, builder.build());
                        /*notificationIntent.putExtra("Activity","On Foot");
                        LocalBroadcastManager.getInstance(mContext).sendBroadcast(notificationIntent);*/
                        Log.d(TAG,"Enter On Foot "+"DetectedActivity "+" "+detectedActivity);
                        //userSate = "On Foot";

                    }
                    break;
                case DetectedActivity.RUNNING:
                    Log.d(TAG, "On Running " + activity.getConfidence());
                    Log.d(TAG, "On Running " + detectedActivity);
                    Log.d(TAG,"Location Resquest Value "+mLocationRequest);
                    if (activity.getConfidence() >= 75 && activity.getType()!=detectedActivity ) {
                        //Send Notification To User
                        Log.d(TAG,"Enter In Running "+"DetectedActivity "+" "+detectedActivity);
                        NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);
                        builder.setContentText("Running");
                        builder.setSmallIcon(R.drawable.demo_x);
                        builder.setContentTitle("demo");
                        // builder.setVibrate(new long[] {1000,1000,1000,1000,1000,1000} );
                        NotificationManagerCompat.from(mContext).notify(0, builder.build());
                        /*notificationIntent.putExtra("Activity","Running");
                        LocalBroadcastManager.getInstance(mContext).sendBroadcast(notificationIntent);*/
                        setTimer(2);
                        //3 min 5 hours= hours * 60 min*60 sec* 1000 milliseconds
                        //requestLocatonSetting(6*60*1000,6*60*1000,LocationRequest.PRIORITY_HIGH_ACCURACY); //TEST
                        detectedActivity=activity.getType();
                        // userSate = "Running ";

                    }
                    break;
                case DetectedActivity.STILL:
                    Log.d(TAG, "On Still " + activity.getConfidence());
                    Log.d(TAG, "On Still " + detectedActivity);
                    Log.d(TAG,"Location Resquest Value "+mLocationRequest);
                    if (activity.getConfidence() >= 75 && activity.getType()!=detectedActivity) {
                        //Send Notification To User
                        Log.d(TAG,"Enter In Still "+"DetectedActivity "+" "+detectedActivity);

                        NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);
                        builder.setContentText("Still");
                        builder.setSmallIcon(R.drawable.demo_x);
                        builder.setContentTitle("demo");
                        // builder.setVibrate(new long[] {1000,1000,1000,1000,1000,1000} );
                        NotificationManagerCompat.from(mContext).notify(0, builder.build());
                        // NOTIFICATION BY LOCAL BROADCAST MANAGER
                        setTimer(60*5);
                        /*notificationIntent.putExtra("Activity","Still");
                        LocalBroadcastManager.getInstance(mContext).sendBroadcast(notificationIntent);*/
                         //5 hrs 5 hours= hours * 60 min*60 sec* 1000 milliseconds
                        // requestLocatonSetting(3*60*1000,2*60*1000,LocationRequest.PRIORITY_HIGH_ACCURACY); //TEST
                        detectedActivity=activity.getType();
                        //userSate = "Still ";
                        App_Functions.writeToFile(App_Functions.MyCurrentTime_Date()+" == "+detectedActivity +" CASE Detection "+System.getProperty ("line.separator"),"Tracking","UserMove.txt",MyApplication.getmContext());

                    }
                    break;
                case DetectedActivity.TILTING:
                    Log.d(TAG, "On Tilting " + activity.getConfidence());
                    Log.d(TAG, "On Tilting " + detectedActivity);
                    Log.d(TAG,"Location Resquest Value "+mLocationRequest);
                    if (activity.getConfidence() >= 95 && activity.getType()!=detectedActivity) {
                        //Send Notification To User
                        Log.d(TAG,"Enter In Tilting "+"DetectedActivity "+" "+detectedActivity);
                        NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);
                        builder.setContentText("Tilting");
                        builder.setSmallIcon(R.drawable.demo_x);
                        builder.setContentTitle("demo");
                        // builder.setVibrate(new long[] {1000,1000,1000,1000,1000,1000} );
                        NotificationManagerCompat.from(mContext).notify(0, builder.build());
                        /*notificationIntent.putExtra("Activity","Tilting");
                        LocalBroadcastManager.getInstance(mContext).sendBroadcast(notificationIntent);*/
                        //5 hours= hours * 60 min*60 sec* 1000 milliseconds
                        //requestLocatonSetting(3*60*60*1000,2*60*60*1000,LocationRequest.PRIORITY_HIGH_ACCURACY); //TEST
                        detectedActivity=activity.getType();
                        // userSate = "Tilting  ";
                    }
                    break;
                case DetectedActivity.WALKING:
                    Log.d(TAG, "On Walking " + activity.getConfidence());
                    Log.d(TAG, "On Walking " + detectedActivity);
                    Log.d(TAG,"Location Resquest Value "+mLocationRequest);
                    if (activity.getConfidence() >= 75 && activity.getType()!=detectedActivity) {
                        //Send Notification To User
                        Log.d(TAG,"Enter In Walking "+"DetectedActivity "+" "+detectedActivity);
                        NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);
                        builder.setContentText("Let's Walk");
                        builder.setSmallIcon(R.drawable.demo_x);
                        builder.setContentTitle("demo");
                        // builder.setVibrate(new long[] {1000,1000,1000,1000,1000,1000} );
                        NotificationManagerCompat.from(mContext).notify(0, builder.build());
                        /*notificationIntent.putExtra("Activity","Let's Walk");
                        LocalBroadcastManager.getInstance(mContext).sendBroadcast(notificationIntent);*/
                         //3 min 5 hours= hours * 60 min*60 sec* 1000 milliseconds
                        setTimer(2);
                        detectedActivity=activity.getType();
                        // userSate = "Let's Walk   ";

                    }
                    break;
                case DetectedActivity.UNKNOWN:
                    Log.d(TAG, "UnKnown " + activity.getConfidence());
                    break;
            }

        }
    }
    public void setTimer(int Minutes) {
        Log.d(TAG, "==================================================");
        Log.d(TAG, "Set Timer Starts It will Run Every " + Minutes);
        int MilliSeconds = 60000 * Minutes;
        final Handler handler = new Handler(Looper.getMainLooper());
        timer = new Timer();

        TimerTask doAsynchronousTask = new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    public void run() {
                        try {
                            //CODE THAT YOU WANT TO EXECUTE AT GIVEN INTERVAL
                            Log.d(TAG, "AsyncTask Start Here For Location Update");
                           // App_Functions.writeToFile(App_Functions.MyCurrentTime_Date()+" == "+detectedActivity +" ************* "+System.getProperty ("line.separator"),"Tracking","UserMove.txt",MyApplication.getmContext());
                            new GetLocation(Activity_Recognized_Service.this,2);
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                        }
                    }
                });
            }
        };
        timer.schedule(doAsynchronousTask, 0, MilliSeconds);
        Log.d(TAG, "==================================================");
    }

}

How can i make my code work for background task and make it run even when app is closed.

Ritu
  • 518
  • 2
  • 12
  • 35
  • you can make a work manager run your activity recognization in a fixed interval by defining some constraints. Since ActivityRecognition is deprecated you can use ActivityRecognitionClient for recognization – Deepak Dec 09 '21 at 14:11
  • @Deepak i need to run in background service which can regularly detect user activity even when app is not visible to user. Any Idea? – Ritu Dec 09 '21 at 21:19
  • yes you can do using work manager schedule task where you can define time interval for starting the task – Deepak Dec 15 '21 at 08:05
  • @Deepak `WorkManager` minimum interval is 15 min. If OP needs to run less than 15 minutes then `WorkManager` is not the option – androidXP Oct 21 '22 at 09:40

0 Answers0