好的我没有遇到与网络协调的问题,但我的教授要求我们将获取代码部分的位置放入其自己的类(比如NetworkLocation.java)。现在事情变得有趣了。
我的代码是:
//MainActivity.java
package com.example.maest.weather;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView t;
private LocationManager mLocationManager;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_scrolling);
t = (TextView) findViewById(R.id.textView);
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
NetworkLocation mNetworkLocation = new NetworkLocation();
double mCoordinate[] = mNetworkLocation.getNetworkLocation(mLocationManager);
t.append("\n Longtitude: " + mCoordinate[0] + "\n Latitude: " + mCoordinate[1] + "\n");
}
}
和NetworkLocation.java
//NetworkLocation.java
package com.example.maest.weather;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class NetworkLocation {
private LocationListener mLocationListener;
private double mCoordinate[] = {0, 0};
public double[] getNetworkLocation (LocationManager mLocationManager) {
mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(Location mLocation) {
mCoordinate[0] = mLocation.getLongitude();
mCoordinate[1] = mLocation.getLatitude();
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
};
try{
mLocationManager.requestLocationUpdates(mLocationManager.NETWORK_PROVIDER, 5000, 0, mLocationListener);
mLocation[0] = 5; //see if it works.
}catch(SecurityException e){
// Need update here.
};
return mCoordinate;
}
}
结果,界面中显示的经度始终为5,纬度始终为0.含义,代码:mLocationManager.requestLocationUpdates(mLocationManager.NETWORK_PROVIDER,5000,0,mLocationListener);但是,onLocationChanged()永远不会被调用。
嗯......这里没有语法错误,也没有运行时错误。那我该怎么办?