从服务中的线程更新ProgressDialog

时间:2013-08-25 08:53:20

标签: android multithreading android-asynctask android-service android-context

我想从服务中的一个线程增加一个进度对话框,我真的很难做到这一点,这是我的代码请帮帮我。

我尝试了很多不同的方法,包括asyncTask(我有上下文问题) 并尝试使用静态函数,但它无法正常工作, 我对android很新,请在这里解释一下我的问题。

活动

public class MainActivity extends Activity {

ProgressDialog progressBar;

private void showProgrssBar() {

    progressBar.show();
}

private void dismissProgressBar() {

    progressBar.dismiss();
}

private void increaseProgressBar(int total) {

    progressBar.incrementProgressBy(total);
};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
     createProgressBarDialog();

Intent n = new Intent(this, myService.class);
startService(n);

}

private void createProgressBarDialog()
{
    progressBar = new ProgressDialog(this);
    progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    progressBar.setMax(200);
    progressBar.setMessage("Recieving bluetooth data");
    progressBar.setCanceledOnTouchOutside(false);
}

服务:

 public class myService extends Service
{

    private myThread myThread;

    Handler handler = new Handler()
    {
        @Override
        public void handleMessage(android.os.Message msg) 
        {
            int total = msg.getData().getInt("total");

            if (total == -1)
            {
                dismissProgressBar();
            }
            else if (total == 0)
            {
                showProgrssBar();
            }
            else
            {
                increaseProgressBar(total);
            }       
        }   
    };

            @Override
            public int onStartCommand(Intent intent, int flags, int startId)
            {
                myThread = new myThread(handler);
                myThread.start();

                return START_STICKY;
            }

线程

  class myThread extends Thread
    { 
         Handler h;
    int numOfLinesToRead = 220;
    int line = 0;


    public myThread(Handler h)
    {
        this.h = h;
    }

    private void increaseProgressBarOnActivity(int i_MsgType)
    {
         Message msg = h.obtainMessage();
         Bundle b = new Bundle();
         b.putInt("total", i_MsgType);
         msg.setData(b);
         h.sendMessage(msg);
    }

    @Override
    public void run() {
        super.run();
        int increase;
        try
        {
            Thread.sleep(1);
        }
        catch (InterruptedException e)
        {

            e.printStackTrace();
        }
          for (; line < 220; line++) 
            {
               increase = (line*100/numOfLinesToRead);
                if (increase != 0)
                {
                    increaseProgressBarOnActivity(increase);   
                    try
                    {
                        Thread.sleep(90);
                    }
                    catch (InterruptedException e)
                    {

                        e.printStackTrace();
                    }

                }
            }

    }
}

1 个答案:

答案 0 :(得分:1)

  

尽管您已经尝试过 AsyncTask ,但我仍然强烈建议您使用它。

只需查看onProgressUpdate()方法即可。它是为了从AsyncTask更新UI。

以下是它的外观示例:

private class DownloadFilesTask extends AsyncTask<String, Integer, Long> {

    private ProgressDialog progressBar;

    @Override
    protected void onPreExecute(){ 
       super.onPreExecute();
       progressBar= new ProgressDialog(getApplicationContext());
       progressBar.setMessage("Loading...");
       progressBar.show();    
    }

    protected Long doInBackground(String... params) {

       long someLong;
       // do something here with params

       // the Integer variable is used for progress
       publishProgress(i);
       // call it for example while downloading a file

       return someLong;
    }

    // this is called whenever you call puhlishProgress(Integer)
    protected void onProgressUpdate(Integer... progress) {
         progressBar.incrementProgressBy(progress[0]);
    }

    // the onPostexecute method receives the return type of doInBackGround()
    protected void onPostExecute(Long result) {
       // do something with the result
       progressBar.dismiss();
   }
}

你说你的问题是获得了上下文。好吧:ServiceContext

因此,您只需使AsyncTask成为服务的内部类,然后使用其上下文。