简体   繁体   English

如何在不冻结我的应用程序的情况下运行循环?

[英]How to run loop without freezing my app?

The loop freezes my app but after it finishes, app works normally. 循环冻结了我的应用程序,但完成后,应用程序可以正常工作。 I tried to run loop in Thread and it worked very well without freezing app. 我尝试在Thread运行循环,并且在不冻结应用程序的情况下效果很好。 But now the problem is that I cant run same loop again if I do the app crashes because we cant restart Thread . 但是现在的问题是,如果我因为应用程序崩溃而无法重启Thread就无法再次运行相同的循环。 I want to run the loop in a way that it doesn't freezes app and could be run again. 我想以不冻结应用程序并且可以再次运行的方式运行循环。 How can I do it? 我该怎么做?

Code in my MainActivity class: 我的MainActivity类中的代码:

protected Thread sendthread;

@Override
protected void onCreate(Bundle savedInstanceState) {

 sendthread = new Thread(new Runnable () {

    @Override
    public void run() {

  for(int i=0;i<amount;i++){

            if  (status == 0){

                break;  

            }

             SmsManager sms = SmsManager.getDefault();
      sms.sendTextMessage(phoneNumber.getText().toString(),null,messagetoSend, null, null);

    }

    }
});


}

Thread is started by a button Thread由一个button启动

start.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

        status = 1;
        sendthread.start();

}

I stop thread by setting status to 0 我通过将status设置为0来停止线程

Try using AsyncTask . 尝试使用AsyncTask Start a progressbar in onPreExecute function and call cancel in onPostExecute . 开始在进度onPreExecute功能,并呼吁cancelonPostExecute Inside doInBackground you can call sleep. doInBackground内部,您可以调用sleep。 This will not crash your app and you will not feel like the app is not responding. 这不会使您的应用程序崩溃,并且您不会觉得该应用程序没有响应。

Create a Runnable, wich will have the code that loops in its run method. 创建一个Runnable,它将在其run方法中具有循环的代码。 Then make a second Runnable that posts to the UI thread. 然后制作第二个Runnable,发布到UI线程。

 Runnable myRunnable = new Runnable() {
     @Override
 public void run() {
       while (testByte == 0) {
            Thread.sleep(1000); // 1 Second delay
            String updateWords = updateAuto(); // make updateAuto() return a string
            myTextView.post(new Runnable() { 
                 @Override
                 public void run() {
                      myTextView.setText(updateWords);
                 });
       }
}

After that you can create your thread using the Runnable and start it Like so: 之后,您可以使用Runnable创建线程并启动它,如下所示:

Thread myThread = new Thread(myRunnable);
myThread.start();

Call the method as many times you want to loop 想要多次循环调用该方法

private void loopInAnotherThread() {
   new Thread(new Runnable() {
       public void run() {
           // Your loop
       }
   }).start();
}

维护布尔值变量以控制内部循环,并保持外部无限循环以阻止线程终止。

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

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