如何将值从Activity传递给Service

时间:2013-01-09 21:04:51

标签: android service

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

我的活动

@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);

}

1 个答案:

答案 0 :(得分:0)

当然有一个问题:

startActivity(intent);

如果您尝试启动Service,则不应该致电startActivity。请改为startService

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

您可能希望将Intent相关代码放在onStartCommand

相关问题