Question

I am starting the service , and I put a message in extra,

Intent mServiceIntent = new Intent(this, TextToSpeechService.class);
mServiceIntent.putExtra(Intent.EXTRA_TEXT, "a message");
mServiceIntent.setType(HTTP.PLAIN_TEXT_TYPE);
this.startService(mServiceIntent);

but running , the service starts and the log shows a message = null...

public class MyService extends IntentService {
    static final String TAG = "MyService";

    public MyService() {
        super("My Service");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String message = intent.getStringExtra("message");
        Log.d(TAG, "received message, should say: " + message);
    }

could it be related to the MIME TYPE, when I state mServiceIntent.setType(HTTP.PLAIN_TEXT_TYPE); ( using import org.apache.http.protocol.HTTP;)

Was it helpful?

Solution

As @Squonk already mentioned your code doesn't really go together. To start your Service you have to use an Intent like this:

// The class you set here determines where the Intent will go.
// You want it to start MyService so we write MyService.class here.
Intent intent = new Intent(this, MyService.class);
intent.putExtra(Intent.EXTRA_TEXT, "a message");
startService(intent);

You can very well use the Intent.EXTRA_TEXT constant as key for your extra, but you have to use the same key to retrieve the message in your Service:

@Override
protected void onHandleIntent(Intent intent) {
    String message = intent.getStringExtra(Intent.EXTRA_TEXT);
    Log.d(TAG, "received message, should say: " + message);
}

The code in your MyService doesn't really show if you actually use the mime type in your MyService so I removed it from my example above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top