Java 让异步任务开始工作

Java 让异步任务开始工作,java,android,function,android-asynctask,Java,Android,Function,Android Asynctask,我正在尝试启动一个异步任务 但是当我运行应用程序时,acctivity崩溃了 我的任务: private class HideTask extends AsyncTask<String, Void, String> { protected void onPreExecute() { //loader.show(); } protected void onPostExecute(String result) { //load

我正在尝试启动一个异步任务

但是当我运行应用程序时,acctivity崩溃了

我的任务:

private class HideTask extends AsyncTask<String, Void, String> {


    protected void onPreExecute() {
        //loader.show();
    }

    protected void onPostExecute(String result) {
        //loader.dismiss();
    }

    @Override
    protected String doInBackground(String... params) {
        //hide();
        return "done";
    }


}
日志:

02-11 19:36:24.799:E/AndroidRuntime(17870):致命异常:main 02-11 19:36:24.799:E/AndroidRuntime(17870):java.lang.RuntimeException:无法实例化活动组件信息{folder.hide.alexander.fuchs/folder.hide.alexander.fuchs.App}:java.lang.IllegalStateException:onCreate()之前的活动无法使用系统服务 02-11 19:36:24.799:E/AndroidRuntime(17870):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1573) 02-11 19:36:24.799:E/AndroidRuntime(17870):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667) 02-11 19:36:24.799:E/AndroidRuntime(17870):在android.app.ActivityThread.access$1500(ActivityThread.java:117) 02-11 19:36:24.799:E/AndroidRuntime(17870):在android.app.ActivityThread$H.handleMessage(ActivityThread.java:935) 02-11 19:36:24.799:E/AndroidRuntime(17870):在android.os.Handler.dispatchMessage(Handler.java:99)上 02-11 19:36:24.799:E/AndroidRuntime(17870):在android.os.Looper.loop(Looper.java:130) 02-11 19:36:24.799:E/AndroidRuntime(17870):在android.app.ActivityThread.main(ActivityThread.java:3691)上 02-11 19:36:24.799:E/AndroidRuntime(17870):位于java.lang.reflect.Method.Invokenactive(本机方法) 02-11 19:36:24.799:E/AndroidRuntime(17870):位于java.lang.reflect.Method.invoke(Method.java:507) 02-11 19:36:24.799:E/AndroidRuntime(17870):在com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907) 02-11 19:36:24.799:E/AndroidRuntime(17870):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665) 02-11 19:36:24.799:E/AndroidRuntime(17870):在dalvik.system.NativeStart.main(本机方法) 02-11 19:36:24.799:E/AndroidRuntime(17870):原因:java.lang.IllegalStateException:onCreate()之前的活动无法使用系统服务 02-11 19:36:24.799:E/AndroidRuntime(17870):位于android.app.Activity.getSystemService(Activity.java:3562) 02-11 19:36:24.799:E/AndroidRuntime(17870):在android.app.Dialog.(Dialog.java:141) 02-11 19:36:24.799:E/AndroidRuntime(17870):在android.app.AlertDialog.(AlertDialog.java:63) 02-11 19:36:24.799:E/AndroidRuntime(17870):在android.app.ProgressDialog.(ProgressDialog.java:80) 02-11 19:36:24.799:E/AndroidRuntime(17870):在android.app.ProgressDialog.(ProgressDialog.java:76) 02-11 19:36:24.799:E/AndroidRuntime(17870):在android.app.ProgressDialog.show(ProgressDialog.java:101)上 02-11 19:36:24.799:E/AndroidRuntime(17870):在android.app.ProgressDialog.show(ProgressDialog.java:90)上 02-11 19:36:24.799:E/AndroidRuntime(17870):位于folder.hide.alexander.fuchs.App.(App.java:58) 02-11 19:36:24.799:E/AndroidRuntime(17870):位于java.lang.Class.newInstanceImpl(本机方法) 02-11 19:36:24.799:E/AndroidRuntime(17870):位于java.lang.Class.newInstance(Class.java:1409) 02-11 19:36:24.799:E/AndroidRuntime(17870):在android.app.Instrumentation.newActivity(Instrumentation.java:1021)上 02-11 19:36:24.799:E/AndroidRuntime(17870):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1565) 02-11 19:36:24.799:E/AndroidRuntime(17870):。。。还有11个

