gpt4 book ai didi

java - 安卓 Java :Getting your longitude and latitude on button click

转载 作者:行者123 更新时间:2023-12-01 11:49:34 24 4
gpt4 key购买 nike

这是我第一次提问,大家好:

我可以通过监听器获取我的位置,但我想在单击按钮时获取它。

提前感谢大家。

如果你想问我什么,请评论。

这是主要 Activity :

package com.Lottery;

import com.example.R;
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.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


public class Main extends Activity implements OnClickListener{
/** Called when the activity is first created. */
TextView tv;
Button b;
LocationManager mlocManager;
@Override

public void onCreate(Bundle savedInstanceState){

super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/* Use the LocationManager class to obtain GPS locations */
tv = (TextView) findViewById(R.id.tv);
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(this);

mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0, mlocListener);
}


/* Class My Location Listener */

public class MyLocationListener implements LocationListener{
@Override

public void onLocationChanged(Location loc){

String Text = "location: " +
"Latitud = " + loc.getLatitude() +
"Longitud = " + loc.getLongitude();

tv.setText(Text);

}
public void onProviderDisabled(String provider){

//nothin
}


public void onProviderEnabled(String provider){

//nothin
}

public void onStatusChanged(String provider, int status, Bundle extras){
//nothin
}
}/* End of Class MyLocationListener */


@Override
public void onClick(View v) {


//i wanto do it here

}
}/* End of UseGps Activity */

最佳答案

假设您想以与 MyLocationListener 中相同的方式执行此操作,您可以这样做:

public void onClick(View v) {
Location lastLocation = mlocManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

String locationInfo = "Location: " +
"\nlatitude = " + lastLocation.getLatitude() +
"\nlongitude = " + lastLocation.getLongitude();

tv.setText(locationInfo);
}

请注意,这实际上并不请求新的位置更新,而是返回最后收到的位置(因此它可能已过时)。如果您的应用持续请求位置更新(通过指定的提供商 - 在您的情况下为 NETWORK_PROVIDER),这应该不是问题。

关于java - 安卓 Java :Getting your longitude and latitude on button click,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28904195/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com