【问题标题】:Start an activity from the thread从线程启动一个活动
【发布时间】:2012-12-08 17:09:23
【问题描述】:

我有一个生成 pdf 文件的类。 这个类是由Activity扩展的,也就是说有onCreate、onPause(等等)方法。

生成 pdf 文件需要一些时间,因此我需要显示一个进度条来通知用户文件正在生成。

一切正常,当我单击生成按钮时,进度条会冻结几秒钟(根据 Logcat:文件生成时进度条冻结)。

所以我的问题是,我不知道如何在文件生成时使进度条无法停止。

下面是我的代码:

Log.i(TAG, "PDF generation: " + position);

final ProgressDialog dialog = new ProgressDialog(this);
dialog.setCancelable(true);
dialog.setIndeterminate(true);
dialog.setMessage("Generating...");
dialog.show();

new Thread(new Runnable() {

    @Override
    public void run() {

        startActivity(new Intent(getApplicationContext(),
            PdfGenerator.class));

        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                dialog.hide();
            }
        });

    }

}).start();

【问题讨论】:

    标签: java android multithreading


    【解决方案1】:

    将代码更改为使用 runOnUiThread 从 Thread 启动 Activity:

    ///... your code here..
    
        new Thread(new Runnable() {
    
            @Override
            public void run() {
    
                Your_Current_Activity.this.runOnUiThread(new Runnable() {
    
                    @Override
                    public void run() {
    
                    dialog.cancel();
    
                    // START ACTIVITY HERE
                   Your_Current_Activity.this.startActivity(new 
                            Intent(Your_Current_Activity.this,
                                           PdfGenerator.class));
    
                    }
                });
    
            }
    
        }).start();
    

    【讨论】:

    • 现在看起来不错,但我做了一些更改。我已将 dialog.hide() 更改为 dialog.cancel() 并在开始新活动后移动。还是谢谢!
    • @juliuks : 但是runOnUiThread 是 Activity 类的方法,那么如果不使用 Activity 上下文就无法访问它。最欢迎朋友 :)
    • 我想你不明白我做了什么改变。顺便说一句,代码现在看起来像:pastebin.com/fxB1Zz9i
    • @juliuks : 是的,你做得对,记住一点Stats.this 在你想访问runOnUiThread 时很重要
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-31
    • 1970-01-01
    相关资源
    最近更新 更多