【问题标题】:how to pass value from activity to service?如何将价值从活动传递到服务?
【发布时间】:2014-11-17 11:36:18
【问题描述】:

我已将服务编写为库项目并将该服务连接到另一个应用程序。现在我想将一些输入值传递给服务。我该如何传递?

像这样传递值:

Intent intent = new Intent(SelfMonitor.this, SchedulerService.class);
intent.putExtra("initialDelay", initialDelay);
intent.putExtra("endTime", endTime);
startService(intent);

在服务中获得这样的价值:

initialDelay = Integer.parseInt(intent.getStringExtra("initialDelay"));
endTime = intent.getStringExtra("endTime");

但我收到null pointer 异常?

【问题讨论】:

    标签: android


    【解决方案1】:

    就像你在活动中所做的那样,

     Intent intent =  new Intent(Activity.this, YourService.class);
        intent.putExtra("key", value);
        startService(intent);
    

    为您服务

    Bundle extras = getIntent().getExtras();
    if (extras != null)
    {
    value = extras.getString("key", "somestring");
    }
    

    欲知详情,请see this

    【讨论】:

    • 我无法使用 getIntent().getExtras();在我的服务类 oncreate 方法中。
    • 非常感谢 nobalG。问题已解决。感谢您的支持。
    • 快乐是我的全部
    【解决方案2】:
    You need serviceIntent for this purpose.
    
    Intent serviceIntent = new Intent(Activity.this, CheckAPI.class);
    serviceIntent.putExtra("number", "96999");
    serviceIntent.putExtra("message", "hello world");         
    startService(serviceIntent);    
    

    【讨论】:

    • 如何在服务类中获取这两个参数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-30
    • 2019-09-04
    • 1970-01-01
    • 1970-01-01
    • 2011-11-14
    • 2015-11-21
    相关资源
    最近更新 更多