我有一个检查位置的应用程序。
为了获取位置信息和更多数据,我正在使用名为UpdateTimesActivity
的java类(这不是一项活动)
现在,我想每7个小时检查一次位置,并更新对应的数据,因此我有一项服务。问题是,当调用UpdateTimesActivity
时,我得到了:
Attempt to invoke virtual method 'android.content.pm.PackageManager android.content.Context.getPackageManager()' on a null object reference
这是我的服务
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, " MyService Started", Toast.LENGTH_LONG).show();
ArrayList<Date> times = (ArrayList<Date>) intent.getExtras().get("requiredTimesToNotify");
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
new UpdateTimesActivity(getApplicationContext(), locationManager);
BroadcastReceiver resultTimeRevicer = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
DecimalFormat df = new DecimalFormat("00");
ArrayList<Calendar> resultTimes= (ArrayList<Calendar>) intent.getExtras().get("a");
if(resultTimes.size()>0){
Toast.makeText(context, resultTimes.size()+" " , Toast.LENGTH_LONG).show();
}
}
};
registerReceiver(resultTimeRevicer, new IntentFilter("times_gabi"));
return START_STICKY;
}
这是问题所在:
public UpdateTimesActivity(final Context context, LocationManager locationManager) {
this.context = context;
this.locationManager = locationManager;
if (ActivityCompat.checkSelfPermission(context,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(context,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.INTERNET}
, 10);
}
return;
}
locationManager.requestLocationUpdates("gps", 5000, 0, locationListener);
}
现在,我确实看到了答案,说明您无法发送上下文抛出服务, 但是即使我尝试做类似的事情 (当我直接从MainActivity调用它时,它确实起作用了)
MainActivity m = new MainActivity();
context = m.context (static);
并将其放在requestPermissions中将不起作用。
谢谢...