1

我有 android 服务,我需要在它启动后返回一个结果。所以:

1)我启动服务

2)服务做某事

3) 服务返回结果

我想也许我可以使用单例类来获取结果。我创建了一个单例类,以使服务将结果保存在其中,然后通过活动从服务中获取结果。这是该类的代码:

public class Result {

    //SIGLETON DECLARATION

    private static Result mInstance = null;

    public static Result getInstance() { 
        if (mInstance == null) {
            mInstance = new Result();
        }
        return mInstance;
    }

    private Result() {
    }

    //CODE

    Object result;
    boolean resultIsSet = false;

    public void deletePreviousResult() {
        this.result = null;
        resultIsSet = false;
    }

    public void setResult(Object result) {
        Log.w("result", "setResult");
        this.result = result;
        resultIsSet = true;
    }

    public Object getResult() {
        Log.w("result", "getResult");
        while(resultIsSet == false) {}
        return this.result;
    }

这是我用来获取结果的代码:

public int getInfo() {
    Result.getInstance().deletePreviousResult();
    //start the service and ask to save the result in singleton class
    Intent myIntent = new Intent(mInstanceContext, MediaPlayerService.class);
    myIntent.setAction("getInfo");
    mInstanceContext.startService(myIntent);
    //take the result
    return (Integer) Result.getInstance().getResult();
}

在做什么onStartCommand是:

 Result.getInstance().setResult(mMediaPlayer.getCurrentPosition()); 

mMediaPlayerMediaPlayer 对象在哪里。

然而问题是 ifsetResult也应该被调用onStartCommand,它永远不会被调用!为什么?是我的方法不对吗?

4

1 回答 1

1

您在以下代码中getInfo()

mInstanceContext.startService(myIntent);
//take the result
return (Integer) Result.getInstance().getResult();

假定当您调用startService()该服务时,该服务已启动并被同步onStartCommand()调用,以便在下一条语句中您可以使用.Result.getInstance().getResult()

不幸的是,它不是那样工作的。调用startService()不像调用对象的方法。当您调用时startService(),您所做的是告诉 Android 您希望该服务在下一个可用时刻启动。由于onStartCommand()在你的服务中需要在主线程上调用,通常这意味着 Android 将启动你的服务并onStartCommand()在下次 Android 获得主线程的控制权时调用(即:当你所有的活动方法都返回时)。在任何情况下,您都无法确定何时启动该服务或何时onStartCommand()调用该服务。是异步调用,所以需要依赖回调机制。这意味着您需要编写某种回调方法,当服务完成工作并希望将结果返回给您时,它可以调用该方法。

有多种方法可以做到这一点。您可以让服务向您的活动发送 Intent。您可以让服务广播带有结果的 Intent。您可以绑定到服务并注册回调侦听器(请参阅绑定服务的开发人员文档)。可能还有其他方法。

于 2012-09-04T21:58:50.940 回答