Android13 中调用IActivitymanager结束进程

13中测试ActivityManager killBackgroundProcesses无法kill掉进程,所以就换种方式使用IActivitymanager 中的forceStopPackage来结束进程

ActivityManager manager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
manager.killBackgroundProcesses("bubei.tingshu");

首先导入IActivitymanager


image.png
/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.app;

interface IActivityManager {
    void forceStopPackage(in String packageName, int userId);
}

第二步获取IActivityManager


import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.IActivityManager;
import android.content.Context;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;

...

@SuppressLint("NewApi")
    public static IActivityManager getActivityManager(Context context) {
        try {
            Class<?> activityManagerNativeClass = Class.forName("android.app.ActivityManagerNative");
            Method getDefaultMethod = activityManagerNativeClass.getMethod("getDefault");
            IActivityManager activityManagerNative = (IActivityManager)getDefaultMethod.invoke(null);
            return  activityManagerNative;
        } catch ( ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }

第三步使用

    /** @hide A user id to indicate all users on the device */
    @UnsupportedAppUsage
    @TestApi
    public static final @UserIdInt int USER_ALL = -1;

    /** @hide A user handle to indicate all users on the device */
    @SystemApi
    public static final @NonNull UserHandle ALL = new UserHandle(USER_ALL);

    /** @hide A user id to indicate the currently active user */
    @UnsupportedAppUsage
    public static final @UserIdInt int USER_CURRENT = -2;
try {
           SystemUtils.getActivityManager(this).forceStopPackage("bubei.tingshu", -2);
} catch (RemoteException e) {
            e.printStackTrace();
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。