简体   繁体   English

从线程启动android活动

[英]Starting an android activity from a thread

What i am trying to do over here is that I want to call a webservice and based on its response i might invoke another webservice or start an activity.I am already writing the web service in a separate thread but the issue is that i am calling the activity in a worker thread, To make myself more clear i have put my pseudo code . 我要在这里做的是我想调用一个Web服务,并根据其响应我可能调用另一个Web服务或启动一个活动。我已经在一个单独的线程中编写了Web服务,但是问题是我正在调用为了使自己更加清楚,我将自己的伪代码放在了工作线程中。

if (User ID and Password present in the shared preference) THEN 
                 Utils.checkauthorisation(API)   //Web Service Call
                 if(respsonse is Paswordexpired)
                    erase password from DB
                    Goto (LOGIN SCREEN)
                 else if( download of images hasn't happened today) ) THEN
                        UTILS.DownloadImages//Web service call
                        if(response==connectivityorOtherError)
                            Toast respective Message
                            GOTO (GALLERY SCREEN)
                        else if (response==confilicted Data)
                            Goto (CHANGES SCREEN)
                        endif
                endif
endif

I was planning to show a progress bar and do all these events in a thread like this 我打算显示一个进度条,并在这样的线程中执行所有这些事件

  progressDialog = ProgressDialog.show(this, "Loading",
                "Authenticating Please wait.");

     new Thread() {
        public void run() {

        ///execute the pseudo code

        Message msg = Message.obtain();
        msg.what = 1;
        messagHandler.sendMessage(msg);
        }

    }.start();



            private static Handler messagHandler = new Handler() {
    public void handleMessage(Message message) {
        super.handleMessage(message);
        switch (message.what) {
        case 1:
            progressDialog.dismiss();
            break;
        default:
            break;
        }
    }

};

But something that disturbs me is that I have to start an activity in a worker thread here. 但令我不安的是,我必须此处的工作线程中启动活动 Is this good practice? 这是好习惯吗? I initially thought that we could only start an activity from the UI thread. 我最初以为我们只能从UI线程开始活动。 What is the process happening in the back end here(in the thread sense)? 在此后端(线程意义上)正在发生什么过程? If this is not a good practice what are the other alternatives to implement my pseudocode ? 如果这不是一个好习惯,那么还有什么其他方法可以实现我的伪代码呢?

Thanks 谢谢

Launch the intent with a message to the Handler not on your worker Thread. 通过不在工作线程上的消息向处理程序启动意图。 Handlers are run on the UI thread. 处理程序在UI线程上运行。 If they were not, you would not be able to update UI elements in a Handler. 如果不是,则将无法更新处理程序中的UI元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM