开发者

sleep/wait in android apps

I had an activity which calls a thread for 10times one after another. However, if the network is slow or too much information loaded, force close will occur. Will adding sleep in each thread help to solve this problem? or is there any other ways to solve it?

   public void run() {
         if(thread_op.equalsIgnoreCase("xml")){
              readXML();
         }
         else if(thread_op.equalsIgnoreCase("getImg")){
              getWallpaperThumb();
         }
         handler.sendEmptyMessage(0);
    }

    private Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                    int count = 0;
                    if (!myExampleHandler.filenames.isEmpty()){
                          count = myExampleHandler.filenames.size();
                    }
                    count = 5;
                    if(thread_op.equalsIgnoreCase("xml")){
                            pd.dismiss();
                            thread_op = "getImg";
                            btn_more.setBackgroundResource(R.drawable.btn_more);

                    }
                    else if(thread_op.equalsIgnoreCase("getImg")){
                            setWallpaperThumb();
                            index++;
                            if (index < count){
                                    Thr开发者_StackOverflow中文版ead thread = new Thread(GalleryWallpapers.this);
                                    thread.start();

                            }
                    }
            }
    };


First step should be to check the stack trace which will give the offending line and cause. You can use Logcat for that.


Are you getting the Application not responding dialog (ANR) or does your app force close?

ANR appears when the UI looper thread takes too long to return from a call. Having 10 or 100 threads should not cause any problem as long as the handleMessage function returns in a timely fashion.

If you really want to limit the number of threads that should be running in one go look up ExecutorService

ExecutorService executorService = Executors.newFixedThreadPool(5);
    executorService.submit(new Runnable() {
        public void run() {
            // This is your thread
        }
    });

You can submit all 10 jobs to the executor service and they'll run one after another with a maximum of 5 running simultaneously.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