Явные намерения не работают на Android 8.1 - PullRequest
0 голосов
/ 23 мая 2018

Приведенный ниже код работает без каких-либо проблем в версиях, предшествующих Oreo.

Хотя я использую метод startForeground и намерен explicit намереваться получить значения Activity, метод onHandleIntent никогда не вызывается.

Я не могу найти ни одной проблемы или решения по этой проблеме.

Есть ли шанс преодолеть эту проблему?

Примечание. Я пытаюсь установить на своем телефоне установленное ПЗУ ине может симулировать на эмуляторе Android это обстоятельство.

AndroidManifest.xml файл

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.myservice"
    android:versionCode="1"
    android:versionName="1.0">

    <application ... >

      <service android:name="com.MyService">
        <intent-filter>
          <action android:name="com.MyService"/>
        </intent-filter>
      </service>

      <uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION" />

      <service android:name="com.myservice.ActivityHelper$ActivityRecognitionService" />

    </application>

</manifest>

MyService.java файл

public class MyService extends Service {

    ...

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);

        runServiceAtForeground();

        return START_STICKY;
    }


    private void runServiceAtForeground () {
        ...

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            ...
            mNotificationManager.createNotificationChannel(channel);
        }

        Intent i = new Intent(getApplicationContext(), MyService.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
        NotificationCompat.Builder notif = new NotificationCompat.Builder(this, channel_id);
        notif.setContentIntent(pi);

        // MAKING FOREGROUND SERVICE
        startForeground(notif_id, notif.build());

        // STARTING ACTIVITY RECOGNITION
        mActivityHelper.startObserving();

    }

    ...

}

ActivityHelper.java файл

public class ActivityHelper {

    ...

    public void startObserving() {
        ActivityRecognitionClient arc = ActivityRecognition.getClient(context);

        Task<Void> task = arc.requestActivityUpdates(20000, getActivityDetectionPendingIntent());

        task.addOnSuccessListener(new OnSuccessListener<Void>() {...});

        task.addOnFailureListener(new OnFailureListener() {...});
    }

    private PendingIntent getActivityDetectionPendingIntent() {
            Intent i = new Intent(mContext, ActivityRecognitionService.class);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                return PendingIntent.getBroadcast(mContext, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
            } else {
                return PendingIntent.getService(mContext, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
            }
    }


    public static class ActivityRecognitionService extends IntentService {

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

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

        @Override
        protected void onHandleIntent(Intent intent) {

            // THIS METHOD IS NEVER RUN ON OREO

            if (ActivityRecognitionResult.hasResult(intent)) {
                ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);

                if (listener != null) {
                    Log.v(TAG, result.getMostProbableActivity().getType());
                }

                stopSelf();
            }
        }

    }

}

1 Ответ

0 голосов
/ 23 мая 2018
private PendingIntent getActivityDetectionPendingIntent() {
        Intent i = new Intent(mContext, ActivityRecognitionService.class);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return PendingIntent.getBroadcast(mContext, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
        } else {
            return PendingIntent.getService(mContext, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
        }
}

Либо ActivityRecognitionService является BroadcastReceiver , либо это Service.Это не может быть и то и другое одновременно.Это не меняется в зависимости от версии ОС, на которой работает устройство.И поскольку ActivityRecognitionService extends IntentService, PendingIntent.getBroadcast() не даст вам полезного PendingIntent.

Также:

  • MyService не используется, поскольку это не так.в вашем фрагменте манифеста, и на него не ссылаются другие фрагменты кода

  • Метод runServiceAtForeground() в MyService создает действие PendingIntent, указывающее на MyService, но MyService это не деятельность, и поэтому она не будет работать

...