Как я могу преобразовать IntentService в фоновый сервис, который должен работать даже после того, как приложение убит - PullRequest
0 голосов
/ 12 сентября 2018

Я работаю над DetectedActivity, и в настоящее время я получаю успешные результаты по этому вопросу. Теперь я хочу получить обнаруженную активность пользователя (в журнале или тосте), пока мое приложение убито. Я прочитал документ Google для ActivityRecognization API, который использует "IntentService" и "PendingIntent". Поэтому я не знаю, как получить значение «Доверие» для обнаруженной активности в тосте, даже если мое приложение убито. Может кто-нибудь, пожалуйста, помогите мне? Мой код, как показано ниже.

ActivityIntentService

public class ActivityIntentService extends IntentService {
    protected static final String TAG = "Activity";
    static int confidence;
    static int activityType;
    static String test;
    //Call the super IntentService constructor with the name for the worker thread//
    public ActivityIntentService() {
        super(TAG);
    }
    @Override
    public void onCreate() {
        super.onCreate();
    }
//Define an onHandleIntent() method, which will be called whenever an activity detection update is available//

    @Override
    protected void onHandleIntent(Intent intent) {
//Check whether the Intent contains activity recognition data//
        if (ActivityRecognitionResult.hasResult(intent)) {

//If data is available, then extract the ActivityRecognitionResult from the Intent//
            ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);

//Get an array of DetectedActivity objects//
            ArrayList<DetectedActivity> detectedActivities = (ArrayList) result.getProbableActivities();
            PreferenceManager.getDefaultSharedPreferences(this)
                    .edit()
                    .putString(MainActivity.DETECTED_ACTIVITY,
                            detectedActivitiesToJson(detectedActivities))
                    .apply();


            DetectedActivity mostProbableActivity;
            mostProbableActivity = result.getMostProbableActivity();

            confidence = mostProbableActivity.getConfidence();
            activityType = mostProbableActivity.getType();
            Toast.makeText(this,"DETECTION IS RUNNING",Toast.LENGTH_LONG).show();

            if (mostProbableActivity.equals("STILL") &&confidence > 80)
            {

                Toast.makeText(this,"STILL",Toast.LENGTH_LONG).show();

            }

        }
    }
//Convert the code for the detected activity type, into the corresponding string//

    @SuppressLint("StringFormatInvalid")
    static String getActivityString(Context context, int detectedActivityType) {
        Resources resources = context.getResources();
        switch(detectedActivityType) {
            case DetectedActivity.ON_BICYCLE:
                return resources.getString(R.string.bicycle);
            case DetectedActivity.ON_FOOT:
                return resources.getString(R.string.foot);
            case DetectedActivity.RUNNING:
                return resources.getString(R.string.running);
            case DetectedActivity.STILL:
                return resources.getString(R.string.still);
            case DetectedActivity.TILTING:
                return resources.getString(R.string.tilting);
            case DetectedActivity.WALKING:
                return resources.getString(R.string.walking);
            case DetectedActivity.IN_VEHICLE:
                return resources.getString(R.string.vehicle);
            default:
                return resources.getString(R.string.unknown_activity, detectedActivityType);
        }
    }
    static final int[] POSSIBLE_ACTIVITIES = {

            DetectedActivity.STILL,
            DetectedActivity.ON_FOOT,
            DetectedActivity.WALKING,
            DetectedActivity.RUNNING,
            DetectedActivity.IN_VEHICLE,
            DetectedActivity.ON_BICYCLE,
            DetectedActivity.TILTING,
            DetectedActivity.UNKNOWN
    };
    static String detectedActivitiesToJson(ArrayList<DetectedActivity> detectedActivitiesList) {
        Type type = new TypeToken<ArrayList<DetectedActivity>>() {}.getType();
        return new Gson().toJson(detectedActivitiesList, type);
    }

    static ArrayList<DetectedActivity> detectedActivitiesFromJson(String jsonArray) {
        Type listType = new TypeToken<ArrayList<DetectedActivity>>(){}.getType();
        ArrayList<DetectedActivity> detectedActivities = new Gson().fromJson(jsonArray, listType);
        if (detectedActivities == null) {
            detectedActivities = new ArrayList<>();
        }
        return detectedActivities;
    }
}

Я использую это service в своем классе активности, как показано ниже:

 Intent intent = new Intent(this, ActivityIntentService.class);
    startService(intent);
    return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

Пожалуйста, кто-нибудь, помогите мне в этом. Заранее спасибо

...