Android 4.2+ 应用如何监听自己是否被卸载及卸载反馈功能的实现(第三版)

Android 4.2+ 应用如何监听自己是否被卸载及卸载反馈功能的实现(第三版)两个月前发了两篇有关监听自己是否被卸载和卸载反馈功能实现的博客,第二版的地址如下: http://www.cnblogs.com/zealotrouge/p/3159772.html ,感谢@whiletrue_童鞋发现了我的代码在4.2.2系统上无法实现卸载反馈,经过调试,有了问题的解决方案,但是由于发完博客后即处于闭关开发阶段,没时间打理博客,所以解决方案迟迟没有与大家见面,最近空闲下来,将解

两个月前发了两篇有关监听自己是否被卸载和卸载反馈功能实现的博客,第二版的地址如下: http://www.cnblogs.com/zealotrouge/p/3159772.html ,感谢@whiletrue_童鞋发现了我的代码在4.2.2系统上无法实现卸载反馈,经过调试,有了问题的解决方案,但是由于发完博客后即处于闭关开发阶段,没时间打理博客,所以解决方案迟迟没有与大家见面,最近空闲下来,将解决思路及方案发出来给大家看看还有没有问题。

调试发现,监听依然没有问题,毕竟是Linux Kernel中的接口,Framework层再怎么改也改不到那儿去,那么问题出在哪呢?阻塞结束后,通过调用exec函数发出am命令调起浏览器访问网页,在API16(Android 4.1.x)的设备上尚可正常访问网页,而API17(Android 4.2.x)的设备上连浏览器也不能调起。

通过分析log,发现了一条线索,如下面的log的所示:

W/ActivityManager( 387): Permission Denial: startActivity asks to run as user -2 but is calling from user 0; this requires android.permission.INTERACT_ACROSS_USERS_FULL

log中直接给出提示,需要加一个权限INTERACT_ACROSS_USERS_FULL,这个权限时API17新引入的,目的在于允许不同用户的应用之间可以产生交互。可是加上去之后发现,还不是无法调起浏览器,而且log依然提示需要权限INTERACT_ACROSS_USERS_FULL,很是奇怪,于是继续分析。

首先说明一下Linux中的pid和uid,以及android扩展的userSerialNumber。pid是Process的标识,用于系统对进程的控制,从API层面看就是用于Process.killProcess()和Process.sendSignal();uid在Linux系统中是用来标识用户的,而在android将uid视为app的标识id,用于”sandbox”安全模型,即用于app权限控制;而对于API17引入的多用户支持(目前只支持平板),uid已经被占用,只好新引入userSerialNumber来标识用户。

回到刚才的问题,log中告知startActivity时运行用户标识为-2,而调用却是由用户标识0发起,导致拒绝执行。用这句话搜索,发现在Google开发者网站中有相关的issue,链接如下: https://code.google.com/p/android/issues/detail?id=39801 (打不开可以把https改为http)。结合官方的回答,问题原因如下:由于被卸载,C端进程监听到目录被删除,立即执行am命令,此时将会默认以USER_CURRENT的身份执行,由于API17中ActivityManagerService.handleIncomingUser()会校验userSerialNumber,发现用户标识不匹配,导致权限校验失败——这也说明了权限的影响范围仅限于Java端的进程,对于fork()出来的C端进程来说,并不继承父进程在Android中声明的权限。

解决方案:增加处理分支,若API>=17,将userSerialNumber传递给C端进程,然后在am命令中带上参数–user userSerialNumber即可。

Java端代码如下:

package main.activity; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import pym.test.uninstalledobserver.R; import android.app.Activity; import android.os.Build; import android.os.Bundle; import android.util.Log; /** * @author pengyiming * @note 监听此应用是否被卸载,若被卸载则弹出卸载反馈 * @note 由于API17加入多用户支持,原有命令在4.2及更高版本上执行时缺少userSerial参数,特此修改 * */

public class UninstalledObserverActivity extends Activity { 
      /* 数据段begin */
    private static final String TAG = "UninstalledObserverActivity"; /* 数据段end */
    
