문제

I have this problem in android. i have a main activity who calls a thread with this

   Runnable work = new Runnable() {

    public void run() {
        while (kill) {
            try {
                Thread.sleep(5000);
                connect();
                } catch (InterruptedException ex) {
                Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
            }
        }


    }
};

kill its a public boolean in MainActivity. what can i do to save the thread so when i resume the activity i still can kill the thread?

도움이 되었습니까?

해결책

I think you want to do something closer to what this solution proposes.

However, if you really want to keep doing it in a Thread, then I suggest you extend a new class from Thread and add a method called killMe(). This will modify the (now private) boolean kill flag. Then, in your onRetainNonConfigurationInstance() you can return this Thread and you can retrieve it again in onResume. If you return and activity has not been killed, then it's fine, you can just call killMe() on the existing Thread.

Example:

 @Override
  public Object onRetainNonConfigurationInstance() {
    return thread;
  }

다른 팁

Why do you want to kill the thread in the resume?

Why not start the thread in the resume part, then put in a finally block to handle the fact that the connect() is interrupted, and then when it starts again you just need to reconnect and do the operation.

In the case of mobile devices, your best bet is to checkmark in some persistent storage where you are, so that if you are interrupted you can continue when the Activity is started again.

You have a high possibility of being interrupted so design for it.

The thread may be killed off by the OS so there is nothing to save and kill later.

If you really need to do something like this then start a RemoteService as that will run in a different process than your Activity and is more likely to stay around.

You may want to look at this question:

Android Remote Service

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top