公共类应用程序扩展活动实现OnClickListener{
私人按钮;
私人按钮选项;
私人编辑文本;
私有文本视图文件夹\u至\u隐藏;
对话进程;
字符串隐藏或显示;
字符串密码;
串通;
字符串目录;
ProgressDialog loader=ProgressDialog.show(App.this,“”,
“正在加载。请稍候…”,正确);
/**在首次创建活动时调用*/
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//按钮;
按钮=(按钮)findViewById(R.id.button1);
setOnClickListener(此);
选项=(按钮)findViewById(R.id.button2);
options.setOnClickListener(此选项);
//编辑文本编辑文本
edittext=(edittext)findViewById(R.id.editText1);
//TextView文件夹要隐藏;
文件夹_to_hide=(TextView)findViewById(R.id.textView1);
init();
对话框();
速率();
}
私有类HideTask扩展异步任务{
受保护的void onPreExecute(){
//loader.show();
}
受保护的void onPostExecute(字符串结果){
//loader.discouse();
}
@凌驾
受保护的字符串doInBackground(字符串…参数){
//隐藏();
返回“完成”;
}
}
公共void init(){
尝试
{
布尔exists2=(新文件(“/data/data/folder.hide.alexander.fuchs/folder.db”)).exists();
如果(存在2){
setText(反序列化字符串(“/data/data/folder.hide.alexander.fuchs/folder.db”);
}
否则{
edittext.setText(“/sdcard/Hide”);
createfolder(“/sdcard/Hide”);
}
布尔存在=(新文件(“/data/data/folder.hide.alexander.fuchs/hide.db”)).exists();
如果(存在){
edittext.setVisibility(View.INVISIBLE);
文件夹\u到\u hide.setVisibility(视图不可见);
隐藏或显示=“显示”;
按钮设置文本(“显示”);
}否则{
隐藏或显示=“隐藏”;
按钮设置文本(“隐藏”);
}
}
捕获(异常x)
{
}
}
公用void createfolder(字符串路径){
尝试
{
新文件(路径).mkdirs();
}
捕获(异常x)
{
完成();
}
}
//删除目录下的所有文件和子目录。
//如果所有删除都成功,则返回true。
//如果删除失败,该方法将停止尝试删除并返回false。
公共静态布尔deleteDir(文件目录){
if(dir.isDirectory()){
String[]children=dir.list();
对于(int i=0;i 0){
out.write(缓冲区,0,长度);
}
in.close();
out.close();
系统
HideTask task = new HideTask();
    task.execute(new String[] { "" });
public class App extends Activity implements OnClickListener {

private Button button;
private Button options;
private EditText edittext;
private TextView folder_to_hide;
Dialog progress;
String hide_or_show;
String password;
String pass;
String directory;

ProgressDialog loader = ProgressDialog.show(App.this, "", 
        "Loading. Please wait...", true);



/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


 // Button button;
    button = (Button) findViewById(R.id.button1);
   button.setOnClickListener(this);

   options = (Button) findViewById(R.id.button2);
   options.setOnClickListener(this);

   // EditText edittext
  edittext = (EditText) findViewById(R.id.editText1);

  //TextView folder_to_hide;
  folder_to_hide = (TextView) findViewById(R.id.textView1);

   init();
   dialog();
   rate();
}
private class HideTask extends AsyncTask<String, Void, String> {


    protected void onPreExecute() {
        //loader.show();
    }

    protected void onPostExecute(String result) {
        //loader.dismiss();
    }

    @Override
    protected String doInBackground(String... params) {
        //hide();
        return "done";
    }


}







public void init() {
    try
    {
    boolean exists2 = (new File("/data/data/folder.hide.alexander.fuchs/folder.db")).exists();
    if (exists2) {
        edittext.setText(deserializeString("/data/data/folder.hide.alexander.fuchs/folder.db"));
    }
    else {
        edittext.setText("/sdcard/Hide");
        createfolder("/sdcard/Hide");
    }
    boolean exists = (new File("/data/data/folder.hide.alexander.fuchs/hide.db")).exists();
    if (exists) {
        edittext.setVisibility(View.INVISIBLE);
        folder_to_hide.setVisibility(View.INVISIBLE);
        hide_or_show = "show";
        button.setText("Show");
    } else {
        hide_or_show = "hide";
        button.setText("Hide");
    }
    }
        catch(Exception x)
        {


        }
    }


public void createfolder(String path) {

    try
    {
        new File(path).mkdirs(); 
    }
        catch(Exception x)
    {
            finish();
    }
}


// Deletes all files and subdirectories under dir.
// Returns true if all deletions were successful.
// If a deletion fails, the method stops attempting to delete and returns false.
public static boolean deleteDir(File dir) {
 if (dir.isDirectory()) {
     String[] children = dir.list();
     for (int i=0; i<children.length; i++) {
         boolean success = deleteDir(new File(dir, children[i]));
         if (!success) {
             return false;
         }
     }
 }

 // The directory is now empty so delete it
 return dir.delete();
  }
    /**
       public void copyDirectory(File sourceLocation , File targetLocation)
        throws IOException {

            if (sourceLocation.isDirectory()) {
                if (!targetLocation.exists()) {
                    targetLocation.mkdir();
                }

                String[] children = sourceLocation.list();
                for (int i=0; i<children.length; i++) {
                    copyDirectory(new File(sourceLocation, children[i]),
                            new File(targetLocation, children[i]));
                }
            } else {

                InputStream in = new FileInputStream(sourceLocation);
                OutputStream out = new FileOutputStream(targetLocation);

                // Copy the bits from instream to outstream
                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                in.close();
                out.close();
            }
        }
        **/
         public static void copyFolder(File src, File dest)
        throws IOException{

        if(src.isDirectory()){

            //if directory not exists, create it
            if(!dest.exists()){
               dest.mkdir();
               System.out.println("Directory copied from " 
                              + src + "  to " + dest);
            }

            //list all the directory contents
            String files[] = src.list();

            for (String file : files) {
               //construct the src and dest file structure
               File srcFile = new File(src, file);
               File destFile = new File(dest, file);
               //recursive copy
               copyFolder(srcFile,destFile);
            }

        }else{
            //if file, then copy it
            //Use bytes stream to support all file types
            InputStream in = new FileInputStream(src);
                OutputStream out = new FileOutputStream(dest); 

                byte[] buffer = new byte[1024];

                int length;
                //copy the file content in bytes 
                while ((length = in.read(buffer)) > 0){
                   out.write(buffer, 0, length);
                }

                in.close();
                out.close();
                System.out.println("File copied from " + src + " to " + dest);
        }
    }

     @Override
     public void onClick(View v) {

if (v == button)
{

try
{

    directory = edittext.getText().toString();
    FileWriter fstream = new FileWriter("/data/data/folder.hide.alexander.fuchs/folder.db");
    BufferedWriter out = new BufferedWriter(fstream);
    out.write(directory);
    //Close the output stream
    out.close();
if(hide_or_show == "hide")
{


    HideTask task = new HideTask();
    task.execute(new String[] { "http://www.vogella.de" });



    edittext.setVisibility(View.INVISIBLE);
    folder_to_hide.setVisibility(View.INVISIBLE);



}
else
{   


    show();
    edittext.setVisibility(View.VISIBLE);
    folder_to_hide.setVisibility(View.VISIBLE);


}
    }
catch(Exception x)
{       
    String ErrorMessage = x.getMessage();
    Toast.makeText(this,"Error"+ErrorMessage, Toast.LENGTH_LONG).show();
    finish();
}
}
if (v == options)
{
    final CharSequence[] items = {"Change password", "http://www.alexander-fuchs.net/", "Market"};

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Options");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {

            if (items[item] == "Change password")
            {
                createpass();

            }
            if (items[item] == "http://www.alexander-fuchs.net/")
            {
            intentstarter(items[item].toString());
           toaster(items[item].toString());
            }
            if (items[item] == "Market")
            {
            intentstarter("market://search?q=pub:Alexander Fuchs");
            toaster("Please wait...");
            }
        }
    });
    AlertDialog alert = builder.create();
    alert.show();
}
    }
