【发布时间】:2012-08-29 08:11:28
【问题描述】:
我有 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());
mMediaPlayer 是一个 MediaPlayer 对象。
但是问题是如果setResult 也应该在onStartCommand 中被调用,那么它永远不会被调用!为什么?是不是我的方法不对?
【问题讨论】:
-
你能分享你的 onStartCommand 的代码吗?
-
当然,它的作用是这样的:Result.getInstance().setResult(mMediaPlayer.getCurrentPosition());其中 mMediaPlayer 是一个 MediaPlayer 对象;)
-
只是为了交叉检查,您是否在清单中声明了服务?您的服务扩展了 Service 或 IntentService 或任何其他基类?
-
它扩展了服务并声明了:)