我无法获得Android设备的速度。所以我试着用一个样本,哪个应该有效。 使用http://www.androidhub4you.com/2013/06/how-to-get-device-current-speed-in_112.html的代码,我应该得到速度。但该应用程序在连接到GPS之前总是崩溃。 代码是:
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity {
Context context;
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.Geschwindigkeit);
LocationManager locationManager = (LocationManager) this .getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = newLocationListener(){ public void onLocationChanged(Location location) {
location.getLatitude();
Toast.makeText(context, "Current speed:" + location.getSpeed(), Toast.LENGTH_SHORT).show(); }
public void onStatusChanged(String provider, int status, Bundle extras) { }
public void onProviderEnabled(String provider) { }
public void onProviderDisabled(String provider) { }
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
}
日志说明如下:
08-04 14:36:51.023 11219-11219/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at android.widget.Toast.<init>(Toast.java:105)
at android.widget.Toast.makeText(Toast.java:261)
at test.gpsspeed.MainActivity$1.onLocationChanged(MainActivity.java:34)
at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:257)
at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:186)
at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:202)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5365)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
我该怎么办?或者我做错了什么?
答案 0 :(得分:0)
这样可行:
1