Calling getIntent Method in service

前端 未结 2 372
一整个雨季
一整个雨季 2020-12-14 17:25

I have to pass parameter from MyActivity.class to TestService.class. MyActivity is a Activity class and TestService is a Service that I have made for sending messages. I hav

相关标签:
2条回答
  • 2020-12-14 17:55

    When you start Service with intent(having Data) then that intent is received in method
    onStart(Intent intent, int startId) or

    onStartCommand (Intent intent, int flags, int startId)
    {
    this **intent** is your intent with data
    }
    

    of your Service.So receive your data from this method having intent as parameter

    0 讨论(0)
  • 2020-12-14 18:05

    Start your service like this;

     Intent ir=new Intent(this, Service.class); 
     ir.putExtra("data", data); 
     this.startService(ir); 
    

    You attach your data as an intent extra.

    Then to retrieve the data from the service;

    data=(String) intent.getExtras().get("data"); 
    

    So you can access your parameter from either the onHandleIntent or onStartCommand Intent parameter. (depending on which type of service you are running) For Example;

    Service

    protected void onStartCommand (Intent intent, int flags, int startId) {
        data=(String) intent.getExtras().get("data"); 
    }
    

    public int onStartCommand (Intent intent, int flags, int startId)

    IntentService

    protected void onHandleIntent(Intent intent) {
        data=(String) intent.getExtras().get("data"); 
    }
    

    protected abstract void onHandleIntent (Intent intent)

    0 讨论(0)
提交回复
热议问题