在两个线程中使用getApplicationContext()

时间:2013-12-04 17:24:09

标签: java android multithreading

我有一个主要课程“A”。这会调用类“B”中的方法。在A类中,我将参数getAplicationContext()传递给B中的方法。

“B”类中的方法是tempContext是Context对象(Global):

    public void backit(Context con) throws Exception {                
    tempContext = con;
            Completion perThread;
    perThread = new Completion();

    perThread.start();

}

完成类是:

public class Completion extends Thread {
        ProgressDialog progDialog;
        int maxvalue;

        public void run() {
            maxvalue = BackupOperation.con_num;
            progDialog = new ProgressDialog(tempContext);               
            Log.d("TEST", "HELLO");
        }

    }

我的申请人关闭。除外:

12-04 22:41:28.984: W/dalvikvm(19517): threadid=10: thread exiting with uncaught exception (group=0x40af3228)
12-04 22:41:29.104: E/AndroidRuntime(19517): FATAL EXCEPTION: Thread-15840
12-04 22:41:29.104: E/AndroidRuntime(19517): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
12-04 22:41:29.104: E/AndroidRuntime(19517):    at android.os.Handler.<init>(Handler.java:121)
12-04 22:41:29.104: E/AndroidRuntime(19517):    at android.app.Dialog.<init>(Dialog.java:127)
12-04 22:41:29.104: E/AndroidRuntime(19517):    at android.app.AlertDialog.<init>(AlertDialog.java:114)
12-04 22:41:29.104: E/AndroidRuntime(19517):    at android.app.AlertDialog.<init>(AlertDialog.java:98)
12-04 22:41:29.104: E/AndroidRuntime(19517):    at android.app.ProgressDialog.<init>(ProgressDialog.java:77)

当我在线程中引用它时,我可以弄明白tempContext,我的申请人关闭了。关于如何在该线程中获取应用程序上下文的任何建议?

1 个答案:

答案 0 :(得分:0)

请参阅此讨论,了解Activity ContextApplication Context之间的区别: Difference between Activity Context and Application Context

例如,演示ProgressDialoghttp://www.techrepublic.com/blog/software-engineer/androids-indeterminate-progressdialog-tutorial/ (它具有可下载的源代码,可以轻松进行实验。) 它在ProgressDialog方法中显示onClick()。如果你改变了行

pd = new ProgressDialog(context);

使用Activity作为context

pd = new ProgressDialog(getApplicationContext());

它会崩溃。

因此,如果您可以将Activity作为Context传递,那么您应该没问题。