Hello everybody I have a problem with LocationManager
I want to get my place position
This my code:
protected LocationManager locationManager;
#SuppressLint("MissingPermission")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000 * 10,
10, this);
}
#Override
public void onLocationChanged(final Location location) {
textView = (TextView) findViewById(R.id.label);
textView.setText("My location = Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
latitude = location.getLatitude();
longitude = location.getLongitude();
}
#Override
public void onProviderDisabled(String provider) {
Log.e("Latitude","disable");
}
#Override
public void onProviderEnabled(String provider) {
Log.e("Latitude","enable");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e("Latitude","status");
}
Manifest
<uses-sdk
android:targetSdkVersion="22" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission. ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
The problem is when I tested in the emulator and on my phone both devices give different results
What can i do help please
Related
I have the code set so it loads up the map, however it doesn't automatically go to the user's location until they press the zoom button. I would prefer if it started at the users location or at least loaded it up within a few seconds of the map appearing.
Use this code in onMapready
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(11);
mMap.clear();
MarkerOptions mp = new MarkerOptions();
mp.position(new LatLng(location.getLatitude(), location.getLongitude()));
mp.title("my position");
mMap.addMarker(mp);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
}
});}}
xml Code Add map like this:
<?xml version="1.0" encoding="utf-8"?>
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>
Add java code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
map = ((SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this); //You can also use LocationManager.GPS_PROVIDER and LocationManager.PASSIVE_PROVIDER
}
#Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
map.animateCamera(cameraUpdate);
locationManager.removeUpdates(this);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) { }
#Override
public void onProviderEnabled(String provider) { }
#Override
public void onProviderDisabled(String provider) { }
}
Add permissions in manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
try this code it helps you
I have 3 Activity. 1 - MainActivity , 2 - InfoActivity, 3 - ChangelogActivity.
If i am located on InfoActivity all is good (on InfoActivity placed ProgressBar) , if i go to ChangelogActivity and go back again to InfoActivity ProgressBar work fine, and his value not 0, but if i go to MainActivity from InfoActivity and go back, now ProgerssBar get value 0.
How i can fix it?
If need i can place some code here.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.teammt.gmanrainy.huaweifirmwarefinder">
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_SUPERUSER" />
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:configChanges="orientation|screenSize|keyboardHidden|uiMode">
android:screenOrientation="portrait"
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".FirmwareInfo"
android:configChanges="orientation|screenSize|keyboardHidden|uiMode"
android:screenOrientation="portrait" />
<activity
android:name=".FirmwareChangelog"
android:configChanges="orientation|screenSize|keyboardHidden|uiMode"
android:screenOrientation="portrait" />
<activity android:name=".SettingsActivity"
android:configChanges="orientation|screenSize|keyboardHidden|uiMode"
android:screenOrientation="portrait"></activity>
</application>
</manifest>
MainActivity Overrided Methods
//Действия во время созданиея MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
//Конструктор Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Проверка прав
ActivityCompat.requestPermissions(this, PERMISSION_STRING_ARRAY, REQUEST_PERMISSION_PHONE_STATE);
//Инициализация
utils = new FFUtils();
gridView = (GridView) findViewById(R.id.firmware_grid_view);
//Установка модели в тайтл
if(deviceModel != null)
setTitle(deviceModel);
else
setTitle(getString(R.string.app_name));
///////////////////////////////////////
// Advanced listener блок
///////////////////////////////////////
//Клик по элементу GridView
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
try
{
System.out.println(lastFirmwares.get(position));
String[] lastFirmwareArray = lastFirmwares.get(position).split("\\|");
Intent intent = new Intent(getThis(), FirmwareInfo.class);
intent.putExtra("firmwareName",lastFirmwareArray[0]).
putExtra("firmwareType",lastFirmwareArray[1]).
putExtra("firmwareLink",lastFirmwareArray[2]).
putExtra("firmwareSize",lastFirmwareArray[3]).
putExtra("firmwareLastmod",lastFirmwareArray[4]).
putExtra("firmwareCount",lastFirmwares.size()).
putExtra("firmwareId",position);
startActivity(intent);
}
catch (Exception ex)
{
Log.e("GetFirmwarePosition",ex.getMessage());
}
}
});
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBundle("newBundy", newBundy);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
savedInstanceState.getBundle("newBundy");
}
//Действия после загрузки формы
#Override
protected void onStart() {
super.onStart();
getDelegate().onStart();
//Получаем список моделей
modelsList = utils.getModelsList(MODELSLIST_LINK);
//Получаем приведенную к общему виду модель
if(modelManuallyChanged == false)
deviceModel = utils.getDeviceModel(modelsList,utils.getDeviceFullModel());
//Добавляем модель в тайтл
setTitle(deviceModel);
}
InfoActivity Overrided Methods
//Действия во время созданиея FirmwareInfo
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_firmware_info);
this.setTitle("FirmwareInfo");
//Инициализация
utils = new FFUtils();
firmware_info_lastmod_textview = (TextView)findViewById(R.id.firmware_info_lastmod_textview);
firmware_info_size_textview = (TextView) findViewById(R.id.firmware_info_size_textview);
firmware_info_download_progressbar = (ProgressBar) findViewById(R.id.firmware_info_download_progressbar);
//firmware_info_download_progressbar.setProgress(0);
//Убираем тень
getSupportActionBar().setElevation(0);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt("progressbar_progress", firmware_info_download_progressbar.getProgress());
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
int progressbar_progress = savedInstanceState.getInt("progressbar_progress");
firmware_info_download_progressbar.setProgress(progressbar_progress);
}
//Действия после загрузки формы
#Override
protected void onStart() {
super.onStart();
getDelegate().onStart();
firmwareName = getIntent().getExtras().getString("firmwareName");
firmwareType = getIntent().getExtras().getString("firmwareType");
firmwareLink = getIntent().getExtras().getString("firmwareLink");
firmwareSize = getIntent().getExtras().getString("firmwareSize");
firmwareLastmod = getIntent().getExtras().getString("firmwareLastmod");
firmwareId = getIntent().getExtras().getInt("firmwareId");
firmwareCount = getIntent().getExtras().getInt("firmwareCount");
if(firmwareName != null)
{
setTitle(firmwareName + " " + firmwareType);
firmware_info_lastmod_textview.setText(getString(R.string.last_mod) + " " + firmwareLastmod);
firmware_info_size_textview.setText(getString(R.string.size) + " " + utils.convertToMegabyte(firmwareSize));
}
}
Changelog Overrided Methods
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_firmware_changelog);
//Инициализация
utils = new FFUtils();
firmware_changelog_view_model = (TextView)findViewById(R.id.firmware_changelog_view_model);
firmware_changelog_view_changelog = (TextView)findViewById(R.id.firmware_changelog_view_changelog);
firmware_changelog_view_changelog.setMovementMethod(new ScrollingMovementMethod());
//Убираем тень
getSupportActionBar().setElevation(0);
//Убираем Titile
getSupportActionBar().hide();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBundle("newBundy", newBundy);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
savedInstanceState.getBundle("newBundy");
}
//Действия после загрузки формы
#Override
protected void onStart() {
super.onStart();
getDelegate().onStart();
firmwareName = getIntent().getExtras().getString("firmwareName");
firmwareType = getIntent().getExtras().getString("firmwareType");
firmwareLink = getIntent().getExtras().getString("firmwareLink");
firmwareSize = getIntent().getExtras().getString("firmwareSize");
firmwareLastmod = getIntent().getExtras().getString("firmwareLastmod");
firmware_changelog_view_model.setText(firmwareName);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try
{
//Получаем List со всеми строками feature из changelog
parsedChangelog = parseXmlString(prepareXpp(utils.getXmlFromUrl(firmwareLink.replace("update.zip","changelog.xml"))));
}
catch (Exception ex)
{
Log.e("Parse error",ex.getMessage());
}
StringBuilder sb = new StringBuilder();
for (String s : parsedChangelog)
{
sb.append(s);
sb.append("\t");
}
utils.universalSetText(firmware_changelog_view_changelog,sb.toString());
//firmware_changelog_view_changelog.setText(sb.toString());
}
});
t.start();
}
I want to show the current location of user on google map but as of now i am not able to show the location.I have a Fragment in which i am writing the code.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_home, container, false);
initGamp(rootView);
// Inflate the layout for this fragment
return rootView;
}
initgmap function
public void initGamp(View root) {
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
// check if map is created successfully or not
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney, Australia, and move the camera.
// LatLng sydney = new LatLng(-34, 151);
// mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
// mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Log.i("MAP","BEFORE LOCATION");
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
Log.i("MAP", "AFTER LOCATION");
LocationManager locationManager = (LocationManager) getActivity().getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
Toast.makeText(getActivity().getApplicationContext(),"not null",Toast.LENGTH_SHORT).show();
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 20, 0, this);
Log.i("MAP", "END LOCATION");
}
#Override
public void onLocationChanged(Location location) {
Log.i("MAP","CHANGE LOCATION");
Toast.makeText(getActivity().getApplicationContext(),"chnage",Toast.LENGTH_SHORT).show();
mMap.clear();
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(latLng));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
All permissions:
<!-- Required to show current location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.CALL_PHONE" />
Above code i have used for showing location but i does not working.I have also button of current location button on tapping that still i don't get current location.
The key here is to wait until the onMapReady() callback has occured before you request location updates. Once an instance of this interface is set on a MapFragment or MapView object, the onMapReady(GoogleMap) method is triggered when the map is ready to be used and provides a non-null instance of GoogleMap.
Here is the full Activity code that does what you need. Register a location listener when the activity loads then when each location changed event occurs.
Here is the sample activity code:
public class MainActivity extends AppCompatActivity implements
OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
LatLng latLng;
GoogleMap mGoogleMap;
SupportMapFragment mFragment;
Marker currLocationMarker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap gMap) {
mGoogleMap = gMap;
mGoogleMap.setMyLocationEnabled(true);
buildGoogleApiClient();
mGoogleApiClient.connect();
}
protected synchronized void buildGoogleApiClient() {
Toast.makeText(this,"buildGoogleApiClient",Toast.LENGTH_SHORT).show();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onConnect
I am developing an app that whenever you click on the get location (gpsBtn), GPS will be enabled and the Location of the user will be shown in a TextView. I get java.lang.NullPointerException error,the app has stops unexpectedly. How do I fix this?
public class MainActivity extends AppCompatActivity {
public LocationManager lm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, new MyLocationListener());
Button gpsBtn = (Button)findViewById(R.id.getLocation);
gpsBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showCurrentLocation();
}
});
public void showCurrentLocation() {
// TODO Auto-generated method stub
final TextView textView=(TextView)findViewById(R.id.textView);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
textView.setText(String.valueOf(location.getLatitude()));
}
class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#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
}
}
Android manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mehrdad.myapplication" >
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
try.....move your final TextView textView=(TextView)findViewById(R.id.textView); to the onCreate() method. Also add textView.setText(String.valueOf(location.getLatitude())); line inside the try and catch block.
try{
textView.setText(String.valueOf(location.getLatitude()));
}catch(Exception e){
// exception occurs......
}
FULL CODE
public class MainActivity extends AppCompatActivity {
public LocationManager lm;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, new MyLocationListener());
textView = (TextView)findViewById(R.id.textView);
Button gpsBtn = (Button)findViewById(R.id.getLocation);
gpsBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showCurrentLocation();
}
});
public void showCurrentLocation() {
// TODO Auto-generated method stub
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
try{
textView.setText(String.valueOf(location.getLatitude()));
}catch(Exception e){
// exception occurs......
}
}
class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#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
}
}
i finally reached an app that get's the GPS position of the user, but i reached it implementing LocationListener. it works fine, but i need to do it without implementing it, because i have to do a class that doesn't implement methods.
I searched for a lot of tutorials and check a lot of websites and i try to transform my code to not implement LocationListener but i can't do it, every thing i tested broken my app and stop getting the GPS position of the user.
Please, if someone expert on this can transform my code for not be using "implements LocationListener" i'll be grated to him
this is the code to transform:
public class GpsMiniActivity extends Activity implements LocationListener{
private LocationManager mLocMgr;
private TextView tv1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout rl = new FrameLayout(this.getApplicationContext());
LinearLayout ll= new LinearLayout(this.getApplicationContext());
ll.setOrientation(LinearLayout.VERTICAL);
setContentView(rl);
rl.addView(ll);
tv1=new TextView(getApplicationContext());
ll.addView(tv1);
//setContentView(R.layout.main);
mLocMgr = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER,
500, 0, this);
}
#Override
public void onLocationChanged(Location location) {
tv1.setText("Lat " + location.getLatitude() + " Long " + location.getLongitude());
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
public class GpsMiniActivity extends Activity {
private LocationManager mLocMgr;
private TextView tv1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout rl = new FrameLayout(this.getApplicationContext());
LinearLayout ll= new LinearLayout(this.getApplicationContext());
ll.setOrientation(LinearLayout.VERTICAL);
setContentView(rl);
rl.addView(ll);
tv1=new TextView(getApplicationContext());
ll.addView(tv1);
//setContentView(R.layout.main);
mLocMgr = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER,
500, 0, ll);
}
}
private LocationListener ll = new LocationListener(){
public void onLocationChanged(Location location) {
tv1.setText("Lat " + location.getLatitude() + " Long " + location.getLongitude());
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
}
There you go.
For that you will have to create a seperate LocationListener outside the onCreate() and give the reference of it to the LocationManager's requestLocationUpdates like this
LocationListener mLocationListener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onLocationChanged(Location location) {
tv1.setText("Lat " + location.getLatitude() + " Long " + location.getLongitude());
}
};
And after that you will have to reference this LocationListener like this inside the onCreate()
mLocMgr = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER,
500, 0, mLocationListener);