11) 网址/IP白名单接口
---------- frameworks/base/core/java/android/provider/Settings.java
-
/** @hide */
-
public
static
final String PRIZE_NET_WHITELIST_ON =
"prize_net_whiteon";
-------------frameworks/base/packages/SettingsProvider/res/values/defaults.xml
<bool name="net_white_on">false</bool>
--------frameworks/base/packages/SettingsProvider/src/com/android/providers/settings/DatabaseHelper.java
loadBooleanSetting(stmt, Settings.System.PRIZE_NET_WHITELIST_ON, R.bool.net_white_on);
-------frameworks/base/core/java/android/os/INetworkManagementService.aidl
-
/**
-
* setBrowserWhiteListEnable add network white list
-
*/
-
void setBrowserWhiteListEnable(String white_list, boolean allow);
-
/**
-
* delBrowserWhiteListChainTable del network white list
-
*/
-
void delBrowserWhiteListChainTable(String white_list, boolean allow);
-------frameworks/base/services/core/java/com/android/server/NetworkManagementService.java
-
@Override
-
public void setBrowserWhiteListEnable(String white_list, boolean allow) {
-
enforceSystemUid();
-
final String rule = allow ?
"allow" :
"deny";
-
try {
-
Slog.e(
"snail_",
"-----setBrowserWhiteListEnable---white_list==" + white_list +
" bool=="+allow);
-
mConnector.execute(
"firewall",
"set_browserwhitelist_enable", white_list, rule);
-
}
catch (NativeDaemonConnectorException e) {
-
Slog.e(
"snail_",
"-----setBrowserWhiteListEnable----Exception----white_list==" + white_list +
" bool=="+allow +
": " + e);
-
throw e.rethrowAsParcelableException();
-
}
-
}
-
-
@Override
-
public void delBrowserWhiteListChainTable(String white_list, boolean allow) {
-
enforceSystemUid();
-
final String rule = allow ?
"allow" :
"deny";
-
try {
-
Slog.e(
"snail_",
"-----delBrowserWhiteListChainTable---white_list==" + white_list +
" bool=="+allow);
-
mConnector.execute(
"firewall",
"del_browserwhitelist_chaintable", white_list, rule);
-
}
catch (NativeDaemonConnectorException e) {
-
Slog.e(
"snail_",
"-----delBrowserWhiteListChainTable----Exception----white_list==" + white_list +
" bool=="+allow +
": " + e);
-
throw e.rethrowAsParcelableException();
-
}
-
}
--------system/netd/server/FirewallController.h
-
int setBrowserWhiteListEnable(const char*, FirewallRule);
-
int delBrowserWhiteListChainTable(const char*, FirewallRule);
--------system/netd/server/FirewallController.cpp
-
int FirewallController::setBrowserWhiteListEnable(
const
char* list, FirewallRule rule) {
-
-
//const char *chaintable = "WEBWHITELIST";
-
//const char *FORWARD_MARK = "1";
-
const
char* op;
-
if (rule == ALLOW) {
-
ALOGE(
"--snail_-----setBrowserWhiteListEnable------rule == allow-------");
-
op =
"-I";
-
}
else {
-
ALOGE(
"--snail_-----setBrowserWhiteListEnable------rule == deny-------");
-
op =
"-D";
-
}
-
ALOGE(
"---snail_------set_browserwhitelist_enable-list===%s", list);
-
const
char *split =
",";
-
char *p;
-
char* white_list = const_cast<
char*>(list);
-
p = strtok(white_list,split);
-
int res =
0;
-
//iptables -t filter -N WEBWHITELIST
-
//iptables -I OUTPUT -p tcp -j WEBWHITELIST
-
//iptables -t mangle -N WEBWHITELIST
-
//iptables -t mangle -I fw_mangle_POSTROUTING -p udp -j WEBWHITELIST
-
res |= execIptables(V4V6,
"-t",
"mangle",
"-N",
"WEBWHITELIST", NULL);
-
ALOGE(
"---snail_-------New WEBWHITELIST---------res===%d", res);
-
if(res ==
0){
-
res |= execIptables(V4V6,
"-t",
"mangle",
"-I",
"fw_mangle_POSTROUTING",
"-p",
"udp",
"-j",
"WEBWHITELIST", NULL);
-
while(p!=NULL) {
-
ALOGE(
"---snail_-set_browserwhitelist_enable-p!=NULL===%s\n", p);
-
//iptables -A WEBWHITELIST -p tcp -m string --string Host: --algo bm -j MARK --set-mark 1
-
//iptables -A WEBWHITELIST -p tcp -m mark --mark 1 -m string --string baidu --algo bm -j ACCEPT
-
//iptables -A WEBWHITELIST -p tcp -m mark --mark 1 -j REJECT
-
//iptables -t mangle -A WEBWHITELIST -p udp --dport 53 -m string --string baidu --algo bm -j ACCEPT
-
//iptables -t mangle -A WEBWHITELIST -p udp --dport 53 -m string --string taobao --algo bm -j ACCEPT
-
//iptables -t mangle -A WEBWHITELIST -p udp --dport 53 -j DROP
-
//res |= execIptables(V4V6, "-A", "WEBWHITELIST", "-p", "tcp", "-m", "string", "--string" ,"Host:", "--algo", "bm","-j", "MARK", "--set-mark", "1", NULL);
-
//res |= execIptables(V4V6, "-A", "WEBWHITELIST", "-p", "tcp", "-m", "mark", "--mark" ,"1" , "-m", "string", "--string" , p, "--algo", "bm", "-j", "ACCEPT", NULL);
-
res |= execIptables(V4V6,
"-t",
"mangle",
"-A",
"WEBWHITELIST",
"-p",
"udp",
"--dport",
"53",
"-m" ,
"string",
"--string" , p,
"--algo",
"bm",
"-j",
"ACCEPT", NULL);
-
-
p = strtok(NULL,split);
-
}
-
//res |= execIptables(V4V6, "-A", "WEBWHITELIST", "-p", "tcp", "-m", "mark", "--mark" ,"1", "-j", "REJECT", NULL);
-
res |= execIptables(V4V6,
"-t",
"mangle",
"-A",
"WEBWHITELIST",
"-p",
"udp",
"--dport",
"53",
"-j",
"DROP", NULL);
-
}
-
ALOGE(
"---snail_------set_browserwhitelist_enable-list---end===%d", res);
-
return res;
-
}
-
-
int FirewallController::delBrowserWhiteListChainTable(
const
char* list, FirewallRule rule) {
-
-
const
char* op;
-
const
char *DEL =
"1";
-
if (rule == ALLOW) {
-
ALOGE(
"--snail_-----delBrowserWhiteListChainTable------rule == allow-------");
-
op =
"-I";
-
}
else {
-
ALOGE(
"--snail_-----delBrowserWhiteListChainTable------rule == deny-------");
-
op =
"-D";
-
}
-
ALOGE(
"---snail_------delBrowserWhiteListChainTable-list===%s", list);
-
//iptables -D OUTPUT 1
-
//iptables -t filter -F WEBWHITELIST
-
//iptables -t filter -X WEBWHITELIST
-
//iptables -t mangle -D fw_mangle_POSTROUTING 1
-
//iptables -t mangle -F WEBWHITELIST
-
//iptables -t mangle -X WEBWHITELIST
-
int res =
0;
-
res |= execIptables(V4V6,
"-t",
"mangle",
"-D",
"fw_mangle_POSTROUTING", DEL, NULL);
-
res |= execIptables(V4V6,
"-t",
"mangle",
"-F",
"WEBWHITELIST", NULL);
-
res |= execIptables(V4V6,
"-t",
"mangle",
"-X",
"WEBWHITELIST", NULL);
-
return res;
-
}
----------system/netd/server/CommandListener.cpp
-
int CommandListener::FirewallCmd::runCommand(SocketClient *cli,
int argc,
-
char **argv) {
-
if (!strcmp(argv[
1],
"set_browserwhitelist_enable")) {
-
ALOGE(
"---snail_---------runCommand------set_browserwhitelist_enable---start-----");
-
if (argc !=
4) {
-
ALOGE(
"---snail_---------runCommand------set_browserwhitelist_enable---Error---");
-
cli->sendMsg(ResponseCode::CommandSyntaxError,
-
"Usage: firewall set_browserwhitelist_enable <rmnet0> <allow|deny>",
false);
-
return
0;
-
}
-
-
const
char* white_list = argv[
2];
-
FirewallRule rule = parseRule(argv[
3]);
-
ALOGE(
"---snail_---------runCommand------set_browserwhitelist_enable-white_list===%s", argv[
2]);
-
int res = gCtls->firewallCtrl.setBrowserWhiteListEnable(white_list, rule);
-
return sendGenericOkFail(cli, res);
-
}
-
-
if (!strcmp(argv[
1],
"del_browserwhitelist_chaintable")) {
-
ALOGE(
"---snail_---------runCommand------del_browserwhitelist_chaintable---start-----");
-
if (argc !=
4) {
-
ALOGE(
"---snail_---------runCommand------del_browserwhitelist_chaintable---Error---");
-
cli->sendMsg(ResponseCode::CommandSyntaxError,
-
"Usage: firewall del_browserwhitelist_chaintable <rmnet0> <allow|deny>",
false);
-
return
0;
-
}
-
-
const
char* white_list = argv[
2];
-
FirewallRule rule = parseRule(argv[
3]);
-
ALOGE(
"---snail_---------runCommand------del_browserwhitelist_chaintable-white_list===%s", argv[
2]);
-
int res = gCtls->firewallCtrl.delBrowserWhiteListChainTable(white_list, rule);
-
return sendGenericOkFail(cli, res);
-
}
app实现
-
@Override
-
public void setBrowserWhiteListEnable(boolean white_list_on,String white_list) throws RemoteException {
-
// TODO Auto-generated method stub
-
//String onnetfile = "/sdcard/.WhiteListNetList";
-
//Utils.initWhiteListNetList(onnetfile);
-
//List<String> list = Utils.readNetWhiteList(onnetfile);
-
List<String> list = Utils.readNetWhiteListByProvider(RemoteService.
this);
-
String[] array =
new String[list.size()];
-
// List转换成数组
-
for (
int i =
0; i < list.size(); i++) {
-
array[i] = list.get(i);
-
TXLog.d(TAG,
"----------setBrowserWhiteListEnable----------------array[i]=="+array[i]);
-
}
-
//Utils.writeNetWhiteList(onnetfile, Arrays.asList(white_list.split(",")));
-
Utils.whiteNetWhiteListByProvider(RemoteService.
this, Arrays.asList(white_list.split(
",")));
-
if(white_list_on){ Utils.delBrowserWhiteListChainTable(
true, white_list);
-
Utils.setBrowserWhiteListEnable(
true, white_list);
-
Settings.System.putInt(RemoteService.
this.getApplicationContext().getContentResolver(),Settings.System.PRIZE_NET_WHITELIST_ON,
1);
-
}
else {
-
Utils.delBrowserWhiteListChainTable(
true, white_list);
-
Settings.System.putInt(RemoteService.
this.getApplicationContext().getContentResolver(),Settings.System.PRIZE_NET_WHITELIST_ON,
0);
-
}
-
}
-
-
@Override
-
public String[] getBrowserWhiteList()
throws RemoteException {
-
// TODO Auto-generated method stub
-
//String onnetfile = "/sdcard/.WhiteListNetList";
-
//Utils.initWhiteListNetList(onnetfile);
-
//List<String> list = Utils.readNetWhiteList(onnetfile);
-
int isopen = Settings.System.getInt(RemoteService.
this.getApplicationContext().getContentResolver(),Settings.System.PRIZE_NET_WHITELIST_ON,
0);
-
if(isopen==
0){
-
TXLog.d(TAG,
"----------getBrowserWhiteList-------return null--------");
-
return
null;
-
}
-
List<String> list = Utils.readNetWhiteListByProvider(RemoteService.
this);
-
String[] array =
new String[list.size()];
-
// List转换成数组
-
for (
int i =
0; i < list.size(); i++) {
-
array[i] = list.get(i);
-
TXLog.d(TAG,
"----------getBrowserWhiteList----------------array[i]=="+array[i]);
-
-
}
-
return array;
-
}
-
-
@Override
-
public void addBrowserWhiteList(String addwhite) throws RemoteException {
-
// TODO Auto-generated method stub
-
//String onnetfile = "/sdcard/.WhiteListNetList";
-
//Utils.initWhiteListNetList(onnetfile);
-
//List<String> list = Utils.readNetWhiteList(onnetfile);
-
List<String> list = Utils.readNetWhiteListByProvider(RemoteService.
this);
-
Utils.delBrowserWhiteListChainTable(
true, addwhite);
-
List<String> addlist = Arrays.asList(addwhite.split(
","));
-
for (
int i =
0; i < addlist.size(); i++) {
-
if(!list.contains(addlist.get(i))){
-
list.add(addlist.get(i));
-
}
-
}
-
StringBuilder csBuilder =
new StringBuilder();
-
for(String weburl : list){
-
csBuilder.append(weburl);
-
csBuilder.append(
",");
-
}
-
if(csBuilder.length()>
1){
-
csBuilder.deleteCharAt(csBuilder.length()-
1);
-
}
-
//Utils.writeNetWhiteList(onnetfile, Arrays.asList(csBuilder.toString().split(",")));
-
//List<String> newlist = Utils.readNetWhiteList(onnetfile);
-
Utils.whiteNetWhiteListByProvider(RemoteService.
this, Arrays.asList(csBuilder.toString().split(
",")));
-
Utils.setBrowserWhiteListEnable(
true, csBuilder.toString());
-
Settings.System.putInt(RemoteService.
this.getApplicationContext().getContentResolver(),Settings.System.PRIZE_NET_WHITELIST_ON,
1);
-
}
-
-
public static void whiteNetWhiteListByProvider(Context context, List<String> webnames){
-
try {
-
Uri uri = Uri.parse(
"content://com.prize.txInterface.provider/ip");
-
context.getApplicationContext().getContentResolver().delete(uri,
null,
null);
-
for (
int i =
0; i < webnames.size(); i++) {
-
String host = webnames.get(i);
-
TXLog.d(TAG,
"---------------whiteNetWhiteListByProvider------------host==="+host);
-
if(!TextUtils.isEmpty(host)){
-
Cursor cursor = context.getApplicationContext().getContentResolver().query(uri,
null,
"host = ?",
new String[]{host},
null);
-
if(cursor !=
null){
-
if(cursor.getCount()<=
0){
-
ContentValues values =
new ContentValues();
-
values.put(
"host", host);
-
values.put(
"isActive",
"true");
-
TXLog.d(TAG,
"---------------whiteNetWhiteListByProvider------------insert==="+host);
-
context.getApplicationContext().getContentResolver().insert(uri, values);
-
}
-
}
-
}
-
}
-
}
catch (Exception e) {
-
// TODO: handle exception
-
TXLog.d(TAG,
"---------------whiteNetWhiteListByProvider------------"+e.getMessage());
-
return ;
-
}
-
}
-
-
public static void delBrowserWhiteListChainTable(boolean white_list_on ,String white_list){
-
INetworkManagementService netMgr = INetworkManagementService.Stub.asInterface(ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
-
try {
-
Log.e(TAG,
"----delBrowserWhiteListChainTable-------------white_list=="+white_list);
-
netMgr.delBrowserWhiteListChainTable(white_list,white_list_on);
-
}
catch (Exception e) {
-
Log.e(TAG,
"----delBrowserWhiteListChainTable-----RemoteException----------e==="+e.getMessage());
-
e.printStackTrace();
-
}
-
}
-
-
public static void setBrowserWhiteListEnable(boolean white_list_on ,String white_list){
-
INetworkManagementService netMgr = INetworkManagementService.Stub.asInterface(ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
-
try {
-
Log.e(TAG,
"----setBrowserWhiteListEnable-------------white_list=="+white_list);
-
netMgr.setBrowserWhiteListEnable(white_list,white_list_on);
-
}
catch (Exception e) {
-
Log.e(TAG,
"----setBrowserWhiteListEnable-----RemoteException----------e==="+e.getMessage());
-
e.printStackTrace();
-
}
-
}
-
12) APK安装白名单接口
---------frameworks/base/core/java/android/provider/Settings.java
-
/** @hide */
-
public
static
final String PRIZE_INSTALL_WHITELIST_ON =
"prize_install_whiteon";
------frameworks/base/packages/SettingsProvider/res/values/defaults.xml
<bool name="install_white_on">false</bool>
loadBooleanSetting(stmt, Settings.System.PRIZE_INSTALL_WHITELIST_ON, R.bool.install_white_on);
-
@Override
-
public void setApkWhiteListEnable(boolean iscaninstall, String whitelist)
-
throws RemoteException {
-
// TODO Auto-generated method stub
-
//Utils.initWhiteListAppList(whitelist);
-
//Utils.readInstallWhiteList(whitelist);
-
//Utils.writeInstallWhiteList("/sdcard/.WhiteListAppList", Arrays.asList(whitelist.split(",")));
-
Utils.readInstallWhiteListByProvider(RemoteService.
this.getApplicationContext());
-
Utils.whiteInstallWhiteListByProvider(RemoteService.
this.getApplicationContext(),Arrays.asList(whitelist.split(
",")));
-
if(iscaninstall){
-
Settings.System.putInt(RemoteService.
this.getApplicationContext().getContentResolver(),Settings.System.PRIZE_INSTALL_WHITELIST_ON,
1);
-
}
else {
-
Settings.System.putInt(RemoteService.
this.getApplicationContext().getContentResolver(),Settings.System.PRIZE_INSTALL_WHITELIST_ON,
0);
-
}
-
}
-
-
public static List<String> readInstallWhiteListByProvider(Context context){
-
try {
-
Uri uri = Uri.parse(
"content://com.prize.txInterface.provider/install");
-
List<String> list =
new ArrayList<String>();
-
Cursor cursor = context.getApplicationContext().getContentResolver().query(uri,
null,
null,
null,
null);
-
-
if(cursor!=
null&&cursor.moveToFirst()){
-
do{
-
String pkg = cursor.getString(cursor.getColumnIndex(
"package"));
-
TXLog.d(TAG,
"---------------readInstallWhiteListByProvider------------pkg=="+pkg);
-
if(!TextUtils.isEmpty(pkg)&& !list.contains(pkg)){
-
list.add(pkg);
-
}
-
}
while(cursor.moveToNext());
-
}
-
return list;
-
}
catch (Exception e) {
-
// TODO: handle exception
-
TXLog.d(TAG,
"---------------readInstallWhiteListByProvider------------"+e.getMessage());
-
return
null;
-
}
-
}
-
-
public static void whiteInstallWhiteListByProvider(Context context, List<String> pkgnames){
-
try {
-
Uri uri = Uri.parse(
"content://com.prize.txInterface.provider/install");
-
context.getApplicationContext().getContentResolver().delete(uri,
null,
null);
-
for (
int i =
0; i < pkgnames.size(); i++) {
-
String pkg = pkgnames.get(i);
-
TXLog.d(TAG,
"---------------whiteInstallWhiteListByProvider------------pkg==="+pkg);
-
if(!TextUtils.isEmpty(pkg)){
-
Cursor cursor = context.getApplicationContext().getContentResolver().query(uri,
null,
"package = ?",
new String[]{pkg},
null);
-
if(cursor !=
null){
-
if(cursor.getCount()<=
0){
-
ContentValues values =
new ContentValues();
-
values.put(
"package", pkg);
-
values.put(
"isActive",
"true");
-
TXLog.d(TAG,
"---------------whiteInstallWhiteListByProvider------------insert==="+pkg);
-
context.getApplicationContext().getContentResolver().insert(uri, values);
-
}
-
}
-
}
-
}
-
}
catch (Exception e) {
-
// TODO: handle exception
-
TXLog.d(TAG,
"---------------whiteInstallWhiteListByProvider------------"+e.getMessage());
-
return ;
-
}
-
}
----- frameworks/base/services/core/java/com/android/server/pm/PackageManagerService.java
-
private void installPackageLI(InstallArgs args, PackageInstalledInfo res){
-
-
String pkgName = res.name = pkg.packageName;
-
Log.e(
"snail_",
"---------installPackageLI---------------------pkgName=="+pkgName);
-
if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) !=
0){
-
Log.e(
"snail_",
"---------installPackageLI----------INSTALL_REPLACE_EXISTING-------------");
-
}
-
//boolean byprize = false;
-
//if ((installFlags & PackageManager.INSTALL_FROM_PRIZE) != 0){
-
// Log.e("snail_", "---------installPackageLI----------INSTALL_FROM_PRIZE-------------");
-
// byprize = true;
-
//}
-
-
int iswhiteon = android.provider.Settings.System.getInt(mContext.getContentResolver(),android.provider.Settings.System.PRIZE_INSTALL_WHITELIST_ON,
-
0);
-
Log.e(
"snail_",
"---------installPackageLI----------------iswhiteon=="+iswhiteon);
-
if(iswhiteon ==
1){
-
//add for installer white list
-
boolean caninstall =
false;
-
Log.e(
"snail_",
"---------installPackageLI----------------pkgName=="+pkgName);
-
if(!TextUtils.isEmpty(pkgName)){
-
if(isInstallerEnable(pkgName)
/*|| byprize*/){
-
Log.e(
"snail_",
"---------installPackageLI----------------caninstall = true------------");
-
caninstall =
true;
-
}
-
-
if(!caninstall){
-
//Toast.makeText(mContext, R.string.install_error, Toast.LENGTH_LONG).show();
-
Log.e(
"snail_",
"---------installPackageLI----------------caninstall = false------------");
-
//res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
-
res.setError(PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE,
-
"app is not in the whitelist. packageName:" + pkgName);
-
return;
-
}
-
}
-
}
-
-
-
/*add for installer white list*/
-
private boolean isInstallerEnable(String packagename){
-
/* ArrayList<String> whiteListApp = new ArrayList<String>();
-
-
try{
-
BufferedReader br = new BufferedReader(new InputStreamReader(
-
new FileInputStream("/sdcard/.WhiteListAppList")));
-
-
String line ="";
-
while ((line = br.readLine()) != null){
-
whiteListApp.add(line);
-
}
-
-
br.close();
-
}catch(java.io.FileNotFoundException ex){
-
Log.e("snail_", "--------isInstallerEnable------FileNotFoundException=="+ex.getMessage());
-
return false;
-
}catch(java.io.IOException ex){
-
Log.e("snail_", "--------isInstallerEnable------IOException=="+ex.getMessage());
-
return false;
-
}
-
-
Iterator<String> it = whiteListApp.iterator();
-
-
while (it.hasNext()) {
-
String whitelisItem = it.next();
-
Log.e("snail_", "--------isInstallerEnable------whitelisItem=="+whitelisItem+" packagename=="+packagename);
-
if (whitelisItem.equals(packagename)) {
-
return true;
-
}
-
}
-
return false;*/
-
try {
-
Uri uri = Uri.parse(
"content://com.prize.txInterface.provider/install");
-
//List<String> list = new ArrayList<String>();
-
Cursor cursor = mContext.getApplicationContext().getContentResolver().query(uri,
null,
"package = ?",
new String[]{packagename},
null);
-
if(cursor !=
null && cursor.moveToFirst()){
-
Log.d(TAG,
"---------readInstallWhiteListByProvider-------------exist==="+packagename);
-
return
true;
-
}
else {
-
Log.d(TAG,
"---------readInstallWhiteListByProvider-------------!!!!!exist==="+packagename);
-
}
-
return
false;
-
}
catch (Exception e) {
-
// TODO: handle exception
-
Log.d(
"snail_",
"---------------readInstallWhiteListByProvider------------"+e.getMessage());
-
return
false;
-
}
-
-
}
---------packages/apps/PackageInstaller/src/com/android/packageinstaller/PackageInstallerActivity.java
-
private boolean readInstallWhiteListByProvider(Context context,String packagename){
-
try {
-
Uri uri = Uri.parse(
"content://com.prize.txInterface.provider/install");
-
List<String> list =
new ArrayList<String>();
-
Cursor cursor = context.getApplicationContext().getContentResolver().query(uri,
null,
"package = ?",
new String[]{packagename},
null);
-
if(cursor !=
null && cursor.moveToFirst()){
-
Log.d(TAG,
"---------readInstallWhiteListByProvider-------------exist==="+packagename);
-
return
true;
-
}
-
return
false;
-
}
catch (Exception e) {
-
// TODO: handle exception
-
Log.d(
"snail_",
"---------------readInstallWhiteListByProvider------------"+e.getMessage());
-
return
false;
-
}
-
}
-
private String getInstallpkg(final Uri packageUri){
-
final String getInstallscheme = packageUri.getScheme();
-
final PackageUtil.AppSnippet as;
-
PackageInfo getInstallPkgInfo =
null;
-
Log.e(
"snail_",
"-----onCreate-------getInstallpkg----------getInstallscheme=="+getInstallscheme);
-
if(getInstallscheme.equals(SCHEME_PACKAGE)){
-
try {
-
getInstallPkgInfo = mPm.getPackageInfo(packageUri.getSchemeSpecificPart(),PackageManager.GET_PERMISSIONS| PackageManager.GET_UNINSTALLED_PACKAGES);
-
}
catch (NameNotFoundException e) {
-
}
-
if (getInstallPkgInfo !=
null) {
-
return getInstallPkgInfo.packageName;
-
}
else {
-
Log.e(
"snail_",
"-----onCreate-------getInstallpkg---SCHEME_PACKAGE----null------");
-
}
-
}
else
if (getInstallscheme.equals(SCHEME_FILE)) {
-
File sourceFile =
new File(packageUri.getPath());
-
PackageParser.Package parsed = PackageUtil.getPackageInfo(sourceFile);
-
// Check for parse errors
-
if (parsed !=
null) {
-
getInstallPkgInfo = PackageParser.generatePackageInfo(parsed,
null,PackageManager.GET_PERMISSIONS,
0,
0,
null,
new PackageUserState());
-
if (getInstallPkgInfo !=
null) {
-
return getInstallPkgInfo.packageName;
-
}
else {
-
Log.e(
"snail_",
"-----onCreate-------getInstallpkg---SCHEME_FILE----null------");
-
}
-
}
-
-
}
else
if (getInstallscheme.equals(SCHEME_CONTENT)) {
-
Uri baseUri = MediaStore.Files.getContentUri(
"external");
-
Log.e(
"snail_",
"-----getInstallpkg--------------------SCHEME_CONTENT--------------baseUri=="+baseUri.toString());
-
if(packageUri.toString().contains(baseUri.toString())){
-
try {
-
//int id = Integer.parseInt(packageUri.toString().replace(baseUri.toString()+File.separator, ""));
-
String id = packageUri.toString().replace(baseUri.toString()+File.separator,
"");
-
String pathString = getPkgPath(PackageInstallerActivity.
this,id);
-
Log.d(
"snail_",
"--------getApkPackagesName---SCHEME_CONTENT--------pathString=="+pathString);
-
if(!TextUtils.isEmpty(pathString)){
-
PackageManager pm = PackageInstallerActivity.
this.getApplicationContext().getPackageManager();
-
PackageInfo info = pm.getPackageArchiveInfo(pathString, PackageManager.GET_ACTIVITIES);
-
ApplicationInfo appInfo =
null;
-
if (info !=
null) {
-
appInfo = info.applicationInfo;
-
String packageName = appInfo.packageName;
-
Log.d(
"snail_",
"--------getApkPackagesName--*****************---------packageName=="+packageName);
-
return packageName;
-
}
-
}
-
}
catch (NumberFormatException e) {
-
Log.e(
"snail_",
"-----onCreate-------getInstallpkg---NumberFormatException------e=="+e.getMessage());
-
e.printStackTrace();
-
}
-
}
-
}
-
return
"";
-
}
-
-
public String getPkgPath(Context context,String _id) {
-
final String[] projection = {MediaColumns.DATA};
-
final String where = MediaColumns._ID +
" = ?";
-
Uri baseUri = MediaStore.Files.getContentUri(
"external");
-
-
Cursor c =
null;
-
String provider =
"com.android.providers.media.MediaProvider";
-
Uri itemUri =
null;
-
context.grantUriPermission(provider, baseUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
-
Log.d(
"snail_",
"getItemContentUri------- projection = "+projection+
", where = "+where+
", baseUri = "+baseUri);
-
try {
-
c = context.getContentResolver().query(baseUri,
-
projection,
-
where,
-
new String[]{_id},
-
null);
-
if (c !=
null && c.moveToNext()) {
-
String path = c.getString(c.getColumnIndexOrThrow(MediaColumns.DATA));
//DATA
-
if (!TextUtils.isEmpty(path)) {
-
Log.d(
"snail_",
"getItemContentUri, path = " + path);
-
return path;
-
}
-
}
-
}
catch (Exception e) {
-
Log.e(TAG,
"getItemContentUri Exception", e);
-
}
finally {
-
if (c !=
null) {
-
c.close();
-
}
-
}
-
return
"";
-
}
-
-
private boolean judgeInstallwhite(String pkgName){
-
if (!TextUtils.isEmpty(pkgName)) {
-
Log.e(
"snail_",
"-----judgeInstallwhite------------------------pkgName=="+ pkgName);
-
// add for installer enable/disable
-
if (!readInstallWhiteListByProvider(PackageInstallerActivity.
this,pkgName)) {
-
Log.e(
"snail_",
"-----judgeInstallwhite-----------!!!!!!isInstallerEnable--------------");
-
return
false;
-
}
-
}
-
return
true;
-
}
-
-
-
-
onCreate{
-
-
Log.e(
"snail_",
"-----onCreate----------------111----------packageUri=="+packageUri);
-
int iswhiteon = android.provider.Settings.System.getInt(
this.getContentResolver(),android.provider.Settings.System.PRIZE_INSTALL_WHITELIST_ON,
0);
-
if (iswhiteon ==
1) {
-
String pkgName = getInstallpkg(packageUri);
-
if (!TextUtils.isEmpty(pkgName)) {
-
Log.e(
"snail_",
"-----judgeInstallwhite------------------------pkgName=="+ pkgName);
-
// add for installer enable/disable
-
if (!judgeInstallwhite(pkgName)) {
-
Log.e(
"snail_",
"-----judgeInstallwhite-----------!!!!!!isInstallerEnable--------------");
-
this.overridePendingTransition(
0,
0);
-
finish();
-
return;
-
}
-
}
-
}
13) 应用卸载接口
详见 天芯教育需求接口实现(一) 应用静默安装
14) 护眼模式开关接口
-
public static void setBluesysEnable(final Context mContext,final boolean isOpen) {
-
final
boolean BLUELIGHT_MTK =
true;
-
AsyncTask.execute(
new Runnable() {
-
public void run() {
-
final ContentResolver mResolver = mContext.getContentResolver();
-
Settings.System.putIntForUser(mResolver,Settings.System.PRIZE_BLULIGHT_MODE_STATE, isOpen ?
0:
1, UserHandle.USER_CURRENT);
-
int mBluLightTimeStatus = Settings.System.getIntForUser(mResolver, Settings.System.PRIZE_BLULIGHT_TIME_STATE,
0, UserHandle.USER_CURRENT);
-
int mBluLightTimingStatus = Settings.System.getIntForUser(mResolver, Settings.System.PRIZE_BLULIGHT_TIMING_STATE,
0, UserHandle.USER_CURRENT);
-
if (isOpen) {
-
if (BLUELIGHT_MTK) {
-
PictureQuality.enableBlueLight(
false);
-
}
-
if (mBluLightTimeStatus ==
1) {
-
Settings.System.putInt(mResolver, Settings.System.PRIZE_BLULIGHT_TIMING_STATE,
0);
-
setBluLightTime(mContext,
101010,Settings.System.PRIZE_BLULIGHT_START_TIME,
"com.android.intent_action_open_blulight");
-
}
-
}
else {
-
if (BLUELIGHT_MTK) {
-
PictureQuality.enableBlueLight(
true);
-
}
-
/* prize-modify for huyanmode-lihuangyuan-2017-06-09-end */
-
if (mBluLightTimingStatus ==
1) {
-
setBluLightTime(mContext,
101011,Settings.System.PRIZE_BLULIGHT_END_TIME,
"com.android.intent_action_close_blulight");
-
if(mBluLightTimingStatus ==
0){
-
cancelAlarm(mContext,
"com.android.intent_action_open_blulight");
-
}
-
}
-
}
-
}
-
});
-
}
-
private static void cancelAlarm(final Context mContext,String action){
-
Intent intent =
new Intent();
-
intent.setAction(action);
-
PendingIntent pi = PendingIntent.getBroadcast(mContext,
0,intent,
0);
-
AlarmManager am = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
-
am.cancel(pi);
-
}
-
private static void setBluLightTime(final Context mContext,int requestCode,String key, String action){
-
TXLog.d(TAG,
"--------setBluLightTime setBluLightTime() key = " + key);
-
AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
-
-
Intent mIntent =
new Intent(action);
-
PendingIntent operation = PendingIntent.getBroadcast(mContext, requestCode
/* requestCode */, mIntent,
0);
-
-
long alarmTime = getAlarmTime(key).getTimeInMillis();
-
-
alarmManager.setExact(AlarmManager.RTC_WAKEUP,alarmTime,operation);
-
}
-
public static Calendar getAlarmTime(String key) {
-
int[] mHourAndMinuteArr = parseBluLightTime(key);
-
int hour = mHourAndMinuteArr[
0];
-
int minute = mHourAndMinuteArr[
1];
-
Log.d(
"BluLight",
"PrizeBluLightTileDefined getAlarmTime() key = " + key+
",hour = "+hour+
",minute = "+minute);
-
-
Calendar calendar = Calendar.getInstance();
-
calendar.setTimeInMillis(System.currentTimeMillis());
-
-
int mYear = calendar.get(Calendar.YEAR);
-
int mMonth = calendar.get(Calendar.MONTH);
-
int mDay = calendar.get(Calendar.DAY_OF_MONTH);
-
-
Calendar mCalendar = Calendar.getInstance();
-
mCalendar.set(Calendar.YEAR, mYear);
-
mCalendar.set(Calendar.MONTH, mMonth);
-
mCalendar.set(Calendar.DAY_OF_MONTH, mDay);
-
mCalendar.set(Calendar.HOUR_OF_DAY, hour);
-
mCalendar.set(Calendar.MINUTE, minute);
-
mCalendar.set(Calendar.SECOND,
0);
-
mCalendar.set(Calendar.MILLISECOND,
0);
-
-
long mCurrentMillis = calendar.getTimeInMillis();
-
long mTimerMillis = mCalendar.getTimeInMillis();
-
-
boolean isTimerEarlyCurrent = mTimerMillis < mCurrentMillis;
-
boolean isEndEarlyStart =
false;
-
if(Settings.System.PRIZE_BLULIGHT_END_TIME.equals(key)){
-
int[] mStartHourAndMinuteArr = parseBluLightTime(Settings.System.PRIZE_BLULIGHT_START_TIME);
-
int mStartHour = mStartHourAndMinuteArr[
0];
-
int mEndHour = mStartHourAndMinuteArr[
1];
-
Calendar mStartCalendar = Calendar.getInstance();
-
mStartCalendar.set(Calendar.YEAR, mYear);
-
mStartCalendar.set(Calendar.MONTH, mMonth);
-
mStartCalendar.set(Calendar.DAY_OF_MONTH, mDay);
-
mStartCalendar.set(Calendar.HOUR_OF_DAY, mStartHour);
-
mStartCalendar.set(Calendar.MINUTE, mEndHour);
-
mStartCalendar.set(Calendar.SECOND,
0);
-
mStartCalendar.set(Calendar.MILLISECOND,
0);
-
-
long mStartMillis = mStartCalendar.getTimeInMillis();
-
isEndEarlyStart = mTimerMillis < mStartMillis;
-
}
-
if(isTimerEarlyCurrent || isEndEarlyStart){
-
mCalendar.set(Calendar.DAY_OF_MONTH, mDay+
1);
-
}
-
SimpleDateFormat dfs =
new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss.SSS");
-
String bgdate = dfs.format(mCalendar.getTime());
-
Log.d(
"BluLight",
"PrizeBluLightTileDefined Time : "+bgdate);
-
return mCalendar;
-
}
-
private
static
int[] parseBluLightTime(String key){
-
String mBluLightTimeStatus = Settings.System.getString(mContext.getContentResolver(), key);
-
int[] mHourAndMinuteArr =
new
int[
2];
-
if(mBluLightTimeStatus !=
null){
-
String[] mTimeArr = mBluLightTimeStatus.split(
":");
-
for(
int i=
0;i<mTimeArr.length;i++){
-
mHourAndMinuteArr[i] = Integer.parseInt(mTimeArr[i]);
-
}
-
}
-
return mHourAndMinuteArr;
-
}
15) 应用联网控制
-
public static void setAppFirewall(Context mContext,int uid, boolean enabled) {
-
try {
-
TXLog.d(
"PrizeNetControlsss",
"setAppFirewall enabled:" + enabled+
" uid=="+uid);
-
getINetworkManagementService(mContext).setFirewallUidChainRule(uid,
0, enabled);
-
getINetworkManagementService(mContext).setFirewallUidChainRule(uid,
1, enabled);
-
}
catch (RemoteException e) {
-
e.printStackTrace();
-
}
catch (Exception e) {
-
TXLog.d(TAG,
"setAppFirewall exception");
-
}
-
}
-
-
public void setFirewallUidChainRule(int uid, int networkType, boolean allow) {
-
//enforceSystemUid();
-
final String MOBILE =
"mobile";
-
final String WIFI =
"wifi";
-
-
final String rule = allow ?
"allow" :
"deny";
-
final String chain = (networkType ==
1) ? WIFI : MOBILE;
-
-
try {
-
mConnector.execute(
"firewall",
"set_uid_fw_rule", uid, chain, rule);
-
}
catch (NativeDaemonConnectorException e) {
-
throw e.rethrowAsParcelableException();
-
}
-
}
-
//CommandListener.cpp
-
if (!strcmp(argv[
1],
"set_uid_fw_rule")) {
-
if (argc !=
5) {
-
cli->sendMsg(ResponseCode::CommandSyntaxError,
-
"Usage: firewall set_uid_fw_rule <uid> <mobile|wifi> <allow|deny>",
-
false);
-
return
0;
-
}
-
-
int uid = atoi(argv[
2]);
-
FirewallChinaRule chain = parseChain(argv[
3]);
-
FirewallRule rule = parseRule(argv[
4]);
-
-
int res = gCtls->firewallCtrl.setUidFwRule(uid, chain, rule);
-
return sendGenericOkFail(cli, res);
-
}
-
-
//FirewallController.cpp
-
int FirewallController::setUidFwRule(
int uid, FirewallChinaRule chain, FirewallRule rule) {
-
char uidStr[
16];
-
int res =
0;
-
const
char* op;
-
const
char* fwChain;
-
-
sprintf(uidStr,
"%d", uid);
-
-
if (rule == ALLOW) {
-
op =
"-I";
-
}
else {
-
op =
"-D";
-
}
-
-
if(chain == MOBILE) {
-
fwChain =
"mobile";
-
}
else{
-
fwChain =
"wifi";
-
}
-
-
if(chain == MOBILE) {
-
if(rule == ALLOW)
-
blacklistUsers.insert(uid);
-
else
-
blacklistUsers.erase(uid);
-
}
-
-
res |= execIptables(V4, op, fwChain,
"-m",
"owner",
"--uid-owner", uidStr,
-
"-j",
"DROP", NULL);
-
-
res |= execIptables(V6, op, fwChain,
"-m",
"owner",
"--uid-owner", uidStr,
-
"-j",
"DROP", NULL);
-
-
return res;
-
}
16) 启动Service或Activity
-
public static void startAapplication(Context context,int type,String pkg_name,String class_name){
-
Intent mIntent=
new Intent();
-
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
-
mIntent.setComponent(
new ComponentName(pkg_name, class_name));
-
TXLog.d(TAG,
"----------startAapplication-----type=="+type+
" pkg_name=="+pkg_name+
" class_name=="+class_name);
-
if(type==
1){
//service
-
context.getApplicationContext().startService(mIntent);
-
}
else
if(type==
2){
//activity
-
context.getApplicationContext().startActivity(mIntent);
-
}
-
}
17) 控制无障碍服务
-
package com.prize.txInterface.util;
-
-
import java.util.Collections;
-
import java.util.HashSet;
-
import java.util.Set;
-
import android.content.ComponentName;
-
import android.content.Context;
-
import android.provider.Settings;
-
import android.text.TextUtils.SimpleStringSplitter;
-
-
-
public
class AccessibilityUtils {
-
-
-
private
static String TAG =
"snail_AccessibilityUtils";
-
/**
-
* @return the set of enabled accessibility services. If there are not services
-
* it returned the unmodifiable {@link Collections#emptySet()}.
-
*/
-
public static Set<ComponentName> getEnabledServicesFromSettings(Context context) {
-
final String enabledServicesSetting = Settings.Secure.getString(
-
context.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
-
if (enabledServicesSetting ==
null) {
-
TXLog.d(TAG,
"----getEnabledServicesFromSettings-------getEnabledServicesFromSettings--------");
-
return Collections.emptySet();
-
}
-
TXLog.d(TAG,
"----getEnabledServicesFromSettings-------getEnabledServicesFromSettings==="+enabledServicesSetting);
-
final Set<ComponentName> enabledServices =
new HashSet<ComponentName>();
-
final SimpleStringSplitter colonSplitter =
new SimpleStringSplitter(
':');
-
colonSplitter.setString(enabledServicesSetting);
-
-
while (colonSplitter.hasNext()) {
-
final String componentNameString = colonSplitter.next();
-
TXLog.d(TAG,
"----getEnabledServicesFromSettings-------componentNameString==="+componentNameString);
-
final ComponentName enabledService = ComponentName.unflattenFromString(componentNameString);
-
if (enabledService !=
null) {
-
enabledServices.add(enabledService);
-
}
-
}
-
-
return enabledServices;
-
}
-
-
-
public static void turnOnAccesibilityService(Context context, Boolean isInsert,String pack_class_name) {
-
Set<ComponentName> enabledServices = AccessibilityUtils.getEnabledServicesFromSettings(context);
-
-
if (enabledServices == (Set<?>) Collections.emptySet()) {
-
enabledServices =
new HashSet<ComponentName>();
-
}
-
ComponentName toggledService = ComponentName.unflattenFromString(pack_class_name);
-
TXLog.d(TAG,
"---turnOnAccesibilityService-----------preferenceKey=="+pack_class_name+
" toggledService=="+toggledService.toString());
-
boolean accessibilityEnabled =
false;
-
if(isInsert){
-
if(!enabledServices.contains(toggledService)){
-
enabledServices.add(toggledService);
-
TXLog.d(TAG,
"--------turnOnAccesibilityService----isInsert---!!!!!!contains---------");
-
}
else {
-
TXLog.d(TAG,
"--------turnOnAccesibilityService---isInsert----contains---------");
-
}
-
}
else {
-
if(!enabledServices.contains(toggledService)){
-
TXLog.d(TAG,
"--------turnOnAccesibilityService----!!isInsert---!!!!!!contains---------");
-
}
else {
-
enabledServices.remove(toggledService);
-
TXLog.d(TAG,
"--------turnOnAccesibilityService---!!!isInsert----contains---------");
-
}
-
}
-
accessibilityEnabled =
true;
-
StringBuilder enabledServicesBuilder =
new StringBuilder();
-
for (ComponentName enabledService : enabledServices) {
-
enabledServicesBuilder.append(enabledService.flattenToString());
-
enabledServicesBuilder.append(
':');
-
}
-
final
int enabledServicesBuilderLength = enabledServicesBuilder.length();
-
if (enabledServicesBuilderLength >
0) {
-
enabledServicesBuilder.deleteCharAt(enabledServicesBuilderLength -
1);
-
}
-
TXLog.d(TAG,
"----turnOnAccesibilityService--------enabledServicesBuilder==="+ enabledServicesBuilder.toString());
-
-
Settings.Secure.putString(context.getContentResolver(),Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES,enabledServicesBuilder.toString());
-
Settings.Secure.putInt(context.getContentResolver(),Settings.Secure.ACCESSIBILITY_ENABLED, accessibilityEnabled ?
1:
0);
-
}
-
}
18) 控制设备管理器
-
@Override
-
public void controlDeviceManager(String pkg_receiver, boolean active)
-
throws RemoteException {
-
// TODO Auto-generated method stub
-
ComponentName receive = ComponentName.unflattenFromString(pkg_receiver);
-
if(active){
-
DeviceAdminUtils.setActiveAdmin(RemoteService.
this.getApplicationContext(), receive);
-
}
else{
-
DeviceAdminUtils.removeActiveAdmin(RemoteService.
this.getApplicationContext(), receive);
-
}
-
}
-
package com.prize.txInterface.util;
-
-
import java.io.IOException;
-
import java.util.ArrayList;
-
import java.util.List;
-
-
import org.xmlpull.v1.XmlPullParserException;
-
import android.app.ActivityManagerNative;
-
import android.os.RemoteCallback;
-
import android.widget.AppSecurityPermissions;
-
import android.app.Activity;
-
import android.app.admin.DeviceAdminInfo;
-
import android.app.admin.DeviceAdminReceiver;
-
import android.app.admin.DevicePolicyManager;
-
import android.content.ComponentName;
-
import android.content.Context;
-
import android.content.Intent;
-
import android.content.pm.ActivityInfo;
-
import android.content.pm.PackageManager;
-
import android.content.pm.ResolveInfo;
-
import android.os.Bundle;
-
import android.os.Handler;
-
import android.os.RemoteException;
-
import android.util.EventLog;
-
import android.util.Log;
-
-
public
class DeviceAdminUtils {
-
-
private
static String TAG =
"snail_DeviceAdminUtils";
-
private
static DevicePolicyManager mDPM;
-
private
static PackageManager mPackageManager;
-
private
static Handler mHandler;
-
-
-
public static void removeActiveAdmin(final Context mContext,ComponentName mComponentName){
-
final DeviceAdminInfo mDeviceAdmin;
-
ActivityInfo ai;
-
try {
-
ai = getPackageManager(mContext).getReceiverInfo(mComponentName, PackageManager.GET_META_DATA);
-
}
catch (PackageManager.NameNotFoundException e) {
-
Log.w(TAG,
"-----removeActiveAdmin----Unable to retrieve device policy " + mComponentName, e);
-
return;
-
}
-
try {
-
ActivityManagerNative.getDefault().stopAppSwitches();
-
}
catch (RemoteException e) {
-
}
-
-
if (!getDevicePolicyManager(mContext).isAdminActive(mComponentName)) {
-
List<ResolveInfo> avail = getPackageManager(mContext).queryBroadcastReceivers(
-
new Intent(DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
-
PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS);
-
int count = avail ==
null ?
0 : avail.size();
-
boolean found =
false;
-
for (
int i=
0; i<count; i++) {
-
ResolveInfo ri = avail.get(i);
-
if (ai.packageName.equals(ri.activityInfo.packageName)&& ai.name.equals(ri.activityInfo.name)) {
-
try {
-
// We didn't retrieve the meta data for all possible matches, so
-
// need to use the activity info of this specific one that was retrieved.
-
ri.activityInfo = ai;
-
DeviceAdminInfo dpi =
new DeviceAdminInfo(mContext, ri);
-
found =
true;
-
}
catch (XmlPullParserException e) {
-
<