【问题标题】:How can we access data in service passed from activity using bundle ?我们如何使用 bundle 访问从活动传递的服务中的数据?
【发布时间】:2018-06-11 22:03:13
【问题描述】:

活动中:

Intent service = new Intent(OverlayShowingService.this, shortLayer.class);
service.putExtra("prevact","overlayService");
startService(service);

stopService(service);

什么是绑定服务?我可以从活动中访问我的数据吗?我做错了什么?

在役:

@Override
public IBinder onBind(Intent intent) {

    return null;
}

public int onStartCommand (Intent Preintent, int flags, int startId) {
    PreActivity = Preintent.getStringExtra("prevact");
    return START_STICKY;
}

【问题讨论】:

  • 什么是shortlayer?您的Service 中的onStartCommand() 是否曾被调用? onStartCommand() 中的代码看起来还不错。您无需绑定到 Service 即可将数据传递给它。

标签: android android-intent android-service bundle


【解决方案1】:

遵循此解决方案

关于“如何通过意图从 Activity 向服务发送数据”这个问题的准确答案,您是否必须重写接收意图对象的 onStartCommand() 方法:

当您创建 Service 时,您应该重写 onStartCommand() 方法,因此如果您仔细查看下面的签名,您会收到传递给它的意图对象:

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

因此,您将从 Activity 创建 Intent 对象以启动服务,然后将数据放在 Intent 对象中,例如,您希望将 UserID 从 Activity 传递给 Service:

 Intent serviceIntent = new Intent(YourService.class.getName())
 serviceIntent.putExtra("UserID", "123456");
 context.startService(serviceIntent);

当服务启动时,其onStartCommand() 方法将被调用,因此在此方法中,您可以从意图对象中检索值(UserID),例如

public int onStartCommand (Intent intent, int flags, int startId) {
    String userID = intent.getStringExtra("UserID");
    return START_STICKY;
}

希望一切顺利。

【讨论】:

  • 我已经在以前的帖子中尝试过这个答案..但这没有帮助!它在服务中不起作用。
猜你喜欢
  • 1970-01-01
  • 2020-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多