处理来电时的线程

时间:2011-10-07 04:38:56

标签: android multithreading

目前,我的应用程序从对话框和线程内的服务器获取数据。 发生来电时应该怎么做。 现在我正在这样做。我想知道这种方法是否正确还是其他必须做的事情。

    @Override
protected void onPause() {
    // TODO Auto-generated method stub
    Utility.debugger("PAUSE 1");
    if (ScreenReceiver.wasScreenOn) {  

                    // this is the case when onPause() is called by the system due to a screen state change  
                    Utility.killDialog();

                    System.out.println("SCREEN TURNED OFF");  

                } else {  

                    Utility.debugger("PAUSE 2");

                 // this is when onPause() is called when the screen state has not changed  
     }  

    super.onPause();

}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    Utility.debugger("PAUSE 3");
    if (!ScreenReceiver.wasScreenOn) {  

               // this is when onResume() is called due to a screen state change  

                     System.out.println("SCREEN TURNED ON"); 

                     Utility.debugger("PAUSE 4");
                        Utility.resumeDialog(); 

                } else {  

                     // this is when onResume() is called when the screen state has not changed



            } 

    super.onResume();


}


public static void killDialog()
{
    if(dialog != null || dialog.isShowing() )
    {dialog.dismiss();
        t.interrupt();
        try {
            t.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

public static void resumeDialog()
{
    if(dialog != null  )
    {
        dialog.setIndeterminate(true);
        dialog.show();
        t.run();

    }
}

其中t是线程,对话框是progressDialog。 我也暂停了,恢复是设备进入睡眠状态。

谢谢!

2 个答案:

答案 0 :(得分:0)

看起来你真正要做的就是为用户创建一个对话框。这里有充足的文档:

http://developer.android.com/guide/topics/ui/dialogs.html

这是一个简单的例子:

ProgressDialog progressDialog;
progressDialog = new ProgressDialog(mContext);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Loading...");
progressDialog.show()

如果要停止对话框,请致电

progressDialog.cancel()

如果您对Android上的线程感到好奇,我建议您查看AsyncTask。此类(与Activity.runOnUiThread()结合使用)应该可以处理Android上99%的线程问题。

http://developer.android.com/reference/android/os/AsyncTask.html

答案 1 :(得分:0)

而不是使用Thread使用Asynck Task,它将与android中的Thread相同。有四种方法 1. onPreExecute() 2. doInBackground(String ... arg0) 3. onProgressUpdate(String ... values) 4. onPostExecute(无效结果)

首先在onPreExecute()中启动进度条,然后在doInBackground()下载下载代码,然后在onPostExecute方法中解除进度条。