从android中的处理程序返回值

时间:2016-02-11 20:20:06

标签: java android android-handler

您好我将测试服务中的处理程序消息传递给测试活动。有什么办法可以将对象从TestActivity返回到Testservice类。或者有更简单的方法来做到这一点。

public class TestService {
    public Handler testResultsHandler;

    private BooleanstoreTestResults(String message) {
        if (testResultsHandler != null)

        {
            Message message = testResultsHandler.obtainMessage();
            message.obj = "refresh";
            testResultsHandler.sendMessage(message);
        }
    }
}


public class TestActivity extends Activity {
    private TestService testService = new TestService(this);


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        formView = (View) findViewById(R.id.form);
        messageTextView = (TextView) findViewById(R.id.status_message);
        testService.testResultsHandler = new TestResultResponse();

    }

    private class TestResultResponse extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg != null && msg.obj != null && this != null) {
                if (msg.obj.toString().equals("refresh")) {
                    refresh(); // return value back to testservice in here
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您需要使用ServiceConnection在Activity中存储Service处理程序。

private ServiceConnection mServiceConnection = new ServiceConnection() {

    @Override
    public void onServiceDisconnected(ComponentName name) {
        // onServiceDisconnected is only called in extreme situations (crashed / killed).
        mBound = false;
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) { 
        mConnectorSender = new Messenger(service);                  
        mBound = true;
    }
}; 

并像这样绑定服务:

mContext.bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);

Here is来自Vogella的好教程。

最好在msg.arg1和msg.arg2参数中发送小消息。您可以为刷新操作创建常量并将其分配给msg.arg1。它比发送对象更好。