package com.fourleaf.phonegap.plugin.installapk;

import java.io.IOException;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

import android.content.Intent;
import android.net.Uri;
import android.util.Log;

public class InstallApkPlugin extends CordovaPlugin {
	@Override
	public boolean execute(String action, JSONArray args,
			CallbackContext callbackContext) throws JSONException {
		if("install".equals(action)){
			String rawUri = args.getString(0);
			Uri uri = Uri.parse(rawUri);
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent.setDataAndType(uri,
					"application/vnd.android.package-archive");
			Process p;
			try {
				// [文件夹705:drwx---r-x]
				String u = rawUri.replace("file://", "");
				String[] args1 = { "chmod", "705", u.substring(0, u.lastIndexOf("/")) };
				p = Runtime.getRuntime().exec(args1);
				p.waitFor();
		        // [文件604:-rw----r--]
		        String[] args2 = { "chmod", "604", u };
		        p = Runtime.getRuntime().exec(args2);
		        p.waitFor();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			cordova.getActivity().startActivity(intent);
			return true;
		}
		return super.execute(action, args, callbackContext);
	}
}

@@ -782,16 +782,55 @@
 ive%22);%0D%0A
+%09%09%09if(rawUri.startsWith(%22file://%22))%7B%0D%0A%09
 %09%09%09Proce
@@ -843,15 +843,17 @@
 %0A%09%09%09
+%09
 try %7B%0D%0A
+%09
 %09%09%09%09
@@ -876,16 +876,17 @@
 --r-x%5D%0D%0A
+%09
 %09%09%09%09Stri
@@ -920,24 +920,25 @@
 ://%22, %22%22);%0D%0A
+%09
 %09%09%09%09String%5B%5D
@@ -1007,16 +1007,17 @@
 %7D;%0D%0A%09%09%09%09
+%09
 p = Runt
@@ -1043,24 +1043,25 @@
 ec(args1);%0D%0A
+%09
 %09%09%09%09p.waitFo
@@ -1064,24 +1064,25 @@
 itFor();%0D%0A%09%09
+%09
         // %5B
@@ -1100,16 +1100,17 @@
 --r--%5D%0D%0A
+%09
 %09%09      
@@ -1150,24 +1150,25 @@
 4%22, u %7D;%0D%0A%09%09
+%09
         p = 
@@ -1202,16 +1202,17 @@
 rgs2);%0D%0A
+%09
 %09%09      
@@ -1222,32 +1222,33 @@
 .waitFor();%0D%0A%09%09%09
+%09
 %7D catch (IOExcep
@@ -1250,32 +1250,33 @@
 Exception e) %7B%0D%0A
+%09
 %09%09%09%09// TODO Auto
@@ -1295,32 +1295,33 @@
 atch block%0D%0A%09%09%09%09
+%09
 e.printStackTrac
@@ -1322,24 +1322,25 @@
 ckTrace();%0D%0A
+%09
 %09%09%09%7D catch (
@@ -1366,24 +1366,25 @@
 n e) %7B%0D%0A%09%09%09%09
+%09
 // TODO Auto
@@ -1403,24 +1403,25 @@
 atch block%0D%0A
+%09
 %09%09%09%09e.printS
@@ -1434,16 +1434,23 @@
 ace();%0D%0A
+%09%09%09%09%7D%0D%0A
 %09%09%09%7D%0D%0A%09%09

fix error when use remote uri