1

我是 Java 新手,我正在编写我的第一个 Thread 用于上传应用程序作为备份。我从一个例子中得到了这段代码,我做了一些改变。

我需要检查布尔值是否存在(如果文件存在),如果不存在,则中断线程并将活动更改为错误显示,我正在尝试但它没有工作。它引发了异常,我的应用程序崩溃了。我该如何解决?

谢谢大家。

Thread threadMenu =  new Thread(new Runnable() {
public void run() {
    runOnUiThread(new Runnable () {
        public void run() {
            /*
            messageText.setText("uploading started.....");
            ProgressDialog progress = new ProgressDialog(null, serverResponseCode);
            progress.setTitle("Loading");
            progress.setMessage("Wait while loading...");
            progress.show();
            */
        }
    });


    File folder = new File(Environment.getExternalStorageDirectory().toString() + myfolder);

    File dir = new File(folder.toString());
    boolean exists = dir.exists();


    uploadFile(folder + "/My_File.png");

    //IF NOT FILES REDIRECT TO NO FILES ACTIVITY



    if (!exists) {

        try {
            //Log.v("ARCHIVOS NO ENCONTRADOS", folder.toString());
            Intent i=new Intent(UploadToServer.this, NoFiles.class);
            startActivity(i);


            } catch (InterruptedException e) {
            // We've been interrupted: no more messages.
            return;
        }


        // Thread.currentThread().interrupt();
        Log.v("ARCHIVOS NO ENCONTRADOS", folder.toString());
        Intent i=new Intent(UploadToServer.this, NoFiles.class);
        startActivity(i);
        Thread.currentThread().interrupt();
    }

    Thread.currentThread().interrupt();
}

});
threadMenu.start();

} 

这是 Logcat 的输出 -> 当线程停止时因为我退出了 Sd 卡。

10-20 23:50:44.158: W/dalvikvm(16441): threadid=1: thread exiting with uncaught exception (group=0x40018578)
10-20 23:50:44.166: E/AndroidRuntime(16441): FATAL EXCEPTION: main
10-20 23:50:44.166: E/AndroidRuntime(16441): java.lang.NullPointerException
10-20 23:50:44.166: E/AndroidRuntime(16441):    at com.uploadtoserver.UploadToServer.uploadFile(UploadToServer.java:149)
10-20 23:50:44.166: E/AndroidRuntime(16441):    at com.uploadtoserver.UploadToServer$1$1.run(UploadToServer.java:105)
10-20 23:50:44.166: E/AndroidRuntime(16441):    at android.os.Handler.handleCallback(Handler.java:587)
10-20 23:50:44.166: E/AndroidRuntime(16441):    at android.os.Handler.dispatchMessage(Handler.java:92)
10-20 23:50:44.166: E/AndroidRuntime(16441):    at android.os.Looper.loop(Looper.java:130)
10-20 23:50:44.166: E/AndroidRuntime(16441):    at android.app.ActivityThread.main(ActivityThread.java:3687)
10-20 23:50:44.166: E/AndroidRuntime(16441):    at java.lang.reflect.Method.invokeNative(Native Method)
10-20 23:50:44.166: E/AndroidRuntime(16441):    at java.lang.reflect.Method.invoke(Method.java:507)
10-20 23:50:44.166: E/AndroidRuntime(16441):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
10-20 23:50:44.166: E/AndroidRuntime(16441):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
10-20 23:50:44.166: E/AndroidRuntime(16441):    at dalvik.system.NativeStart.main(Native Method)
4

1 回答 1

1

这里要了解的主要内容是,您不能从后台线程调用 startActivity() 方法,因为它可能会导致奇怪的竞争条件。相反,您需要向主线程的消息队列发布一个 runnable,以便在主线程上执行。

像这样更新你的 onCreate 方法

   Thread threadMenu;
    Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        handler = new Handler();
        threadMenu = new Thread(runnable);
        threadMenu.start();

    }

并在您的 onCreate 结束后编写此代码

Runnable runnable = new Runnable() {

        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                public void run() {

                    // messageText.setText("uploading started.....");
                    // ProgressDialog progress = new ProgressDialog(null,
                    // serverResponseCode);
                    // progress.setTitle("Loading");
                    // progress.setMessage("Wait while loading...");
                    // progress.show();

                }
            });

            File folder = new File(Environment.getExternalStorageDirectory()
                    .toString() + "myfolder");

            File dir = new File(folder.toString());
            boolean exists = dir.exists();
            System.out.println("boolean value is " + exists);

            // uploadFile(folder + "/My_File.png");

            // IF NOT FILES REDIRECT TO NO FILES ACTIVITY

            if (!exists) {

                // Thread.currentThread().interrupt();
                Log.v("ARCHIVOS NO ENCONTRADOS", folder.toString());




                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        Intent i = new Intent(UploadToServer.this, NoFiles.class);
                        startActivity(i);

                        threadMenu.stop();
                    }
                });

            }


        }
    };

我建议你应该使用 AsyncTask 除了 android 中的线程,这是 android 推荐的。更多关于线程和 Asynctask 的信息可以在这里找到。

于 2013-10-21T06:12:11.033 回答