您的位置:首页 > 移动开发 > Android开发

Android获取系统文件目录,让程序访问其他程序的/data/data下的私有文件

2014-03-29 19:23 603 查看
Android系统为每个程序分配了各自的数据存储空间,一个程序要想访问另一个程序的私有文件,必须要有足够的权限。如何获取这个权限呢?答案是将手机root,这样就可以获取最高权限了。如果你的手机没有root,就不用继续看下去了

获取Android系统目录下的文件(夹):

package com.example.rootexploretest;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ListView lvFile = (ListView) findViewById(R.id.listFile);
String[] content = getRootFileContent("/data/data"); //获取/data/data目录下的文件(夹)

lvFile.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, content));
}

public static String[] getRootFileContent(String strPath) {
Process process = null;
DataOutputStream os = null;
String allList = "";
String strItems[] = null;
try {
process = Runtime.getRuntime().exec("su"); // 切换到root帐号
os = new DataOutputStream(process.getOutputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()), 1024);

os.writeBytes("ls " + strPath + "\n");
os.writeBytes("exit\n");

String strTmp = "";
while ((strTmp = bufferedReader.readLine()) != null) {
allList += strTmp + "<";
}
strItems = allList.split("<");

os.flush();
process.waitFor();
} catch (Exception e) {
return null;
} finally {
try {
if (os != null) {
os.close();
}
process.destroy();
} catch (Exception e) {
}
}
return strItems;
}
}

那么该如何访问其他程序的私有文件呢?之所以不能访问一个程序的私有文件,是因为该文件的权限被设置为不能被外部程序读写。所以,只要将私有文件的权限设置为可以被外部程序读写就可以了。

要想将文件的权限修改为可被其他程序读写,可以参看下面的方法:

(摘自:http://blog.csdn.net/tianshuai1111/article/details/8678895





/**
* 应用程序运行命令获取 Root权限,设备必须已破解(获得ROOT权限)
* @return 应用程序是/否获取Root权限
*/
public static boolean upgradeRootPermission(String pkgCodePath) {
Process process = null;
DataOutputStream os = null;
try {
String cmd="chmod 777 " + pkgCodePath;
process = Runtime.getRuntime().exec("su"); //切换到root帐号
os = new DataOutputStream(process.getOutputStream());
os.writeBytes(cmd + "\n");
os.writeBytes("exit\n");
os.flush();
process.waitFor();
} catch (Exception e) {
return false;
} finally {
try {
if (os != null) {
os.close();
}
process.destroy();
} catch (Exception e) {
}
}
return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