    /* 函数段begin */
    private native void init(String userSerial); static { Log.d(TAG, "load libuninstalled_observer"); System.loadLibrary("uninstalled_observer"); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "onCreate"); setContentView(R.layout.uninstalled_observer_layout); // API level小于17,不需要获取userSerialNumber
        if (Build.VERSION.SDK_INT < 17) { Log.d(TAG, "no need get user serial"); init(null); } // 否则,需要获取userSerialNumber
        else { Log.d(TAG, "need get user serial"); String userSerial = getUserSerial(); Log.d(TAG, "userSerial = " + userSerial); init(getUserSerial()); } } // 由于targetSdkVersion低于17,只能通过反射获取
    private String getUserSerial() { Object userManager = getSystemService("user"); if (userManager == null) { Log.d(TAG, "no user manager"); return null; } try { Method myUserHandleMethod = android.os.Process.class.getMethod("myUserHandle", (Class<?>[]) null); Object myUserHandle = myUserHandleMethod.invoke(android.os.Process.class, (Object[]) null); Method getSerialNumberForUser = userManager.getClass().getMethod("getSerialNumberForUser", myUserHandle.getClass()); long userSerial = (Long) getSerialNumberForUser.invoke(userManager, myUserHandle); return String.valueOf(userSerial); } catch (NoSuchMethodException e) { Log.e(TAG, "", e); } catch (IllegalArgumentException e) { Log.e(TAG, "", e); } catch (IllegalAccessException e) { Log.e(TAG, "", e); } catch (InvocationTargetException e) { Log.e(TAG, "", e); } return null; } /* 函数段end */ }

核心——native方法头文件:

 1 /* 头文件begin */
 2 #include <jni.h>
 3 #include <stdlib.h>
 4 #include <stdio.h>
 5 #include <string.h>
 6 #include <android/log.h>
 7 #include <unistd.h>
 8 #include <sys/inotify.h>
 9 #include <fcntl.h>
