使用线程同步绑定服务上的调用

时间:2011-11-22 20:54:58

标签: android multithreading binding service

我在Android中使用BoundService时遇到了问题。

我有一个包装器,它作为一个BoundService的客户端,应该有一个send方法,它绑定到一个服务,向它发送一条消息并返回从服务返回的一个答案。

它的行为应该是这样的:

public Object send(Object toSend)
{   
    //bind to service
    //send the Object
    //return the answer
}

我仍然试图让它发挥作用。我试图使用线程和同步块,但我仍然卡住了。代码现在看起来像这样:

public class Wrapper{

private static Context context;
private Object objToSend;
private Object obj = new Object();

private Messenger mService = new Messenger(new Handler());
final Messenger mMessenger = new Messenger(new IncomingHandler());

class IncomingHandler extends Handler {
    @Override
    public void handleMessage(Message msg) {

                synchronized (obj) {
                    obj = msg.obj;
                    obj.notify();
                }
        }
    }
}

private ServiceConnection mConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
            mService = new Messenger(service);

            Message msg = Message.obtain();
            msg.obj = objToSend;
            msg.replyTo = mMessenger;
            try {
                mService.send(msg);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
    }

    public void onServiceDisconnected(ComponentName className) {
        Log.d(TAG,"Service disconnected, IBinder");
        mService = null;
    }
};

public Wrapper(Context callerContext)
{
    context = callerContext;
}

public void bind(String action)
{
    Intent intent = new Intent(action);
    context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}

class MyThread extends Thread {
    private String action;

    public MyThread (String action)
    {
        this.action = action;
    }

    public void run() {
            bind(action);
    }
}

public Object send(Object toSend, String action)
{   
    objToSend = toSend;
    synchronized (obj) {
        try {
            new MyThread(action).start();
            obj.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return obj;
    }
}
}

对于调用send,我尝试在单独的Thread中使用它,如果我不调用onServiceConnected,尽管调用了Service的onBind()。

new Thread(){
        public void run()
        {
            Object obj = new Wrapper(getApplicationContext()).send("test","MyServiceAction");
        }
    }.start();

我在obj.notify()行上收到以下异常。

12-15 20:50:10.859: E/AndroidRuntime(22884): Uncaught handler: thread main exiting due to uncaught exception
12-15 20:50:10.859: E/AndroidRuntime(22884): java.lang.IllegalMonitorStateException: object not locked by thread before notify()
12-15 20:50:10.859: E/AndroidRuntime(22884): at java.lang.Object.notify(Native Method)
12-15 20:50:10.859: E/AndroidRuntime(22884): at de.Wrapper$IncomingHandler.handleMessage(Wrapper.java:57)

....

在send-method的synchronized块之前启动mThread会产生相同的错误。

0 个答案:

没有答案