Android获取SharedPreferences失败,且App无法启动

说明:

一个app访问另外一个app的SharedPreferences,程序启动之后没有显示界面就卡死了,无任何提示信息。

错误原因:

应用调用createPackageContext失败,但是也不给出异常信息;

/*
 * SharedPreferences sp = getSharedPreferences("ethernet",
 *      //Context.MODE_WORLD_WRITEABLE);
 *      Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE);
 */

Context ethernetAppContext = null;
try {
    ethernetAppContext = createPackageContext("com.dog.ethernet", Context.CONTEXT_IGNORE_SECURITY);
} catch (NameNotFoundException e) {
    new AlertDialog.Builder(this).setTitle("ERROR").setMessage("Please install ethernet application.").setPositiveButton("confirm", null ).show();  
    System.exit(-1);
    e.printStackTrace();
}   

SharedPreferences sharedPreferences = ethernetAppContext.getSharedPreferences("ethernet",  Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE);   
Log.e("info", "-------------------------------------------------");
Log.e("info", sharedPreferences.getString("conn_mode", ""));
Log.e("info", sharedPreferences.getString("mIpaddr", ""));
Log.e("info", sharedPreferences.getString("mDns", ""));
Log.e("info", sharedPreferences.getString("mProxyIp", ""));
Log.e("info", sharedPreferences.getString("mProxyPort", ""));
Log.e("info", sharedPreferences.getString("mProxyExclusionList", ""));
Log.e("info", "-------------------------------------------------");
  • 最后通过查看/data/data/路径下的包名,检查到com.dog.ethernet包名不存在,于是修改为正确的包名就正常了。
  • 将当前包下生成ethernet SharedPreferences的代码注释了才能获取到正确的数据,如果不注释掉,好像获取的数据是当前包下的ethernet SharedPreferences,花了挺长时间才确定这个问题。

获取结果

E/info    ( 5353): -------------------------------------------------
E/info    ( 5353): manual
E/info    ( 5353): 10.10.10.10
E/info    ( 5353): 8.8.8.8
E/info    ( 5353): -------------------------------------------------

Android.mk

LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)

LOCAL_MODULE_TAGS := optional

LOCAL_SRC_FILES := $(call all-java-files-under, com)

LOCAL_PACKAGE_NAME := ethernetCF
LOCAL_CERTIFICATE := platform

include $(BUILD_PACKAGE)

# Use the folloing include to make our test apk.
include $(call all-makefiles-under,$(LOCAL_PATH))

posted on 2016-04-29 11:25  zengjf  阅读(842)  评论(0编辑  收藏  举报

导航