【问题标题】:Calling getIntent Method in service在服务中调用 getIntent 方法
【发布时间】:2012-08-10 13:32:53
【问题描述】:

我必须将参数从 MyActivity.class 传递给 TestService.class。 MyActivity 是一个 Activity 类,而 TestService 是我为发送消息而制作的一个服务。我必须将参数从 Activity 传递给服务,但是当我在服务类中调用 Intent i = getIntent(); 时,我收到一个错误 getIntent() is undefined

那么,如何将参数从我的 Activity 发送到 Service?

【问题讨论】:

    标签: android service android-intent


    【解决方案1】:

    像这样开始你的服务;

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

    您附加您的数据作为额外的意图。

    然后从服务中检索数据;

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

    因此,您可以从 onHandleIntent 或 onStartCommand Intent 参数访问您的参数。 (取决于您正在运行的服务类型)例如;

    服务

    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)

    【讨论】:

    • 如果系统级服务(例如可访问性)自行启动,该怎么办?
    • 如果我需要在onCreate() 中获取意图怎么办?
    【解决方案2】:

    当您以意图(具有数据)启动服务时,该意图会在方法中接收到
    onStart(Intent intent, int startId)

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

    你的 Service.So 从这个方法接收你的数据,意图作为参数

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-29
      • 2021-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多