Android: how to get the intent received by a servi

2019-02-02 20:43发布

I'm starting a service with an intent where I put extra information.

How can I get the intent in the code of my service?

There isn't a function like getIntent().getExtras() in service like in activity.

3条回答
萌系小妹纸
2楼-- · 2019-02-02 21:12

onStart() is deprecated now. You should use onStartCommand(Intent, int, int) instead.

查看更多
走好不送
3楼-- · 2019-02-02 21:25

To pass the extras:

Intent intent = new Intent(this, MyService.class);
intent.putExtra(MyService.NAME, name);
...
startService(intent);

To retrieve the extras in the service:

public class MyService extends Service {  
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        String name = intent.getExtras().getString(NAME);
        ...
    } 
    ...
} 
查看更多
唯我独甜
4楼-- · 2019-02-02 21:32

Override onStart() -- you receive the Intent as a parameter.

查看更多
登录 后发表回答