我用GPS功能做了一个获取城市名字的功能,然后把这个名字发送给服务器的程序public class SelectCityActivity extends Activity{
private RadioGroup selectType = null;
private RadioButton selectTypeCity = null;
private RadioButton selectGps = null;
private AutoCompleteTextView editCityName = null;
private Button okButton = null;
private String selectCity = null;
private String flag_selectType = null;
private String username = null;
private String nickname = null;
private Double latitude=null;
private Double longitude = null;
private TextView test = null;
LocationManager locationManager=null;
static final String[] COUNTRIES = new String[]{
"Leicester","London","Leeds"
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.selectcityactivity);
selectType = (RadioGroup)findViewById(R.id.SelectType);
selectTypeCity = (RadioButton)findViewById(R.id.TypeCity);
selectGps = (RadioButton)findViewById(R.id.UseGPS);
editCityName = (AutoCompleteTextView)findViewById(R.id.EditCityName);
List<String> list = new ArrayList<String>();
list.add("Leicester");
list.add("London");
list.add("Leeds");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,R.layout.autocompletetextview,list);
editCityName.setAdapter(arrayAdapter);
Intent intent = getIntent();
username = intent.getStringExtra("username");
nickname = intent.getStringExtra("nickname");
okButton = (Button)findViewById(R.id.OK);
okButton.setOnClickListener(new OKButtonListener());
test=(TextView)findViewById(R.id.test);
selectType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(selectTypeCity.getId() == checkedId){
editCityName.setVisibility(View.VISIBLE);
flag_selectType = "TypeName";
}
else if(selectGps.getId() == checkedId)
{
editCityName.setVisibility(View.GONE); flag_selectType = "UseGPS";
}
}
});
}
class OKButtonListener implements Button.OnClickListener{
@Override
public void onClick(View arg0) {
handler.post(SelectCityThread);
}
}
Handler handler = new Handler(){ @Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
}
};
Runnable SelectCityThread = new Runnable(){
public void run(){
try{
if(flag_selectType==null){
Toast.makeText(SelectCityActivity.this, "Please choose a Type to select a city in UK", Toast.LENGTH_SHORT).show();
}
else {
if(flag_selectType.equals("TypeName")){
selectCity = editCityName.getText().toString();
transMit();
}
//用GPS查找城市名
else if (flag_selectType.equals("UseGPS")){
openGPSSettings();
String serviceName = Context.LOCATION_SERVICE;
locationManager = (LocationManager) SelectCityActivity.this.getSystemService(serviceName); Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE); // 高精度
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW); // 低功耗
System.out.println("openGPS 1");
String provider = locationManager.getBestProvider(criteria, true); // 获取GPS信息
Location location = locationManager.getLastKnownLocation(provider); // 通过GPS获取位置
System.out.println("openGPS 2");
System.out.println("3");
locationManager.requestLocationUpdates(provider, 0, 0, locationListener);
System.out.println(latitude+" b "+longitude);
System.out.println("4"); }
}
}
catch(Exception e)
{
// TODO: handle exception
e.printStackTrace();
}
}
} ;
private void transMit(){
try {
ArrayList<String> sightName = new ArrayList<String>();
String selectCityName = selectCity;
Socket socket = null;
if(selectCity.equals("")){
Toast.makeText(SelectCityActivity.this, "Please select a city in UK", Toast.LENGTH_SHORT).show();
}
else {
socket = new Socket("192.168.1.64",4445);
//向服务器发送消息
PrintWriter out = null;
if(selectCityName.equals("Greater London"))
{
selectCityName = "London";
}
if(selectCityName.equals("Leicestershire"))
{
selectCityName = "Leicester";
}
out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
out.println(selectCityName);
//接收来自服务器的消息
String msg = null;
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
int i = 0; while((msg = br.readLine())!=null&&(!msg.equals("false"))&&(!msg.equals("true"))){ System.out.println(msg);
System.out.println(i);
sightName.add(msg);
i++;
}
if(msg.equals("true")){
System.out.println(msg);
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putStringArrayList("sightname", sightName); intent.putExtras(bundle);
intent.putExtra("username", username);
intent.putExtra("nickname", nickname);
intent.putExtra("cityname", selectCityName);
intent.setClass(SelectCityActivity.this, SelectSightActivity.class);
SelectCityActivity.this.startActivity(intent);
}
else {
Toast.makeText(SelectCityActivity.this, "Sorry, we can not find the city.", Toast.LENGTH_SHORT).show();
System.out.println(msg); }
System.out.println(username);
//关闭流
out.close();
br.close();
//关闭Socket
socket.close();
}}
catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
}
}
private void openGPSSettings() {
LocationManager alm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
Toast.makeText(this, "GPS模块正常", Toast.LENGTH_SHORT).show();
return;
}
else {
Toast.makeText(this, "请开启GPS!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent,0); //此为设置完成后返回到获取界面
}
}
private final LocationListener locationListener = new LocationListener(){
@Override
public void onLocationChanged(Location location) {
System.out.println(location.getLatitude()+" k "+location.getLongitude());
latitude=location.getLatitude();
longitude=location.getLongitude();
String LatitudStr =
latitude.toString();
String LongitudeStr =
longitude.toString();
System.out.println(LatitudStr+" a "+LongitudeStr);
String url = "http://maps.googleapis.com/maps/api/geocode/json?latlng="+LatitudStr+","+LongitudeStr+"&sensor=false";
//创建一个HttpClient对象
HttpClient httpClient = new DefaultHttpClient();
String responseData = "";
try{
//向指定的URL发送Http请求
HttpResponse response = httpClient.execute(new HttpGet(url));
//取得服务器返回的响应
System.out.println("1"); HttpEntity entity = response.getEntity();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
String line = "";
System.out.println("2");
while((line = bufferedReader.readLine()) != null){
responseData = responseData + line;
}
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println("3");
Gson gson = new Gson();
TestResult testResult = gson.fromJson(responseData, TestResult.class);
String result = testResult.toString();
String [] split = null;
split = result.split("], ");
String city = null;
String kill;
int i = 0;
while(i<=5){
String [] splitSec = null;
kill = split[i];
splitSec = kill.split("!=!");
String type = splitSec[1];
city = splitSec[0];
if(type.equals("[administrative_area_level_2, political")){
System.out.println(type);
System.out.println(city);
selectCity = city;
}
i++;
}
System.out.println(result);
Toast.makeText(SelectCityActivity.this, city, Toast.LENGTH_SHORT).show();
transMit();
locationManager.removeUpdates(locationListener);
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
} @Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
} @Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};
}但是我在DDMS里面测试正常,只发送一次名字,用真机就会传三次或多次,就是说把这个名字传服务器好几次,这是为什么?
请问我代码有什么错误吗?
private RadioGroup selectType = null;
private RadioButton selectTypeCity = null;
private RadioButton selectGps = null;
private AutoCompleteTextView editCityName = null;
private Button okButton = null;
private String selectCity = null;
private String flag_selectType = null;
private String username = null;
private String nickname = null;
private Double latitude=null;
private Double longitude = null;
private TextView test = null;
LocationManager locationManager=null;
static final String[] COUNTRIES = new String[]{
"Leicester","London","Leeds"
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.selectcityactivity);
selectType = (RadioGroup)findViewById(R.id.SelectType);
selectTypeCity = (RadioButton)findViewById(R.id.TypeCity);
selectGps = (RadioButton)findViewById(R.id.UseGPS);
editCityName = (AutoCompleteTextView)findViewById(R.id.EditCityName);
List<String> list = new ArrayList<String>();
list.add("Leicester");
list.add("London");
list.add("Leeds");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,R.layout.autocompletetextview,list);
editCityName.setAdapter(arrayAdapter);
Intent intent = getIntent();
username = intent.getStringExtra("username");
nickname = intent.getStringExtra("nickname");
okButton = (Button)findViewById(R.id.OK);
okButton.setOnClickListener(new OKButtonListener());
test=(TextView)findViewById(R.id.test);
selectType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(selectTypeCity.getId() == checkedId){
editCityName.setVisibility(View.VISIBLE);
flag_selectType = "TypeName";
}
else if(selectGps.getId() == checkedId)
{
editCityName.setVisibility(View.GONE); flag_selectType = "UseGPS";
}
}
});
}
class OKButtonListener implements Button.OnClickListener{
@Override
public void onClick(View arg0) {
handler.post(SelectCityThread);
}
}
Handler handler = new Handler(){ @Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
}
};
Runnable SelectCityThread = new Runnable(){
public void run(){
try{
if(flag_selectType==null){
Toast.makeText(SelectCityActivity.this, "Please choose a Type to select a city in UK", Toast.LENGTH_SHORT).show();
}
else {
if(flag_selectType.equals("TypeName")){
selectCity = editCityName.getText().toString();
transMit();
}
//用GPS查找城市名
else if (flag_selectType.equals("UseGPS")){
openGPSSettings();
String serviceName = Context.LOCATION_SERVICE;
locationManager = (LocationManager) SelectCityActivity.this.getSystemService(serviceName); Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE); // 高精度
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW); // 低功耗
System.out.println("openGPS 1");
String provider = locationManager.getBestProvider(criteria, true); // 获取GPS信息
Location location = locationManager.getLastKnownLocation(provider); // 通过GPS获取位置
System.out.println("openGPS 2");
System.out.println("3");
locationManager.requestLocationUpdates(provider, 0, 0, locationListener);
System.out.println(latitude+" b "+longitude);
System.out.println("4"); }
}
}
catch(Exception e)
{
// TODO: handle exception
e.printStackTrace();
}
}
} ;
private void transMit(){
try {
ArrayList<String> sightName = new ArrayList<String>();
String selectCityName = selectCity;
Socket socket = null;
if(selectCity.equals("")){
Toast.makeText(SelectCityActivity.this, "Please select a city in UK", Toast.LENGTH_SHORT).show();
}
else {
socket = new Socket("192.168.1.64",4445);
//向服务器发送消息
PrintWriter out = null;
if(selectCityName.equals("Greater London"))
{
selectCityName = "London";
}
if(selectCityName.equals("Leicestershire"))
{
selectCityName = "Leicester";
}
out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
out.println(selectCityName);
//接收来自服务器的消息
String msg = null;
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
int i = 0; while((msg = br.readLine())!=null&&(!msg.equals("false"))&&(!msg.equals("true"))){ System.out.println(msg);
System.out.println(i);
sightName.add(msg);
i++;
}
if(msg.equals("true")){
System.out.println(msg);
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putStringArrayList("sightname", sightName); intent.putExtras(bundle);
intent.putExtra("username", username);
intent.putExtra("nickname", nickname);
intent.putExtra("cityname", selectCityName);
intent.setClass(SelectCityActivity.this, SelectSightActivity.class);
SelectCityActivity.this.startActivity(intent);
}
else {
Toast.makeText(SelectCityActivity.this, "Sorry, we can not find the city.", Toast.LENGTH_SHORT).show();
System.out.println(msg); }
System.out.println(username);
//关闭流
out.close();
br.close();
//关闭Socket
socket.close();
}}
catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
}
}
private void openGPSSettings() {
LocationManager alm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
Toast.makeText(this, "GPS模块正常", Toast.LENGTH_SHORT).show();
return;
}
else {
Toast.makeText(this, "请开启GPS!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent,0); //此为设置完成后返回到获取界面
}
}
private final LocationListener locationListener = new LocationListener(){
@Override
public void onLocationChanged(Location location) {
System.out.println(location.getLatitude()+" k "+location.getLongitude());
latitude=location.getLatitude();
longitude=location.getLongitude();
String LatitudStr =
latitude.toString();
String LongitudeStr =
longitude.toString();
System.out.println(LatitudStr+" a "+LongitudeStr);
String url = "http://maps.googleapis.com/maps/api/geocode/json?latlng="+LatitudStr+","+LongitudeStr+"&sensor=false";
//创建一个HttpClient对象
HttpClient httpClient = new DefaultHttpClient();
String responseData = "";
try{
//向指定的URL发送Http请求
HttpResponse response = httpClient.execute(new HttpGet(url));
//取得服务器返回的响应
System.out.println("1"); HttpEntity entity = response.getEntity();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
String line = "";
System.out.println("2");
while((line = bufferedReader.readLine()) != null){
responseData = responseData + line;
}
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println("3");
Gson gson = new Gson();
TestResult testResult = gson.fromJson(responseData, TestResult.class);
String result = testResult.toString();
String [] split = null;
split = result.split("], ");
String city = null;
String kill;
int i = 0;
while(i<=5){
String [] splitSec = null;
kill = split[i];
splitSec = kill.split("!=!");
String type = splitSec[1];
city = splitSec[0];
if(type.equals("[administrative_area_level_2, political")){
System.out.println(type);
System.out.println(city);
selectCity = city;
}
i++;
}
System.out.println(result);
Toast.makeText(SelectCityActivity.this, city, Toast.LENGTH_SHORT).show();
transMit();
locationManager.removeUpdates(locationListener);
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
} @Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
} @Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};
}但是我在DDMS里面测试正常,只发送一次名字,用真机就会传三次或多次,就是说把这个名字传服务器好几次,这是为什么?
请问我代码有什么错误吗?
顶哈