如何在非活动类(LocationManager)中使用getSystemService?


180

我无法将主要的Activity OnCreate方法中的任务卸载到另一个类上来进行繁重的工作。

当我尝试从非Activity类调用getSystemService时,将引发异常。

任何帮助将不胜感激 :)

lmt.java:

package com.atClass.lmt;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.location.Location;

public class lmt extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        fyl lfyl = new fyl();
        Location location = lfyl.getLocation();
        String latLongString = lfyl.updateWithNewLocation(location);

        TextView myLocationText = (TextView)findViewById(R.id.myLocationText);
        myLocationText.setText("Your current position is:\n" + latLongString);
    }
}

fyl.java

package com.atClass.lmt;

import android.app.Activity;
import android.os.Bundle;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.content.Context;

public class fyl {
    public Location getLocation(){
        LocationManager locationManager;
        String context = Context.LOCATION_SERVICE;
        locationManager = (LocationManager)getSystemService(context);

        String provider = LocationManager.GPS_PROVIDER;
        Location location = locationManager.getLastKnownLocation(provider);

        return location;
    }

    public String updateWithNewLocation(Location location) {
        String latLongString;

        if (location != null){
            double lat = location.getLatitude();
            double lng = location.getLongitude();
            latLongString = "Lat:" + lat + "\nLong:" + lng;
        }else{
            latLongString = "No Location";
        }

        return latLongString;
    }
}

2
向问题中添加异常和堆栈跟踪可能会帮助潜在的回答者
Bert F

嗨,很抱歉犯错了。如果尝试使用该类扩展Activity类,则会引发异常。我不想扩展该类的Activity类,仅希望能够从我的getLocation方法中调用getSystemService。异常:java.lang.IllegalStateException:onCreate()之前的活动无法使用系统服务
Kevin Parker

Answers:


280

您需要将上下文传递给fyl类。
一种解决方案是为您的fyl类创建一个类似这样的构造函数:

public class fyl {
 Context mContext;
 public fyl(Context mContext) {
       this.mContext = mContext;
 }

 public Location getLocation() {
       --
       locationManager = (LocationManager)mContext.getSystemService(context);

       --
 }
}

因此,在您的活动类中,在onCreate函数中创建fyl对象,如下所示:

package com.atClass.lmt;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.location.Location;

public class lmt extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        fyl lfyl = new fyl(this); //Here the context is passing 

        Location location = lfyl.getLocation();
        String latLongString = lfyl.updateWithNewLocation(location);

        TextView myLocationText = (TextView)findViewById(R.id.myLocationText);
        myLocationText.setText("Your current position is:\n" + latLongString);
    }
}

抱歉,我不明白,代码会更有帮助。如果有的话,我应该将一个LocationManager对象传递给getLocation方法...我真的看不到当我什至不能调用getSystemService而不将这个类作为扩展类编写为Activity时,如何将上下文传递给该方法也不会有所帮助。
凯文·帕克

你尝试过这个吗 在onCreate中,如果您要通过“ this”传递访问上下文
Labeeb Panampullan

但是,如果lmt该类无法执行,则fly不会具有上下文
狩猎

BTW getSysytemService()仅接受String作为参数。因此,您不能将上下文传递给它。我该如何解决?@Hunt
Parth Sane

2
只提,Android的经理(BluetoothManagerActivityManager等)也建立这样(不一定是传递一个Activity上下文的构造函数),这就是为什么他们能在应用程序范围内访问组件。
Eido95 '16

46

您可以这样做:

getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);

5
该类的getActivity()方法未定义。显示此错误。
2014年

您正在使用哪种类类型?即它是一个接收器类,片段,简单的Java类或任何其他类。
Maddy

您需要使用FreagmentActivity而不是Activity来扩展您的Activity。希望对您有用...?
Maddy

对于我要扩展的简单类而言,它不起作用ArrayAdapter
David Silva-Barrera

2
通过使用getContext()而不是getActivity()可以工作!
阿米尔(Amir)

16

解决这个问题的一种方法是为实例创建一个静态类。我在AS3中使用了很多东西,在android开发中也为我工作得很好。

配置文件

public final class Config {
    public static MyApp context = null;
}

MyApp.java

public class MyApp extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Config.context = this;
    }
    ...
}

然后,您可以访问上下文或通过使用 Config.context

LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = Config.context.getSystemService(context);

4
我看到的这种方法的问题是,如果有人给它分配了null,它会留下未受保护的东西,可能会导致灾难性的失败?
罗布

2
对此的一种变化是在MyApp中放置一个私有静态变量,然后添加getter。 private static MyApp _context; public static MyApp getContext() { return _context; }...在onCreate中: _context = this; 在onStop中:_context = null;...用法: MyApp.getContext()
ToolmakerSteve

2
这可能会导致内存泄漏
Yat3s

2
这绝对会导致内存泄漏。理想情况下,您不应使用此过程。
初学者


0

对于某些非活动类(例如Worker),您已经在公共构造函数中获得了Context对象。

Worker(Context context, WorkerParameters workerParams)

您可以使用它,例如,将其保存到类中的私有Context变量中(例如mContext),然后例如

mContext.getSystenService(Context.ACTIVITY_SERVICE)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.