开发者

Implement a Thread by providing a new class that extends Thread and overriding its run() method

开发者 https://www.devze.com 2023-03-14 02:40 出处:网络
Implementing a Thread by providing a new class that extends Thread and overriding its run() method is new to me. I\'ve tried all day to get it to work. Here\'s my code:

Implementing a Thread by providing a new class that extends Thread and overriding its run() method is new to me. I've tried all day to get it to work. Here's my code:

/*
 * see http://developer.android.com/reference/java/lang/Thread.html
 */
class threadClass extends Thread {
    private Handler mHandler;
    private Message mMsg;
    // constructor
    public threadClass(Handler handler, Message msg) {
        // do something like save the Handler reference
        mHandler = handler;
        mMsg = msg;
    }
    @Override
    public void run() {
        // do some background processing, call the Handler?
        mHandler.sendMessage(mMsg);
    }
}
public Thread passHandlerToThread(Handler handler) {
    handler.sendEmptyMessage(10);
    Message msg = Message.obtain();
    msg.what = 10;
    Thread thread = new threadClass(handler, msg);
    return thread;
}
private Handler localHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        int what = msg.what;
        if (what == 10) Log.i("localHandler", "what: " + what);
    }
};
public void startThread() {
    Thread thread = passHandlerToThread(localHandler);
    threa开发者_运维知识库d.start();
}

I call startThread() in my LocalService onCreate() but nothing happens. What am I doing wrong? I was expecting localHandler() to be called twice: once in passHandlerToThread() and again in run().


Do something like this:

private final Handler handler = new Handler();
// toast runnables
final Runnable updateTwitterNotification = new Runnable() {
    @Override
    public void run() {
        dismissProgressSpinner();
        Toast.makeText(getBaseContext(), "Tweet sent!", Toast.LENGTH_LONG).show();
    }
};  

final Runnable updateCreateError = new Runnable() {
    @Override
    public void run() {
        Toast.makeText(getBaseContext(), "Tweet error!", Toast.LENGTH_LONG).show();
    }
};

postMessageInThread();


//implementation:
private void postMessageInThread() {
    Thread t = new Thread() {
        @Override
        public void run() {

            try {
                connectToTwitterService() // or whatever
                handler.post(updateTwitterNotification);
            } catch (Exception ex) {
                Log.e(TAG, "Error sending msg", ex);
                handler.post(updateCreateError);
            }
        }
    };
    t.start();
}
0

精彩评论

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