首页 > 解决方案 > 如何触发 Android 操作系统杀死我的后台服务以进行测试?

问题描述

我们知道,如果系统需要更多资源,Android OS 会选择一些活动或服务来杀死。我想运行一个测试,看看我的服务是否会成为被杀死的候选人。如何创建触发事件的情境?

标签: androidperformance

解决方案


method 1

command kill -9 pid

This is actually a shell command. We know that the bottom layer of Android is Linux. Therefore, all Linux terminal commands can be used on Android. Paste a piece of code to show how do you incorporate it into the code.

private void killProcess(String pid) {
    Process sh = null;
    DataOutputStream os = null;
    try {
        sh = Runtime.getRuntime().exec("su");
        os = new DataOutputStream(sh.getOutputStream());
        final String Command = "kill -9 " + pid + "\n";
        os.writeBytes(Command);
        os.flush();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        sh.waitFor();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

The most important function of this method is to tell you how to execute Linux shell commands in an Android program.

method 2

Kill the background service without automatic startup:

am (Activity Manager) command

The am command is a command in the /system/bin/ directory of the Android system. You can not only start an application on the terminal, but also start a service, send broadcast, intent action, and force stop process. We're going to use a function that is to force the application to stop.

For the description and usage of the am command, see the Android official website at http://developer.android.com/tools/help/adb.html#am.

The following is an example of code: am force-stop <PACKAGE>

private void forceStopAPK(String pkgName){
    Process sh = null;
    DataOutputStream os = null;
    try {
        sh = Runtime.getRuntime().exec("su");
        os = new DataOutputStream(sh.getOutputStream());
        final String Command = "am force-stop "+pkgName+ "\n";
        os.writeBytes(Command);
        os.flush();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        sh.waitFor();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

In the preceding code, we call the forceStopAPK method to pass the package name of an application. Then we can kill the corresponding Android application without starting it automatically.


推荐阅读