2

将浮点值从服务传递到活动的代码:

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");

它没有用。

4

2 回答 2

1

试试这个:

float value =  getIntent().getFloatExtra("floatvalue", 0.0f);

由于您在启动它之前将浮动添加到您的意图中,因此您应该从该意图而不是从捆绑中获取浮动。

于 2013-01-14T13:17:02.663 回答
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

于 2013-01-14T13:22:54.083 回答