将浮点值从服务传递到活动的代码:
call.putExtra("floatvalue", fv);
call.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(call);
在活动中获取浮动值的代码:
Bundle extras=new Bundle();
float value = extras.getFloat("floatvalue");
问题是无论从服务中传递什么作为浮点值,我在活动中只得到0.0。
代码有什么问题?
修改
我将活动中的代码更改为
Bundle extras=new Bundle();
extras=getIntent().getExtras();
float value = extras.getFloat("floatvalue");
它没有用。
答案 0 :(得分:1)
试试这个:
float value = getIntent().getFloatExtra("floatvalue", 0.0f);
由于你在启动之前将浮动添加到你的意图中,你应该从该意图中获取浮动而不是从包中获取。
答案 1 :(得分:1)
在您的服务中定义一个侦听器,如下所示:
// listener ----------------------------------------------------
static ArrayList<OnNewLocationListener> arrOnNewLocationListener =
new ArrayList<OnNewLocationListener>();
// Allows the user to set a OnNewLocationListener outside of this class and
// react to the event.
// A sample is provided in ActDocument.java in method: startStopTryGetPoint
public static void setOnNewLocationListener(
OnNewLocationListener listener) {
arrOnNewLocationListener.add(listener);
}
public static void clearOnNewLocationListener(
OnNewLocationListener listener) {
arrOnNewLocationListener.remove(listener);
}
// This function is called after the new point received
private static void OnNewLocationReceived(float myValue) {
// Check if the Listener was set, otherwise we'll get an Exception when
// we try to call it
if (arrOnNewLocationListener != null) {
// Only trigger the event, when we have any listener
for (int i = arrOnNewLocationListener.size() - 1; i >= 0; i--) {
arrOnNewLocationListener.get(i).onNewLocationReceived(
myValue);
}
}
}
}
并在您的活动中注册,如下所示:
OnNewLocationListener onNewLocationListener = new OnNewLocationListener() {
@Override
public void onNewLocationReceived(float myValue) {
//use your value here
MyService.clearOnNewLocationListener(this);
}
};
// start listening for new location
MyService.setOnNewLocationListener(
onNewLocationListener);
有关详细信息,请查看以下链接:https://stackoverflow.com/a/7709140/779408