Android IntentService没有收到额外的费用

时间:2014-04-22 22:19:14

标签: android intentservice

我正在启动该服务,并在附加信息中添加了一条消息,

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

但正在运行,服务启动,日志显示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);
    }

当我声明mServiceIntent.setType(HTTP.PLAIN_TEXT_TYPE)时,它可能与MIME TYPE有关; (使用import org.apache.http.protocol.HTTP;)

1 个答案:

答案 0 :(得分:0)

正如@Squonk已经提到的,你的代码并没有真正融合在一起。要开始Service,您必须使用Intent这样的内容:

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

您可以使用Intent.EXTRA_TEXT常量作为附加内容的密钥,但您必须使用相同的密钥在Service中检索邮件:

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

MyService中的代码并非真实地显示您是否在MyService中实际使用了mime类型,因此我将其从上面的示例中删除了。