简体   繁体   English

活动转换 API 调用意图

[英]Activity Transition API Calling Intent

ActivityTransitionUpdate returns null, always. ActivityTransitionUpdate 总是返回 null。 But if I change it to requestactivityupdate it works fine.但是,如果我将其更改为 requestactivityupdate 它工作正常。 But I need the transition API.但我需要过渡 API。 I do not understand why this is not working, especially since a couple of days ago it was working right.我不明白为什么这不起作用,特别是几天前它工作正常。

I have tried rewriting the code, looked everywhere on the web, copied code from other projects that apparently work, but the requestActivityTransitionUpdates does not want to work anymore.我已经尝试重写代码,在 web 上到处查看,从其他明显有效的项目中复制代码,但 requestActivityTransitionUpdates 不想再工作了。 I have also uninstalled and reinstalled android studio, but nothing is working.我还卸载并重新安装了 android studio,但没有任何效果。

Main Activity ''''主要活动 ''''

private List<ActivityTransition> transitions;

    private ActivityRecognitionClient activityRecognitionClient;

    private PendingIntent transitionPendingIntent;
    private Context mContext;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

       System.out.println(getExternalCacheDir());
        Log.i(TAG, "ON");

        mContext = this;
        activityRecognitionClient = ActivityRecognition.getClient(mContext);

        Intent intent = new Intent(mContext, TransitionIntentService.class);

        transitionPendingIntent = PendingIntent.getService(this, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);


    }


    public void registerHandler(View view) {

        transitions = new ArrayList<>();


        transitions.add(new ActivityTransition.Builder()
                .setActivityType(DetectedActivity.WALKING)
                .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                .build());


        transitions.add(new ActivityTransition.Builder()
                .setActivityType(DetectedActivity.WALKING)
                .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                .build());


        transitions.add(new ActivityTransition.Builder()
                .setActivityType(DetectedActivity.STILL)
                .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                .build());

        transitions.add(new ActivityTransition.Builder()
                .setActivityType(DetectedActivity.STILL)
                .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                .build());

        transitions.add(new ActivityTransition.Builder()
                .setActivityType(DetectedActivity.RUNNING)
                .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                .build());


        transitions.add(new ActivityTransition.Builder()
                .setActivityType(DetectedActivity.RUNNING)
                .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                .build());


        transitions.add(new ActivityTransition.Builder()
                .setActivityType(DetectedActivity.IN_VEHICLE)
                .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
                .build());

        transitions.add(new ActivityTransition.Builder()
                .setActivityType(DetectedActivity.IN_VEHICLE)
                .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
                .build());

        ActivityTransitionRequest activityTransitionRequest
                = new ActivityTransitionRequest(transitions);



        Task<Void> task;
        task = activityRecognitionClient.requestActivityTransitionUpdates(activityTransitionRequest, transitionPendingIntent);


        task.addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Toast.makeText(mContext, "Transition update set up", Toast.LENGTH_LONG).show();
            }
        });

        task.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(mContext, "Transition update Failed to set up", Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
        });
        //startService(intent);
    }


    public void deregisterHandler(View view) {
        Task<Void> task = activityRecognitionClient.removeActivityTransitionUpdates(transitionPendingIntent);
        task.addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                transitionPendingIntent.cancel();
                Toast.makeText(mContext, "Remove Activity Transition Successfully", Toast.LENGTH_LONG).show();
            }
        });

        task.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(mContext, "Remove Activity Transition Failed", Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
        });
    }

'''' ''''

IntentService意向服务

