简体   繁体   中英

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. But now the problem is that I cant run same loop again if I do the app crashes because we cant restart 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:

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

start.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

        status = 1;
        sendthread.start();

}

I stop thread by setting status to 0

Try using AsyncTask . Start a progressbar in onPreExecute function and call cancel in onPostExecute . Inside doInBackground you can call 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. Then make a second Runnable that posts to the UI thread.

 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:

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();
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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