非アクティビティクラス(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
例外とスタックトレースを質問に追加すると、潜在的な回答者に役立つ可能性があります
バートF

こんにちは、申し訳ありません。このクラスでActivityクラスを拡張しようとすると、例外がスローされます。このクラスのActivityクラスを拡張するのではなく、単にgetLocationメソッド内からgetSystemServiceを呼び出せるようにしたいだけです。例外:java.lang.IllegalStateException:onCreate()より前のアクティビティでシステムサービスを利用できない
Kevin Parker

回答:


280

コンテキストをfylクラスに渡す必要があります。1
つの解決策は、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ない場合、コンテキストはありません
Hunt

BTW はパラメーターとしてgetSysytemService()のみ受け入れStringます。したがって、コンテキストを渡すことはできませんどうすればこれを回避できますか?@ハント
Parth Sane

2
ちょうど言及、Androidの経営者(へBluetoothManagerActivityManagerなど)もしている構築方法は、(必ずしも通らないことをActivity彼らのコンストラクタにコンテキスト)を、彼らはアプリケーションスコープ内のコンポーネントにアクセスできる理由です。
Eido95 2016年

47

あなたはこれのために行くことができます:

getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);

5
getActivity()メソッドはクラスに対して未定義です。このエラーが表示されます。
Darpan 2014

使用しているクラスのタイプは何ですか?つまり、レシーバクラス、フラグメント、単純なJavaクラスなどです。
マディ2014

アクティビティの代わりにFreagmentActivityを使用してアクティビティを拡張する必要があります。うまくいくといいのですが...?
Maddy

拡張したい単純なクラスでは機能しませんArrayAdapter
David Silva-Barrera 2016

2
MIneはgetActivity()の代わりにgetContext()を使用して機能しました!
アミール

16

これを回避する1つの方法は、インスタンスの静的クラスを作成することです。AS3でよく使用しました。Android開発でもうまく機能しました。

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; in onStop:_context = null;...使用法: MyApp.getContext()
ToolmakerSteve

2
メモリリークにつながる可能性があります
Yat3s 2016

2
これは絶対にメモリリークにつながります。理想的には、このプロセスを使用しないでください。
初心者用

0

これが役立つかどうかはわかりませんが、これを行いました:

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

@マディが言うように、正しい方法は静的な方法で使用することです
russellhoff

0

Workerなどの一部の非アクティビティクラスでは、パブリックコンストラクターでContextオブジェクトが既に与えられています。

Worker(Context context, WorkerParameters workerParams)

それを使用することができます。たとえば、クラスのプライベートContext変数(たとえば、mContext)に保存し、次に、たとえば

mContext.getSystenService(Context.ACTIVITY_SERVICE)
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.