后台任务中的Android用户活动识别

时间:2018-11-23 15:15:54

标签: android activity-recognition

我的目标是听取用户的活动,并在更改后在后台执行一些操作,例如将事件记录到数据库中。当应用程序处于前台时,事件将正确触发。当应用关闭时(但我的服务正在运行),则不会触发任何事件。我如何获得这些事件?

一般后台服务:

public class AppService extends Service {

    ActivitySensor activitySensor;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
       activitySensor = new ActivitySensor(getApplicationContext());
       activitySensor.start();
        return START_STICKY;
    }

@Override
    public void onDestroy() {
        Log.d("Service", "onDestroy");
        activitySensor.stop();
        super.onDestroy();
    }

ActivitySensor:

public class ActivitySensor {

    private static final long DETECTION_INTERVAL_IN_MILLISECONDS = 3000;

    private  ActivityRecognitionClient mActivityRecognitionClient;
    private Intent mIntentService;
    private PendingIntent mPendingIntent;
    private Context context;

    public ActivitySensor(Context _context){
        this.context = _context;
        mIntentService = new Intent(context, DetectedActivitiesIntentService.class);
        mPendingIntent = PendingIntent.getService(context, 1, mIntentService, PendingIntent.FLAG_UPDATE_CURRENT);
        mActivityRecognitionClient = new ActivityRecognitionClient(context);

    }
    public void start(){
        Task<Void> task = mActivityRecognitionClient.requestActivityUpdates(
                DETECTION_INTERVAL_IN_MILLISECONDS,
                mPendingIntent);

        task.addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void result) {
                Toast.makeText(context,
                        "Successfully requested activity updates",
                        Toast.LENGTH_SHORT)
                        .show();
            }
        });

        task.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(context,
                        "Requesting activity updates failed to start",
                        Toast.LENGTH_SHORT)
                        .show();
            }
        });
    }

     public void stop() {
        Task<Void> task = mActivityRecognitionClient.removeActivityUpdates(
                mPendingIntent);
        task.addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void result) {
                Toast.makeText(context,
                        "Removed activity updates successfully!",
                        Toast.LENGTH_SHORT)
                        .show();
            }
        });

        task.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(context, "Failed to remove activity updates!",
                        Toast.LENGTH_SHORT).show();
            }
        });
    }
}

DetectedActivitiesIntentService:

public class DetectedActivitiesIntentService  extends IntentService {

    protected static final String TAG = DetectedActivitiesIntentService.class.getSimpleName();

    String[] valueNames = {"activity", "confidence"} ;
    AppDatabase db;

    public DetectedActivitiesIntentService() {
        // Use the TAG to name the worker thread.
        super(TAG);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        this.db = ((BaseApp)getApplication()).getDatabase();
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        //never fired
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {

                @Override
                public void run() {
                    Toast.makeText(DetectedActivitiesIntentService.this.getApplicationContext(), "Activity detected: "+ actS + " "+ values[1], Toast.LENGTH_SHORT).show();
                }


        });
    }
    }

1 个答案:

答案 0 :(得分:0)

由于后台执行限制,

标准后台服务在Android Oreo中不再受支持。您可以在这里了解更多信息:android docs

我建议您看看可以代替标准服务使用的JobintentService,它可能适合您使用显式广播接收器来调用JobIntentService。