Majstor
Majstor

Reputation: 879

Android intent.putExtra() from Service to Activity

For some time now I'm trying to pass the simple one String data from the Service to the Activity with Intent.putExtra() but with no success however. Intent.getStringExtra() is always NULL

SERVICE CODE:

Intent intent=new Intent(getBaseContext(),MainActivity.class);
intent.putExtra(Consts.INTERNET_ERROR, "error");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(intent);

ACTIVITY CODE:

public void onResume() {

    super.onResume();

    Intent i = getIntent();
    String test = "temp";
    Bundle b = i.getExtras();
    if (b != null) {
        test = b.getString(Consts.INTERNET_ERROR);
    }
}   

Any suggestions?

Upvotes: 3

Views: 6425

Answers (4)

Augusto Picciani
Augusto Picciani

Reputation: 804

First: try to move your code from onResume to onStart:

public void onStart() {

    super.onStart();

    Intent i = getIntent();
    String test = "temp";
    Bundle b = i.getExtras();
    if (b != null) {
        test = b.getString(Consts.INTERNET_ERROR);
    }
}  

If it still not working try with this:

First activity:

Intent myIntent = new Intent(firstActivity.this, secondActivity.class);
myIntent.putExtra("mystring",strValue)' <=your String
startActivity(myIntent);

Second activity:

 String str = getIntent.getExtras().getString("mystring");<=get string 

and check here for some informations:

How do I pass data between Activities in Android application?

Upvotes: 0

Hoan Nguyen
Hoan Nguyen

Reputation: 18151

To elaborate my comment above, getIntent returns the original intent as documented at [1]http://developer.android.com/reference/android/app/Activity.html#onNewIntent(android.content.Intent) [1]:

The intent from the service is passed to your activity through onNewIntent which is called before onResume. Thus if you override onNewIntent you will get the intended string.

@Override
protected void onNewIntent(Intent intent)
{
    super.onNewIntent(intent);

    // set the string passed from the service to the original intent
       setIntent(intent);

}

Then your code onResume will work.

Upvotes: 6

daniel_c05
daniel_c05

Reputation: 11518

Rather than calling

extras.getString();

Try calling:

intent.getStringExtra("key");

Also, are you starting the activity directly FROM the service? Or are you already running on the activity and simply want to receive data from the service?

Upvotes: 0

muhoweb
muhoweb

Reputation: 116

I don't see where you add the String in the service code, however you can run the following code to send the string.

Intent intent=new Intent(getBaseContext(),MainActivity.class);
Bundle b = new Bundle();
b.putString(Consts.INTERNET_ERROR, "Your String Here");
intent.putExtras(b);
intent.setAction(Consts.INTERNET_ERROR);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(intent);

Upvotes: 0

Related Questions