我想在我的应用中获取当前位置。我试过这个solution。
我必须检查权限,但我找不到如何检查权限nonActivity类。
我试过了:
public class MyLocation {
public MyLocation(Context context){
this.context = context;
}
public boolean getLocation(Context context, LocationResult result) {
locationResult = result;
if (lm == null)
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (gps_enabled)
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return true;
}
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
if (network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
timer1 = new Timer();
timer1.schedule(new GetLastLocation(context), 10000);
return true;
}
class GetLastLocation extends TimerTask {
Context context;
public GetLastLocation(Context context){
this.context = context;
}
@Override
public void run() {
//Context context = getClass().getgetApplicationContext();
Location net_loc = null, gps_loc = null;
if (gps_enabled)
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(network_enabled)
net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
}
在我的活动中,我传递了上下文;
MyLocation myLocation = new MyLocation(this);
我在GetLastLocation类中获得了权限错误;
E/AndroidRuntime: FATAL EXCEPTION: Timer-1
Process: com.example.merve.myapplication, PID: 4124
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.content.Context.checkPermission(java.lang.String, int, int)' on a null object reference
at android.support.v4.content.ContextCompat.checkSelfPermission(ContextCompat.java:439)
at other.MyLocation$GetLastLocation.run(MyLocation.java:124)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)
MyLocation.java第124行:
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
我无法添加完整代码。
答案 0 :(得分:1)
如果我不得不猜测,我会说这个
public GetLastLocation(Context context){
context = this.context;
}
应该是
public GetLastLocation(Context context){
this.context = context;
}
答案 1 :(得分:0)
只需将您的活动或上下文对象传递给非活动类。 timertask不会在主线程上运行,因此您必须在其他地方请求权限。也许在创建GetLastLocation对象之前