public void hide() {

    try
    {





    FileWriter fstream = new FileWriter("/data/data/folder.hide.alexander.fuchs/hide.db");
    BufferedWriter out = new BufferedWriter(fstream);
    out.write("hide");
    //Close the output stream
    out.close();


    File copy = new File(directory);
    File target = new File("/data/data/folder.hide.alexander.fuchs/Hide");
    copyFolder(copy,target);

    deleteDir(copy);

    hide_or_show = "show";
    button.setText("Show");


    }
    catch(Exception x)
    {   
        edittext.setVisibility(View.VISIBLE);
        folder_to_hide.setVisibility(View.VISIBLE);
        File copy = new File("/data/data/folder.hide.alexander.fuchs/folder.db");
        deleteDir(copy);
        copy = new File("/data/data/folder.hide.alexander.fuchs/hide.db");
        deleteDir(copy);
        String ErrorMessage = x.getMessage();
        Toast.makeText(this,"Error", Toast.LENGTH_LONG).show();
        finish();
    }

}
    public void show() {

    try
    {

        File delete = new File("/data/data/folder.hide.alexander.fuchs/hide.db");
        deleteDir(delete);

        File target = new File(directory);
        File copy = new File("/data/data/folder.hide.alexander.fuchs/Hide");
        copyFolder(copy,target);

        deleteDir(copy);

        hide_or_show = "hide";
        button.setText("Hide");
    }
    catch(Exception x)
    {       
        String ErrorMessage = x.getMessage();
        Toast.makeText(this,"Error", Toast.LENGTH_LONG).show();
        finish();
    }

}
public void dialog() {
//set up dialog
final Dialog dialog = new Dialog(App.this);
dialog.setContentView(R.layout.dialoglayout);
dialog.setTitle("Password");
dialog.setCancelable(false);
//there are a lot of settings, for dialog, check them all out!

//set up text
final EditText text = (EditText) dialog.findViewById(R.id.editText1);
text.setText("");



//set up button
Button button = (Button) dialog.findViewById(R.id.Button01);
button.setOnClickListener(new OnClickListener() {
@Override
    public void onClick(View v) {
    password = text.getText().toString();
    try
    {
    pass = deserializeString("/data/data/folder.hide.alexander.fuchs/password.db");
    }
    catch(Exception x)
    {       
        String ErrorMessage = x.getMessage();
        toaster("Error");
        finish();
    }
    if(password.equals(pass))
    {
    dialog.dismiss();
    }
    else
    {
        toaster("Invalid Password");
        finish();
    }
}
});
//now that the dialog is set up, it's time to show it   
boolean exists = (new File("/data/data/folder.hide.alexander.fuchs/password.db")).exists();
if (exists) {
    dialog.show();
}
else
{
createpass();
}

     }
    public static String deserializeString(String file)
      throws IOException {
          int len;
          char[] chr = new char[4096];
          final StringBuffer buffer = new StringBuffer();
          final FileReader reader = new FileReader(file);
          try {
              while ((len = reader.read(chr)) > 0) {
                  buffer.append(chr, 0, len);
              }
          } finally {
              reader.close();
          }
          return buffer.toString();
      }
   public void toaster(String text) {
Toast.makeText(this,text, Toast.LENGTH_LONG).show();
}

  public void intentstarter(String string) {
String url = string;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
 public void dialogbuilder(String text) {
new AlertDialog.Builder(this).setMessage(
        text).setNeutralButton(
        "OK",
        null).show();
}
public void createpass() {
//set up dialog
final Dialog dialog = new Dialog(App.this);
dialog.setContentView(R.layout.createpass);
dialog.setTitle("Set Password");
dialog.setCancelable(false);
//there are a lot of settings, for dialog, check them all out!

//set up text
final EditText text = (EditText) dialog.findViewById(R.id.editText1);
text.setText("");
//set up text
final EditText text2 = (EditText) dialog.findViewById(R.id.editText2);
text2.setText("");



//set up button
Button button = (Button) dialog.findViewById(R.id.Button01);
button.setOnClickListener(new OnClickListener() {
@Override
    public void onClick(View v) {

    String createpass_password = text.getText().toString().trim();
    String createpass_password2 = text2.getText().toString().trim();


    try
    {
        if(createpass_password.equals(createpass_password2))
        {
            FileWriter fstream = new FileWriter("/data/data/folder.hide.alexander.fuchs/password.db");
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(createpass_password);
            //Close the output stream
            out.close();    
        dialog.dismiss();
        dialogbuilder("Please notice that if you forget your password there is no availability to restore your data !");

        }
        else
        {
            toaster("Passwords are not matching !");
            text.setText("");
            text2.setText("");
        }
    }
    catch(Exception x)
    {       
        String ErrorMessage = x.getMessage();
        toaster("Error");
        finish();
    }

}
});
//now that the dialog is set up, it's time to show it   

    dialog.show();

}
public void rate() {
//set up dialog
final Dialog dialog = new Dialog(App.this);
dialog.setContentView(R.layout.vote);
dialog.setTitle("Like this App ?");
dialog.setCancelable(true);
//there are a lot of settings, for dialog, check them all out!





//Rate
Button button = (Button) dialog.findViewById(R.id.button1);
//Later
Button button2 = (Button) dialog.findViewById(R.id.button2);
//No Thanks
Button button3 = (Button) dialog.findViewById(R.id.button3);

button.setOnClickListener(new OnClickListener() {
@Override
    public void onClick(View v) {
    try
    {
        // /data/data/folder.hide.alexander.fuchs/rate.db
    FileWriter fstream = new FileWriter("/data/data/folder.hide.alexander.fuchs/rate.db");
    BufferedWriter out = new BufferedWriter(fstream);
    out.write("no");
    //Close the output stream
    out.close();
  dialog.dismiss();
    }
    catch (Exception x)
    {

    }
    intentstarter("market://details?id=folder.hide.alexander.fuchs");
    toaster("Please wait...");
    dialog.dismiss();

}
});
button2.setOnClickListener(new OnClickListener() {
    @Override
        public void onClick(View v) {
        // /data/data/folder.hide.alexander.fuchs/rate.db
        File dta = new File("/data/data/folder.hide.alexander.fuchs/rate.db");
        deleteDir(dta);
        dialog.dismiss();
    }
    });
button3.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        try
        {
            // /data/data/folder.hide.alexander.fuchs/rate.db
        FileWriter fstream = new FileWriter("/data/data/folder.hide.alexander.fuchs/rate.db");
        BufferedWriter out = new BufferedWriter(fstream);
        out.write("no");
        //Close the output stream
        out.close();
      dialog.dismiss();
        }
        catch (Exception x)
        {

        }
    }
    });



if (rate.rate() == 3)
{
    dialog.show();
}

}



}
new HideTask().execute();