10 /* 头文件end */
11 
12 /* 宏定义begin */
13 //清0宏
14 #define MEM_ZERO(pDest, destSize) memset(pDest, 0, destSize)
15 
16 //LOG宏定义
17 #define LOG_INFO(tag, msg) __android_log_write(ANDROID_LOG_INFO, tag, msg)
18 #define LOG_DEBUG(tag, msg) __android_log_write(ANDROID_LOG_DEBUG, tag, msg)
19 #define LOG_WARN(tag, msg) __android_log_write(ANDROID_LOG_WARN, tag, msg)
20 #define LOG_ERROR(tag, msg) __android_log_write(ANDROID_LOG_ERROR, tag, msg)
21 /* 宏定义end */
22 
23 #ifndef _Included_main_activity_UninstalledObserverActivity
24 #define _Included_main_activity_UninstalledObserverActivity
25 #ifdef __cplusplus
26 extern "C" {
27 #endif
28 
29 #undef main_activity_UninstalledObserverActivity_MODE_PRIVATE
30 #define main_activity_UninstalledObserverActivity_MODE_PRIVATE 0L
31 #undef main_activity_UninstalledObserverActivity_MODE_WORLD_READABLE
32 #define main_activity_UninstalledObserverActivity_MODE_WORLD_READABLE 1L
33 #undef main_activity_UninstalledObserverActivity_MODE_WORLD_WRITEABLE
34 #define main_activity_UninstalledObserverActivity_MODE_WORLD_WRITEABLE 2L
35 #undef main_activity_UninstalledObserverActivity_MODE_APPEND
36 #define main_activity_UninstalledObserverActivity_MODE_APPEND 32768L
37 #undef main_activity_UninstalledObserverActivity_MODE_MULTI_PROCESS
38 #define main_activity_UninstalledObserverActivity_MODE_MULTI_PROCESS 4L
39 #undef main_activity_UninstalledObserverActivity_BIND_AUTO_CREATE
40 #define main_activity_UninstalledObserverActivity_BIND_AUTO_CREATE 1L
41 #undef main_activity_UninstalledObserverActivity_BIND_DEBUG_UNBIND
42 #define main_activity_UninstalledObserverActivity_BIND_DEBUG_UNBIND 2L
43 #undef main_activity_UninstalledObserverActivity_BIND_NOT_FOREGROUND
44 #define main_activity_UninstalledObserverActivity_BIND_NOT_FOREGROUND 4L
45 #undef main_activity_UninstalledObserverActivity_BIND_ABOVE_CLIENT
46 #define main_activity_UninstalledObserverActivity_BIND_ABOVE_CLIENT 8L
47 #undef main_activity_UninstalledObserverActivity_BIND_ALLOW_OOM_MANAGEMENT
48 #define main_activity_UninstalledObserverActivity_BIND_ALLOW_OOM_MANAGEMENT 16L
49 #undef main_activity_UninstalledObserverActivity_BIND_WAIVE_PRIORITY
50 #define main_activity_UninstalledObserverActivity_BIND_WAIVE_PRIORITY 32L
51 #undef main_activity_UninstalledObserverActivity_BIND_IMPORTANT
52 #define main_activity_UninstalledObserverActivity_BIND_IMPORTANT 64L
53 #undef main_activity_UninstalledObserverActivity_BIND_ADJUST_WITH_ACTIVITY
54 #define main_activity_UninstalledObserverActivity_BIND_ADJUST_WITH_ACTIVITY 128L
55 #undef main_activity_UninstalledObserverActivity_CONTEXT_INCLUDE_CODE
56 #define main_activity_UninstalledObserverActivity_CONTEXT_INCLUDE_CODE 1L
57 #undef main_activity_UninstalledObserverActivity_CONTEXT_IGNORE_SECURITY
58 #define main_activity_UninstalledObserverActivity_CONTEXT_IGNORE_SECURITY 2L
59 #undef main_activity_UninstalledObserverActivity_CONTEXT_RESTRICTED
60 #define main_activity_UninstalledObserverActivity_CONTEXT_RESTRICTED 4L
61 #undef main_activity_UninstalledObserverActivity_RESULT_CANCELED
62 #define main_activity_UninstalledObserverActivity_RESULT_CANCELED 0L
63 #undef main_activity_UninstalledObserverActivity_RESULT_OK
64 #define main_activity_UninstalledObserverActivity_RESULT_OK -1L
65 #undef main_activity_UninstalledObserverActivity_RESULT_FIRST_USER
66 #define main_activity_UninstalledObserverActivity_RESULT_FIRST_USER 1L
67 #undef main_activity_UninstalledObserverActivity_DEFAULT_KEYS_DISABLE
68 #define main_activity_UninstalledObserverActivity_DEFAULT_KEYS_DISABLE 0L
69 #undef main_activity_UninstalledObserverActivity_DEFAULT_KEYS_DIALER
70 #define main_activity_UninstalledObserverActivity_DEFAULT_KEYS_DIALER 1L
71 #undef main_activity_UninstalledObserverActivity_DEFAULT_KEYS_SHORTCUT
72 #define main_activity_UninstalledObserverActivity_DEFAULT_KEYS_SHORTCUT 2L
73 #undef main_activity_UninstalledObserverActivity_DEFAULT_KEYS_SEARCH_LOCAL
74 #define main_activity_UninstalledObserverActivity_DEFAULT_KEYS_SEARCH_LOCAL 3L
75 #undef main_activity_UninstalledObserverActivity_DEFAULT_KEYS_SEARCH_GLOBAL
76 #define main_activity_UninstalledObserverActivity_DEFAULT_KEYS_SEARCH_GLOBAL 4L
77 
78 /*
79  * Class: main_activity_UninstalledObserverActivity 80  * Method: init 81  * Signature: (Ljava/lang/String;)V 82  */
83 JNIEXPORT void JNICALL Java_main_activity_UninstalledObserverActivity_init(JNIEnv *, jobject, jstring);
84 
85 #ifdef __cplusplus
86 }
87 #endif
88 #endif

