비 활동 클래스 (LocationManager)에서 getSystemService를 사용하려면 어떻게해야합니까?


181

주요 활동 OnCreate 메서드에서 다른 클래스로 작업을 오프로드하는 데 문제가있어서 무거운 물건을 들어 올리는 데 어려움이 있습니다.

비 활동 클래스에서 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 () 이전 활동에 사용할 수없는 시스템 서비스
케빈 파커

답변:


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 메소드에 전달 해야하는 것이 있다면 ...이 클래스를 Activity에 확장 클래스로 쓰지 않고 getSystemService를 호출 할 수 없을 때 메소드에 컨텍스트를 전달하는 것이 어떻게 도움이되는지 실제로 알지 못합니다.
케빈 파커

이것을 시도 했습니까? onCreate에서 'this'로 컨텍스트에 액세스하는 경우
Labeeb Panampullan

그러나 lmt수업이 실행 되지 않으면 fly상황이 발생하지 않습니다
사냥

BTW 는 매개 변수 getSysytemService()로만 허용 String합니다. 따라서 컨텍스트를 전달할 수 없습니다 . 이 문제를 어떻게 해결합니까? @ 헌트
Parth Sane

2
그냥 언급, 안드로이드 관리자 ( BluetoothManager, ActivityManager등)도있다 구성 하는 방법 (안 반드시 통과 Activity자신의 생성자에 컨텍스트를) 그리고 그들은 응용 프로그램 범위의 구성 요소에 액세스 할 수 있습니다 이유입니다.
Eido95

47

당신은 이것을 위해 갈 수 있습니다 :

getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);

5
클래스에 대해 getActivity () 메소드가 정의되지 않았습니다. 이 오류가 나타납니다.
Darpan

사용하는 수업 유형은 무엇입니까? 즉, 수신자 클래스, 프래그먼트, 간단한 Java 클래스 또는 기타입니다.
Maddy

활동 대신 FreagmentActivity로 활동을 확장해야합니다. 나는 그것이 당신을 위해 작동하기를 바랍니다 ...?
Maddy

확장하려는 간단한 클래스에서는 작동하지 않습니다 ArrayAdapter.
David Silva-Barrera

2
MIne은 getActivity () 대신 getContext ()를 사용하여 작동했습니다!
Amir

16

이 문제를 해결하는 한 가지 방법은 인스턴스에 대한 정적 클래스를 만드는 것입니다. 나는 그것을 AS3에서 많이 사용했다. 나는 안드로이드 개발에서도 나를 위해 훌륭하게 일했다.

Config.java

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을 할당하면 치명적인 실패를 일으킬 수있는 보호되지 않은 상태로 남겨 두는 것입니다.
Rob

2
이에 대한 변형은 MyApp에 개인 정적을 넣은 다음 게터를 추가하는 것입니다. private static MyApp _context; public static MyApp getContext() { return _context; }... onCreate : _context = this; 에서 onStop : _context = null;... 사용법 : MyApp.getContext().
ToolmakerSteve

2
메모리 누수로 이어질 수 있습니다.
Yat3s

2
이것은 절대적으로 메모리 누수로 이어질 것입니다. 이 프로세스를 사용하지 않는 것이 이상적입니다.
초보자

0

이것이 도움이 될지 모르겠지만 다음과 같이했습니다.

LocationManager locationManager  = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);

@Maddy의 말처럼 올바른 방법은 정적 인 방식으로 사용하는 것입니다
russellhoff

0

Worker 와 같은 비 활동 클래스의 경우 이미 공용 생성자에 Context 객체가 제공되었습니다.

Worker(Context context, WorkerParameters workerParams)

예를 들어 클래스의 개인 컨텍스트 변수 (예 :)에 저장 mContext한 다음 예를 들어

mContext.getSystenService(Context.ACTIVITY_SERVICE)
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.