Android:Thread Runnable和Handler

时间:2015-02-19 21:57:52

标签: java android multithreading

我遇到了一个问题,我正在学习android以及如何使用Runnable Thread和Handler来改变UI线程我已经知道如何使用AsynkTask来实现这一点我只是试图学习如何两种方式,问题是我的应用程序冻结然后崩溃我认为解决方案是使用postDelayed但我不知道如何应用它,这就是我提出的:< / p>

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
     //MORE CODEE
    handler();
}

UI线程中的我的处理程序(主要)我在onCreate上调用:

private void handler()
    {
        HandlerMessage = new Handler(){

            @Override
            public void handleMessage(Message msg) {

                Bundle infoBundle = msg.getData();

                int index= infoBundle.getInt(KEY_HANDLER_INDEX);

                switch(index)
                {
                case CHANGE_COLOR:

                    eColors selectedColor = (eColors) infoBundle.getSerializable(KEY_HANDLER_COLOR);
                    myTextViewMain.setBackgroundColor(eColors.enumToColor(selectedColor));
                    myLayoutMain.setBackgroundColor(eColors.enumToColor(selectedColor));

                    break;

                case STARTING_EXECUTION:

                    Toast.makeText(getApplicationContext(), "Handler: Sending SOS...",
                            Toast.LENGTH_SHORT).show();
                    myTextViewMain.setBackgroundColor(Color.WHITE);
                    myLayoutMain.setBackgroundColor(Color.WHITE);

                    break;

                case STOP_EXECUTION:

                    Toast.makeText(getApplicationContext(), "Handler: Cancel SOS...",
                            Toast.LENGTH_SHORT).show();
                    System.out.println("Stop");
                    changeColor(currentColor);

                    break;

                default:
                }

            }

        };
    }

我用什么来创建新线程:

private void workingWithBottle(taskWork work) {

        if(work == taskWork.STOP){

            sosButton.setEnabled(true);
            StingHandler.cancelExecution();

        }else{
            if (work == taskWork.START)
            {
                sosButton.setEnabled(false);
                StingHandler = new handlerMessageInABottle(HandlerMessage);
                StingHandler.run(); 
            }
        }
}

My Runnable在一个单独的文件中:

//handlerMessageInABottle.java
package com.izonfreak.lightadvance;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import com.izonfreak.lightadvance.MainActivity.eColors;

public class handlerMessageInABottle  implements Runnable {

    boolean stopWorking = false;
    Message myMessage;
    Bundle myBundle;
    eColors workColor;
    Handler myHandler;

    private final String KEY_HANDLER_INDEX = "HANDLER_INDEX";
    private final String KEY_HANDLER_COLOR = "HANDLER_COLOR";
    private static final int CHANGE_COLOR=1, STARTING_EXECUTION =2 , STOP_EXECUTION =3;


    handlerMessageInABottle(Handler handler)
    {
        myHandler = handler;

    }
    @Override
    public void run() {
        String mourseMessage = "...---...";
        int i=0, time =0;

        sendToHandler(STARTING_EXECUTION);

        while (true) {

            System.out.println(mourseMessage);

            if(mourseMessage.charAt(i)=='.')
                time = 1000;
            else if (mourseMessage.charAt(i)=='-')
                time = 2000;
            else
                time = 1000;

            i++;

            //sendVisualMessage(time);

            if (stopWorking)break;

            if(i>=mourseMessage.length())i=0;
        }

        sendToHandler(STOP_EXECUTION);

    }

    private void sendToHandler(int action)
    {
        myMessage = myHandler.obtainMessage();
        myBundle = new Bundle();
        myBundle.putInt(KEY_HANDLER_INDEX, action);
        myBundle.putSerializable(KEY_HANDLER_COLOR, workColor);
        myMessage.setData(myBundle);
        myHandler.sendMessage(myMessage);
    }

    private void sendVisualMessage(int duration)
    {
        workColor = eColors.eBLACK;
        sendToHandler(CHANGE_COLOR);

        //myHandler.postDelayed(this, duration);

        workColor = eColors.eWHITE;
        sendToHandler(CHANGE_COLOR);
    }

    public void cancelExecution()
    {
        stopWorking= true;
    }

}

我知道线程正在工作,因为我在LogCat中看到一些输出(&#34; ... --- ...&#34;)当应用程序崩溃时,我在LogCat中得到以下内容: / p>

02-19 21:52:28.715: I/System.out(615): ...---...
02-19 21:52:28.715: I/System.out(615): ...---...
02-19 21:52:28.715: I/System.out(615): ...---...
02-19 21:52:28.715: I/System.out(615): ...---...
02-19 21:52:28.735: W/ActivityManager(58):   Force finishing activity com.izonfreak.lightadvance/.MainActivity
02-19 21:52:28.735: I/ActivityManager(58): Killing com.izonfreak.lightadvance (pid=615): user's request
02-19 21:52:28.735: I/Process(58): Sending signal. PID: 615 SIG: 9
02-19 21:52:28.805: I/WindowManager(58): WIN DEATH: Window{460e7a60 Toast paused=false}
02-19 21:52:28.815: I/WindowManager(58): WIN DEATH: Window{460a8f38 com.izonfreak.lightadvance/com.izonfreak.lightadvance.MainActivity paused=true}
02-19 21:52:28.815: I/ActivityManager(58): Process com.izonfreak.lightadvance (pid 615) has died.
02-19 21:52:28.865: W/InputManagerService(58): Got RemoteException sending setActive(false) notification to pid 615 uid 10037

就是这样......我整天都被困在这部分x_x。

1 个答案:

答案 0 :(得分:0)

您实际上并没有创建单独的线程。您的runnable直接在主线程的上下文中运行。因此,它位于主线程的紧密循环中,由于ANR,Android会杀死应用程序。