如何在android中制作无限循环?

时间:2018-05-14 13:06:30

标签: android infinite-loop

我想在我的代码中创建一个while(true)但是,当我运行时,我什么也看不见: 我试过AsyncTask,但我认为无限循环太重了。

public class openActivity extends AppCompatActivity {
 ArrayList<String> myArraylist = new Arraylist<> ();
 CustomAdapter myAdapter;
 ListView list;
 protected void onCreate(Bundle savedInstanceState) {
     setContentView(R.layout.myActivity);
     list = findViewById(R.id.myList);
     try {
         while (true) {
             Document doc = Jsoup.connect(myUrl).get;
             //here i get info i need
             //add that info to myArraylist
             myAdapter = new CustomAdapter(this, myArraylist);
             list.setAdapter(myAdapter);
             myAdapter.notifyDataSetChanged();
             while (myArrayList.get(0).equals(myArraylist.get(0))) {
                 Thread.sleep(900000);
             }
         }
     } catch (Exception ex) {
         ex.getLocalizeMessage()
     }
 }

2 个答案:

答案 0 :(得分:1)

您的循环阻止了UI线程。要执行定期任务,您应使用ScheduledExecutorService

此外,避免在每次迭代时重新创建适配器。更新现有数据并使用DiffUtils通知更改。

答案 1 :(得分:1)

或者你可以试试这个:

myAdapter = new CustomAdapter(this, myArraylist);
list.setAdapter(myAdapter);
getData();

public void getData(){
         Document doc = Jsoup.connect(myUrl).get;
         //here i get info i need
         //add that info to myArraylist
         myAdapter.notifyDataSetChanged();
         getData()
}