核心——native方法实现:

  1 /* 头文件begin */
  2 #include "main_activity_UninstalledObserverActivity.h"
  3 /* 头文件end */
  4 
  5 #ifdef __cplusplus
  6 extern "C" {
  7 #endif
  8 
  9 /* 内全局变量begin */
 10 static char c_TAG[] = "UninstalledObserverActivity.init";
 11 static jboolean b_IS_COPY = JNI_TRUE;
 12 /* 内全局变量 */
 13 
 14 /*
 15  * Class: main_activity_UninstalledObserverActivity  16  * Method: init  17  * Signature: ()V  18  */
 19 JNIEXPORT void JNICALL Java_main_activity_UninstalledObserverActivity_init(JNIEnv *env, jobject obj, jstring userSerial)
 20 {
 21     jstring tag = (*env)->NewStringUTF(env, c_TAG);
 22 
 23     //初始化log
 24     LOG_DEBUG((*env)->GetStringUTFChars(env, tag, &b_IS_COPY)
 25             , (*env)->GetStringUTFChars(env, (*env)->NewStringUTF(env, "init OK"), &b_IS_COPY));
 26 
 27     //fork子进程,以执行轮询任务
 28     pid_t pid = fork();
 29     if (pid < 0)
 30     {
 31         //出错log
 32         LOG_ERROR((*env)->GetStringUTFChars(env, tag, &b_IS_COPY)
 33                 , (*env)->GetStringUTFChars(env, (*env)->NewStringUTF(env, "fork failed !!!"), &b_IS_COPY));
 34     }
 35     else if (pid == 0)
 36     {
 37         //子进程注册"/data/data/pym.test.uninstalledobserver"目录监听器
 38         int fileDescriptor = inotify_init();
 39         if (fileDescriptor < 0)
 40         {
 41             LOG_DEBUG((*env)->GetStringUTFChars(env, tag, &b_IS_COPY)
 42                     , (*env)->GetStringUTFChars(env, (*env)->NewStringUTF(env, "inotify_init failed !!!"), &b_IS_COPY));
 43 
 44              exit(1);
 45         }
 46 
 47         int watchDescriptor;
 48         watchDescriptor = inotify_add_watch(fileDescriptor, "/data/data/pym.test.uninstalledobserver", IN_DELETE);
 49         if (watchDescriptor < 0)
 50         {
 51             LOG_DEBUG((*env)->GetStringUTFChars(env, tag, &b_IS_COPY)
 52                     , (*env)->GetStringUTFChars(env, (*env)->NewStringUTF(env, "inotify_add_watch failed !!!"), &b_IS_COPY));
 53 
 54             exit(1);
 55         }
 56 
 57         //分配缓存,以便读取event,缓存大小=一个struct inotify_event的大小,这样一次处理一个event
 58         void *p_buf = malloc(sizeof(struct inotify_event));
 59         if (p_buf == NULL)
 60         {
 61             LOG_DEBUG((*env)->GetStringUTFChars(env, tag, &b_IS_COPY)
 62                     , (*env)->GetStringUTFChars(env, (*env)->NewStringUTF(env, "malloc failed !!!"), &b_IS_COPY));
 63 
 64             exit(1);
 65         }
 66         //开始监听
 67         LOG_DEBUG((*env)->GetStringUTFChars(env, tag, &b_IS_COPY)
 68                     , (*env)->GetStringUTFChars(env, (*env)->NewStringUTF(env, "start observer"), &b_IS_COPY));
 69         size_t readBytes = read(fileDescriptor, p_buf, sizeof(struct inotify_event));
 70 
 71         //read会阻塞进程,走到这里说明收到目录被删除的事件,注销监听器
 72         free(p_buf);
 73         inotify_rm_watch(fileDescriptor, IN_DELETE);
 74 
 75         //目录不存在log
 76         LOG_DEBUG((*env)->GetStringUTFChars(env, tag, &b_IS_COPY)
 77                     , (*env)->GetStringUTFChars(env, (*env)->NewStringUTF(env, "uninstalled"), &b_IS_COPY));
 78 
 79         if (userSerial == NULL)
 80         {
 81             //执行命令am start -a android.intent.action.VIEW -d http://shouji.360.cn/web/uninstall/uninstall.html
 82             execlp("am", "am", "start", "-a", "android.intent.action.VIEW", "-d", "http://shouji.360.cn/web/uninstall/uninstall.html", (char *)NULL);
 83         }
 84         else
 85         {
 86             //执行命令am start --user userSerial -a android.intent.action.VIEW -d http://shouji.360.cn/web/uninstall/uninstall.html
 87             execlp("am", "am", "start", "--user", (*env)->GetStringUTFChars(env, userSerial, &b_IS_COPY), "-a", "android.intent.action.VIEW", "-d", "http://shouji.360.cn/web/uninstall/uninstall.html", (char *)NULL);
 88         }
 89 
 90         //执行命令失败log
 91         LOG_ERROR((*env)->GetStringUTFChars(env, tag, &b_IS_COPY)
 92                     , (*env)->GetStringUTFChars(env, (*env)->NewStringUTF(env, "exec AM command failed !!!"), &b_IS_COPY));
 93     }
 94     else
 95     {
 96         //父进程直接退出,使子进程被init进程领养,以避免子进程僵死
 97     }
 98 }
 99 
100 #ifdef __cplusplus
101 }
102 #endif

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:http://bianchenghao.cn/34844.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注