'''' ''''

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

    private int activityBang;
    private int transitionBang;


    @Override
    public void onHandleIntent(Intent intent) {

        Log.i(TAG, "onHandleIntent: GO");
        if (intent != null) {
            if (ActivityTransitionResult.hasResult(intent)) {
                ActivityTransitionResult result = ActivityTransitionResult.extractResult(intent);
                for (ActivityTransitionEvent event : result.getTransitionEvents()) {

                    Toast.makeText(this, event.getTransitionType() + "-" + event.getActivityType(), Toast.LENGTH_LONG).show();
                    //7 for walking and 8 for running
                    Log.i(TAG, "Activity Type " + event.getActivityType());
                    activityBang = event.getActivityType();

                    // 0 for enter, 1 for exit
                    Log.i(TAG, "Transition Type " + event.getTransitionType());
                    transitionBang = event.getTransitionType();

                    try {
                        ActivityWriter();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        else {
            Log.d(TAG, "onHandleIntent: Banana");
        }
    }



    private void ActivityWriter() throws IOException {

        String baseDir = getExternalCacheDir().toString();
        String fileName = "SentinelData.csv";
        String filePath = baseDir + File.separator + fileName;
        File f = new File(filePath);
        CSVWriter writer;


       SimpleDateFormat date1 = new SimpleDateFormat("yyyy.MM.dd G");
       SimpleDateFormat time1 = new SimpleDateFormat("HH:mm:ss z");

        String date = date1.format(new Date());
        String time = time1.format(new Date());

        if(f.exists()&&!f.isDirectory())
        {
            FileWriter mFileWriter = new FileWriter(filePath, true);
            writer = new CSVWriter(mFileWriter);
        }
        else
        {
            writer = new CSVWriter(new FileWriter(filePath));
        }

        String[] data = {date, time, String.valueOf(activityBang), String.valueOf(transitionBang)};

        writer.writeNext(data);

        writer.close();
    }

'''' ''''

My Manifest ''''我的清单''''

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.a200000"
    tools:ignore="GoogleAppIndexingWarning">

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

    <application
        android:allowBackup="true"
        android:fullBackupContent="@xml/backup_descriptor"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".TransitionIntentService"
            android:exported="false" />
    </application>

</manifest>

'''' ''''

My Gradle我的 Gradle

    apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.a200000"
        minSdkVersion 22
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation 'com.google.android.gms:play-services-location:17.0.0'
    implementation 'com.google.code.gson:gson:2.8.5'
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'com.opencsv:opencsv:4.0'
}

I expect to and was receiving transition updates when the app was open that were being stored in a csv file in the apps cache.当应用程序打开时,我希望并且正在接收转换更新,这些更新存储在应用程序缓存中的 csv 文件中。 Now my OnHandleIntent is not even being run from the task as it should be.现在我的 OnHandleIntent 甚至没有从任务中运行,因为它应该是。

Not sure about it, but maybe helpful:不确定,但可能有帮助:

transitionPendingIntent = PendingIntent.getService(this, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Task task = activityRecognitionClient.requestActivityUpdates(1000, transitionPendingIntent);

It happened to me the same thing before.It seems that last activity transition event kept in catch.我以前也发生过同样的事情。似乎最后一个活动转换事件被捕获了。 Sometimes, you get an old event results from device's catch.有时,您会从设备的捕获中获得旧事件结果。 So, to avoid all that problem, check the elapsed time of when the transition occurred, and ignore the callback if the transition happened over 30 seconds ago.因此,为了避免所有这些问题,请检查转换发生的经过时间,如果转换发生在 30 秒前,则忽略回调。

if (intent != null) {
        if (ActivityTransitionResult.hasResult(intent)) {
            ActivityTransitionResult result = ActivityTransitionResult.extractResult(intent);
            for (ActivityTransitionEvent event : result.getTransitionEvents()) {

                //if event occurred less than 30 seconds, get the event. Sometimes app gets old events from device's catch
                //that is why you have to make sure that the event is not that old.
                if(((SystemClock.elapsedRealtime()-(event.getElapsedRealTimeNanos()/1000000))/1000) <= 30) {
                   //Do your staff here......
                   ............................
                   ............................
                   ...............................
                }

            }
        }
    }
    else {
        Log.d(TAG, "onHandleIntent: Banana");
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM