【问题标题】:How to pass value from Activity to Service如何将值从活动传递到服务
【发布时间】:2013-01-09 21:04:50
【问题描述】:

我试图通过一个意图传递我的价值,如果它是从 Activity 到另一个 Activity,它工作得很好。但这次是从一个Activity到一个Service。我认为这是正确的方法?但我收到一个错误服务类

我的活动

@Override
    protected void onPause() {
        // TODO Auto-generated method stub
        myLocation.disableCompass();
        super.onPause();
        locationManager.removeUpdates(this);


    Intent intent = new Intent(this, LocationLoggerService.class);
    intent.putExtra("midllat", midllat);
    intent.putExtra("midlongi", midlongi);
    startActivity(intent);

}

我的服务类

@Override
public void onCreate() {
    // Find my current location
    locationManager = (LocationManager) this
            .getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
            2000, 0, this);
    Criteria crit = new Criteria();
    towers = locationManager.getBestProvider(crit, false);
    Location location = locationManager.getLastKnownLocation(towers);
    Toast.makeText(this, "The app is know running in the background",
            Toast.LENGTH_LONG).show();
    gm = new GoogleMaps();

我在 getIntent() 中遇到错误它找不到方法,是因为在服务类中吗?怎么办?

    Intent intent = getIntent();
    String test1 = intent.getStringExtra("midllat");
    String test2 = intent.getStringExtra("midlongi");

    midllat = Double.parseDouble(test1);
    midlongi = Double.parseDouble(test2);

}

【问题讨论】:

  • 我刚才说了? @alex .. 它站在那里我在 getIntent() 中遇到错误它找不到方法,是因为在服务类中吗?怎么办?
  • @JafarKhQ... 看看代码.. 您不能在服务类中使用 getIntent()。那该怎么办?你发布的问题对我没有帮助..
  • 我的意思是:堆栈跟踪说明了什么?

标签: android service


【解决方案1】:

一个问题当然是这样的:

startActivity(intent);

如果您尝试启动Service,则不应调用startActivity。请改用startService

假设您只是忘记在问题中更改它,您指出的另一个问题是getIntentService 没有那个方法。那是Activity 方法。服务通常与许多意图相关联,通常是同时进行的,因此getIntent 方法实际上没有意义。阅读Service 的文档,尤其是lifecycle section

您可能希望将与Intent 相关的代码放入onStartCommand

【讨论】:

  • @Zaz 如果此答案足以解决您的原始问题,请继续接受。就您的崩溃而言,我建议您通读堆栈跟踪并尝试理解该消息并尝试自己修复它。如果您无法弄清楚,请随意创建一个新问题,其中包含包括该堆栈跟踪在内的详细信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-04
  • 1970-01-01
  • 1970-01-01
  • 2011-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多