我打开一个新问题更清楚:) 我有android服务,我需要返回一个结果后,它已经开始。 所以: 1)我开始服务 2)服务做些什么 3)服务返回结果 我想也许我可以使用单例类来取得结果。因此,我创建了一个单例类,以便使服务将结果保存在其中,并从活动的服务中获取结果。这里有类的代码:Android:从服务中获取结果
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的代码吗? – sandyiscool
当然,它所做的是: Result.getInstance()。setResult(mMediaPlayer.getCurrentPosition()); 其中mMediaPlayer是一个MediaPlayer对象;) – user1315621
只是为了进行交叉检查,您是否在manifest中声明了该服务?您的服务扩展了哪些基类Service或IntentService或其他? – vikas