android - 如何触发 Android 操作系统杀死我的后台服务以进行测试?
问题描述
我们知道,如果系统需要更多资源,Android OS 会选择一些活动或服务来杀死。我想运行一个测试,看看我的服务是否会成为被杀死的候选人。如何创建触发事件的情境?
解决方案
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.
推荐阅读
- c# - Identity Server 4 WindowsCryptographicException:密钥集不存在
- c - 在c中使用bmp文件截屏?
- typescript - 具有 T[K] 约束的通用排序函数
- xml - Teiid Springboot 启动文件数据源
- c++ - 通过别名返回变量而不在函数分配后动态分配或删除
- ibm-cloud - 带有德语变音符号 (ä-ö-ü) 的 IBM Watson Text-to-Speech 问题
- javascript - 在 Express Application Generator 上开发时,除索引路由外的所有路由都显示错误 404
- vue.js - 用函数中的数据填充 vuetify 组合框
- apache-kafka - 如何使用在 docker 上运行的 debezium 和 confluent-sink-connector 将所有更改从源数据库复制到目标数据库
- ssl - NGINX ssl_client_certificate:“失败:无法验证第一个证书”