Advertisement
Guest User

Fr4gg0r

a guest
Sep 16th, 2010
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.73 KB | None | 0 0
  1. package de.Fr4gg0r.SGSTools;
  2.  
  3. import java.io.BufferedOutputStream;
  4. import java.io.BufferedReader;
  5. import java.io.DataOutputStream;
  6. import java.io.File;
  7. import java.io.FileFilter;
  8. import java.io.FileOutputStream;
  9. import java.io.FileReader;
  10. import java.io.IOException;
  11. import java.io.InputStream;
  12. import java.io.InputStreamReader;
  13. import java.io.OutputStream;
  14. import java.util.ArrayList;
  15. import java.util.Enumeration;
  16. import java.util.zip.ZipEntry;
  17. import java.util.zip.ZipFile;
  18.  
  19. import android.app.AlertDialog;
  20. import android.app.ListActivity;
  21. import android.app.ProgressDialog;
  22. import android.content.DialogInterface;
  23. import android.os.Bundle;
  24. import android.os.Handler;
  25. import android.view.KeyEvent;
  26. import android.view.View;
  27. import android.view.ViewGroup.LayoutParams;
  28. import android.widget.AdapterView;
  29. import android.widget.AdapterView.OnItemClickListener;
  30. import android.widget.ArrayAdapter;
  31. import android.widget.TextView;
  32. import android.widget.Toast;
  33.  
  34. public class ScriptReceiver extends ListActivity{
  35.     private myMenu menu;
  36.     //must be global..
  37.     private String output = "";
  38.     private boolean done;
  39.     private Runnable update;
  40.     private ArrayList<String> usedFromZip;
  41.     private boolean remove;
  42.     public void onCreate(Bundle b){
  43.         super.onCreate(b);
  44.         setContentView(R.layout.scriptreceivermain);
  45.         menu = new myMenu(this);
  46.         File file = new File("/sdcard/sgstools");
  47.         if(!file.exists()){
  48.             //create dir if not already exits
  49.             file.mkdir();
  50.         }
  51.         final ArrayList<String> scriptz = new ArrayList<String>();
  52.         file.listFiles(new FileFilter(){
  53.             public boolean accept(File file){
  54.                 if(file.getName().endsWith(".txt"))scriptz.add(file.getAbsolutePath());
  55.                 return false;
  56.             }
  57.         });
  58.         file.listFiles(new FileFilter(){
  59.             public boolean accept(File file){
  60.                 if(file.getName().endsWith(".zip"))scriptz.add(file.getAbsolutePath());
  61.                 return false;
  62.             }
  63.         });
  64.         final String[] data = scriptz.toArray(new String[0]);      
  65.         setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data));
  66.         menu = new myMenu(this);  
  67.         addContentView(menu, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
  68.            menu.addSection(getString(R.string.menu), getResources().getDrawable(android.R.drawable.ic_menu_preferences));
  69.            menu.setCallback(new myMenuCallback(){
  70.                public void menuItemSelected(int which){
  71.                    //only 1 section so which always 0
  72.                    finish();
  73.                }
  74.            });
  75.            getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
  76.             public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
  77.                 final String name = ((TextView)view).getText().toString();
  78.                 AlertDialog.Builder builder = new AlertDialog.Builder(ScriptReceiver.this);
  79.                 builder.setTitle("Delete File?");
  80.                 builder.setMessage("Do you want to delete "+name);
  81.                 builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
  82.                     public void onClick(DialogInterface dialog, int which) {
  83.                         final File file = new File(name);
  84.                         file.delete();
  85.                         //restart activity now!
  86.                         startActivity(ScriptReceiver.this.getIntent());
  87.                         finish();
  88.                     }
  89.                 });
  90.                 builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
  91.                     public void onClick(DialogInterface dialog, int which) {
  92.                         dialog.dismiss();
  93.                     }
  94.                 });
  95.                 builder.create().show();
  96.                 return true;
  97.                 }
  98.            });
  99.            getListView().setOnItemClickListener(new OnItemClickListener() {
  100.              public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {  
  101.                 final String name = ((TextView)view).getText().toString();
  102.                 AlertDialog.Builder al = new AlertDialog.Builder(ScriptReceiver.this);
  103.                 al.setTitle("Execute Script");
  104.                 al.setIcon(android.R.drawable.ic_dialog_alert);
  105.                 al.setMessage("Do you really want to execute the following script:\n"+name);
  106.                 al.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
  107.                     public void onClick(DialogInterface dialog, int which) {
  108.                         if(name.endsWith(".txt"))runTxtScript(name);
  109.                         else runZipScript(name);
  110.                     }
  111.                 });
  112.                 al.setNegativeButton("No", new DialogInterface.OnClickListener() {
  113.                     public void onClick(DialogInterface dialog, int which) {
  114.                         dialog.dismiss();
  115.                     }
  116.                 });
  117.                 //I always forget this.. -.-
  118.                 al.create().show();
  119.                 }
  120.            });
  121.     }
  122.     private void runZipScript(final String path){
  123.         new Thread(){
  124.             public void run(){
  125.                 usedFromZip = new ArrayList<String>();
  126.                 remove = true;
  127.                 //first unzip the zip archieve.. this method was simply copied from a java tutorial
  128.                 Enumeration entries;
  129.                 ZipFile zipFile;
  130.                 try {
  131.                     zipFile = new ZipFile(path);
  132.                     entries = zipFile.entries();
  133.                     while(entries.hasMoreElements()){
  134.                         ZipEntry entry = (ZipEntry) entries.nextElement();
  135.                         usedFromZip.add(entry.getName());
  136.                         copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream(new FileOutputStream("/sdcard/sgstools/"+entry.getName())));
  137.                     }
  138.                     zipFile.close();
  139.                 } catch (IOException e) { }
  140.                 String scriptPath = "";
  141.                 for(String s: usedFromZip){
  142.                     if(s.endsWith(".txt")){
  143.                         scriptPath = s;
  144.                         break;
  145.                     }
  146.                 }
  147.                 if(scriptPath.length() > 0){
  148.                     final String abc = scriptPath;
  149.                     runOnUiThread(new Runnable(){ //runTxtScript will start a new thread
  150.                         public void run(){
  151.                             runTxtScript("/sdcard/sgstools/"+abc); //if length == 0, no .txt script was found
  152.                         }
  153.                     });
  154.                 }
  155.                 else{
  156.                     runOnUiThread(new Runnable(){
  157.                         public void run() {
  158.                             Toast.makeText(ScriptReceiver.this, "The zip does not contain a valid script file", 1).show();                             
  159.                         }
  160.                     });
  161.                 }  
  162.             }
  163.         }.start();
  164.     }
  165.     private void runTxtScript(final String path){
  166.         //bugfix: reset output before each script
  167.         output = "";
  168.         //do this in a new Thread to put some eyecandy with progressbar and status updates for user
  169.         final ProgressDialog pd = new ProgressDialog(ScriptReceiver.this);
  170.         pd.setCancelable(false);
  171.         //a nice Handler for handling runnables... mainly for ui updates from new thread
  172.         final Handler handler = new Handler();
  173.         //we use this for updating the text in progressdialog
  174.         final Runnable updateText = new Runnable(){
  175.             public void run(){
  176.                 pd.setMessage(output);
  177.             }
  178.         };
  179.         new Thread(){
  180.             public void run(){
  181.                 done = false;
  182.                 //first read all commands in and save them in a string
  183.                 StringBuilder sb = null;
  184.                 try{
  185.                     BufferedReader in = new BufferedReader(new FileReader(path));
  186.                     sb = new StringBuilder();
  187.                     while(in.ready()){
  188.                         sb.append(in.readLine());
  189.                         sb.append("\n");
  190.                     }
  191.                 }
  192.                 catch(Exception e){ }
  193.                 final String commands = sb.toString();                 
  194.                 try {
  195.                     final Process p = Runtime.getRuntime().exec("su");
  196.                     final DataOutputStream out = new DataOutputStream(p.getOutputStream());
  197.                     final BufferedReader inReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
  198.                     final BufferedReader errReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
  199.                     update = new Runnable(){
  200.                         public void run(){
  201.                             //check for new output from inputstream or errorstream
  202.                             try{
  203.                                 //this gets annoying..
  204.                                 while(inReader.ready()){
  205.                                     output += inReader.readLine()+"\n";
  206.                                     handler.post(updateText);
  207.                                 }
  208.                                 while(errReader.ready()){
  209.                                     output += errReader.readLine()+"\n";
  210.                                     handler.post(updateText);
  211.                                 }                                      
  212.                             }
  213.                             catch(Exception e){}
  214.                             if(!done){
  215.                                 //we will come back in 100ms and check again for output/errors
  216.                                 handler.postDelayed(update, 100);
  217.                             }
  218.                         }
  219.                     };
  220.                     handler.post(update);
  221.                     //for convenience we mount /system rw before executing and remount it ro when script is done
  222.                     out.writeBytes("mount -o rw,remount -t rfs /dev/block/st19 /system\n");
  223.                     out.writeBytes(commands);
  224.                     out.close();
  225.                     p.waitFor();
  226.                     //update output that is still waiting in inputstreams
  227.                     while(inReader.ready()){
  228.                         output += inReader.readLine()+"\n";
  229.                         handler.post(updateText);
  230.                     }
  231.                     while(errReader.ready()){
  232.                         output += errReader.readLine()+"\n";
  233.                         handler.post(updateText);
  234.                     }
  235.                 } catch (Exception e) { }
  236.                 done = true;
  237.                 handler.removeCallbacks(update);                       
  238.                 //status update: done!
  239.                 pd.setCancelable(true);
  240.                 output += "\nAll Done! Press back key now";
  241.                 handler.post(updateText);
  242.                 //remove unziped files
  243.                 if(remove){
  244.                     for(String s: usedFromZip){
  245.                         final File f = new File("/sdcard/sgstools/"+s);
  246.                         f.delete();
  247.                     }
  248.                 }
  249.                 //end run method of new thread
  250.             }
  251.         }.start();
  252.         pd.show();
  253.     }
  254.     public void onStop(){
  255.         super.onStop();
  256.         //remount /system to read only
  257.         try {
  258.             Process p = Runtime.getRuntime().exec("su");
  259.             DataOutputStream out = new DataOutputStream(p.getOutputStream());
  260.             out.writeBytes("mount -o ro,remount -t rfs /dev/block/st19 /system\n");
  261.             out.flush();
  262.             out.close();
  263.         } catch (IOException e) { }    
  264.     }
  265.     public boolean onKeyDown(int keycode, KeyEvent event){
  266.         if(keycode == KeyEvent.KEYCODE_MENU){
  267.             menu.showOrDismiss();
  268.             return true;
  269.         }
  270.         if(keycode == KeyEvent.KEYCODE_BACK){
  271.             finish();
  272.         }
  273.         return false;
  274.     }
  275.     //copied from java unzip tutorial
  276.     public static final void copyInputStream(InputStream in, OutputStream out)
  277.     throws IOException
  278.     {
  279.       byte[] buffer = new byte[1024];
  280.       int len;
  281.  
  282.       while((len = in.read(buffer)) >= 0)
  283.         out.write(buffer, 0, len);
  284.  
  285.       in.close();
  286.       out.close();
  287.     }
  288. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement