Karthik Balakrishnan
Karthik Balakrishnan

Reputation: 4383

Passing parameters between service and activity

Code for passing float value from service to activity:

call.putExtra("floatvalue", fv);
call.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(call);

Code for getting float value in the activity:

Bundle extras=new Bundle();
float value = extras.getFloat("floatvalue");

The problem is no matter what is passed as the float value from the service, I get only 0.0 in the activity.

What is the problem with the code?

EDIT

I changed the code in the activity to

Bundle extras=new Bundle();
extras=getIntent().getExtras();
float value = extras.getFloat("floatvalue");

It didnt work.

Upvotes: 2

Views: 2968

Answers (2)

N Jay
N Jay

Reputation: 1824

Try this:

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

Since you added the float to your intent before starting it, you should get the float from that intent not from the bundle.

Upvotes: 1

Bob
Bob

Reputation: 23000

Define a listener in your service like this:

// 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);
        }
    }
}
}

And register it in your Activity like this:

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

For more information look at this link: https://stackoverflow.com/a/7709140/779408

Upvotes: 1

Related Questions