使用 Location.getSpeed 时崩溃
Crash when using Location.getSpeed
好像每次显示速度都崩溃,只要没有定位,需要打印“--”就好了!
public class MainActivity extends Activity implements LocationListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,this);
this.onLocationChanged(null);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public void onLocationChanged(Location location) {
TextView textView = (TextView) findViewById(R.id.textView);
if(location == null){textView.setText("--");}
else{textView.setText((int)location.getSpeed());}
}
}
使用
textView.setText(String.valueOf((int)location.getSpeed()));
因为当您将 int 传递给 TextView.SetText 时,它需要一个资源 ID
好像每次显示速度都崩溃,只要没有定位,需要打印“--”就好了!
public class MainActivity extends Activity implements LocationListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,this);
this.onLocationChanged(null);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public void onLocationChanged(Location location) {
TextView textView = (TextView) findViewById(R.id.textView);
if(location == null){textView.setText("--");}
else{textView.setText((int)location.getSpeed());}
}
}
使用
textView.setText(String.valueOf((int)location.getSpeed()));
因为当您将 int 传递给 TextView.SetText 时,它需要一个资源 ID