2016-10-28 2 views
0

Я хочу установить текущее местоположение в TextView. Я пробовал некоторые учебные пособия, но он не работал.Не получать текущее местоположение inTextView

дал все разрешения в манифесте.

Вот мой полный код: -

package com.example.sachin.gps_currentlocation; 

import android.Manifest; 
import android.content.Context; 
import android.content.pm.PackageManager; 
import android.location.Criteria; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.support.v4.app.ActivityCompat; 
import android.support.v7.app.AppCompatActivity; 
import android.widget.TextView; 
import android.widget.Toast; 

public class GetCurrentGPSLocation extends AppCompatActivity implements LocationListener { 

    LocationManager locationManager; 
    String mprovider; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.current_gps_loaction); 

     locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
     Criteria criteria = new Criteria(); 

     mprovider = locationManager.getBestProvider(criteria, false); 

     if (mprovider != null && !mprovider.equals("")) { 
      if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
       return; 
      } 
      Location location = locationManager.getLastKnownLocation(mprovider); 
      locationManager.requestLocationUpdates(mprovider, 15000, 1, this); 

      if (location != null) 
       onLocationChanged(location); 
      else 
       Toast.makeText(getBaseContext(), "No Location Provider Found Check Your Code", Toast.LENGTH_SHORT).show(); 
     } 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     TextView longitude = (TextView) findViewById(R.id.textView); 
     TextView latitude = (TextView) findViewById(R.id.textView1); 

     longitude.setText("Current Longitude:" + location.getLongitude()); 
     latitude.setText("Current Latitude:" + location.getLatitude()); 
    } 

    @Override 
    public void onStatusChanged(String s, int i, Bundle bundle) { 

    } 

    @Override 
    public void onProviderEnabled(String s) { 

    } 

    @Override 
    public void onProviderDisabled(String s) { 

    } 
} 

Здесь проявляется

 <?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.sachin.gps_currentlocation"> 

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
    <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=".GetCurrentGPSLocation"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
    </application> 

Я перепробовал много tutorails, но не из них дают мне место .. пожалуйста, предложить некоторые необходимые вещи для этого .. .

+0

Вы не получаете текущее местоположение? или вы получаете текущее местоположение, но пытаетесь показать это в текстовом виде? –

+0

Нет, я не получил текущее местоположение –

+0

Удалили ли вы услуги определения местоположения на своем устройстве? – Raghavendra

ответ

-1

здесь код, чтобы просто получить текущее местоположение и показать в тосте

import android.app.AlertDialog; 
import android.app.Service; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.os.IBinder; 
import android.provider.Settings; 
import android.util.Log; 

public class GPSTracker extends Service implements LocationListener { 

private final Context mContext; 

// flag for GPS status 
boolean isGPSEnabled = false; 

// flag for network status 
boolean isNetworkEnabled = false; 

// flag for GPS status 
boolean canGetLocation = false; 

Location location; // location 
double latitude; // latitude 
double longitude; // longitude 

// The minimum distance to change Updates in meters 
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters 

// The minimum time between updates in milliseconds 
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute 

// Declaring a Location Manager 
protected LocationManager locationManager; 

public GPSTracker(Context context) { 
    this.mContext = context; 
    getLocation(); 
} 

public Location getLocation() { 
    try { 
     locationManager = (LocationManager) mContext 
       .getSystemService(LOCATION_SERVICE); 

     // getting GPS status 
     isGPSEnabled = locationManager 
       .isProviderEnabled(LocationManager.GPS_PROVIDER); 

     // getting network status 
     isNetworkEnabled = locationManager 
       .isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

     if (!isGPSEnabled && !isNetworkEnabled) { 
      // no network provider is enabled 
     } else { 
      this.canGetLocation = true; 
      // First get location from Network Provider 
      if (isNetworkEnabled) { 
       locationManager.requestLocationUpdates(
         LocationManager.NETWORK_PROVIDER, 
         MIN_TIME_BW_UPDATES, 
         MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
       Log.d("Network", "Network"); 
       if (locationManager != null) { 
        location = locationManager 
          .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
        if (location != null) { 
         latitude = location.getLatitude(); 
         longitude = location.getLongitude(); 
        } 
       } 
      } 
      // if GPS Enabled get lat/long using GPS Services 
      if (isGPSEnabled) { 
       if (location == null) { 
        locationManager.requestLocationUpdates(
          LocationManager.GPS_PROVIDER, 
          MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
        Log.d("GPS Enabled", "GPS Enabled"); 
        if (locationManager != null) { 
         location = locationManager 
           .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
         if (location != null) { 
          latitude = location.getLatitude(); 
          longitude = location.getLongitude(); 
         } 
        } 
       } 
      } 
     } 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    return location; 
} 

/** 
* Stop using GPS listener 
* Calling this function will stop using GPS in your app 
* */ 
public void stopUsingGPS(){ 
    if(locationManager != null){ 
     locationManager.removeUpdates(GPSTracker.this); 
    } 
} 

/** 
* Function to get latitude 
* */ 
public double getLatitude(){ 
    if(location != null){ 
     latitude = location.getLatitude(); 
    } 

    // return latitude 
    return latitude; 
} 

/** 
* Function to get longitude 
* */ 
public double getLongitude(){ 
    if(location != null){ 
     longitude = location.getLongitude(); 
    } 

    // return longitude 
    return longitude; 
} 

/** 
* Function to check GPS/wifi enabled 
* @return boolean 
* */ 
public boolean canGetLocation() { 
    return this.canGetLocation; 
} 

/** 
* Function to show settings alert dialog 
* On pressing Settings button will lauch Settings Options 
* */ 
public void showSettingsAlert(){ 
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); 

    // Setting Dialog Title 
    alertDialog.setTitle("GPS is settings"); 

    // Setting Dialog Message 
    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?"); 

    // On pressing Settings button 
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog,int which) { 
      Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
      mContext.startActivity(intent); 
     } 
    }); 

    // on pressing cancel button 
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int which) { 
      dialog.cancel(); 
     } 
    }); 

    // Showing Alert Message 
    alertDialog.show(); 
} 

@Override 
public void onLocationChanged(Location location) { 
} 

@Override 
public void onProviderDisabled(String provider) { 
} 

@Override 
public void onProviderEnabled(String provider) { 
} 

@Override 
public void onStatusChanged(String provider, int status, Bundle extras) { 
} 

@Override 
public IBinder onBind(Intent arg0) { 
    return null; 
}} 

Добавьте эту строку в Gradle файл под зависимостями

compile 'com.android.support:appcompat-v7:24.2.1' 

Добавить эти разрешения файл манифеста выше Applicatin тега

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
<uses-permission android:name="android.permission.INTERNET" /> 

Не забывайте указать местоположение на мобильном телефоне

Теперь называем это в основной деятельности просто получить место

btnShowLocation = (Button) findViewById(R.id.btn); 

    // show location button click event 
    btnShowLocation.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View arg0) { 
      // create class object 
      gps = new GPSTracker(MainActivity.this); 

      // check if GPS enabled 
      if(gps.canGetLocation()){ 

       double latitude = gps.getLatitude(); 
       double longitude = gps.getLongitude(); 

       // \n is for new line 
       Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show(); 
      }else{ 
       // can't get location 
       // GPS or Network is not enabled 
       // Ask user to enable GPS/network in settings 
       gps.showSettingsAlert(); 
      } 

     } 
    }); 

Надеется, что это помогает, дайте мне знать, если вы сталкиваетесь с любой проблемой это полный рабочий кодом я тестировал этот код

+0

Поскольку вы запрашиваете непрерывные обновления местоположения, вы также не должны получать их в обратном вызове 'onLocationChanged()'? В чем смысл повторного запроса обновлений снова, когда вызывается 'getLocation()' для получения актуального местоположения? Почему обновления не отменены, когда они не нужны? (Код не постоянно обновляет объект 'location', поэтому он просто расточает батарею.) В чем смысл сновазывать' location.getLatitude() 'и' location.getLongitude() 'в' getLatitude() 'и' getLongitude() ', если это уже сделано в' getLocation() '? –

0

Если вы тестируете устройство для зефира, вы даете первое динамическое разрешение

if (Build.VERSION.SDK_INT >= 23) { 
      if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
       // TODO: Consider calling 
       ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 
         PERMISSION_FINE_LOCATION); 
      } else { 
       tv.setText("here yourcode"); 

      } 
     } else { 
      tv.setText("here yourcode"); 
     } 
} 


@Override 
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { 
     super.onRequestPermissionsResult(requestCode, permissions, grantResults); 
     switch (requestCode) { 
      case PERMISSION_FINE_LOCATION: { 
       if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
        // permission was granted 
        tv.setText("yourcode"); 
       } else { 
        // permission denied 
        Toast.makeText(MainActivity.this, "Request not granted", Toast.LENGTH_SHORT).show(); 
       } 
       break; 


      } 
     } 
    } 

выше - код для динамического разрешения для местоположения. И это работа для меня.

0

Этого надрез коды работает с GoogleMaps, так что вы можете реализовать эту логику:

public Handler handler; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    ... 
    //put handler in to recieve message object with long/lat from onLocationChanged 
    //to enable smoothly location changing in your TextView 
    handler = new Handler(){ 
     @Override 
     public void handleMessage(Message msg) { 

      Double long = msg.getData().getDouble("longitude"); 
      Double lat = msg.getData().getDouble("latitude"); 

      String myLocation = String.valueOf(long) + " " + String.valueOf(lat); 

      textView.setText(myLocation); 
     } 
    }; 
} 

А вот пример вашего onLocationChanged метода:

@Override 
public void onLocationChanged(final Location location) { 

    Thread thread = new Thread(new Runnable() { 
     @Override 
     public void run() { 
      Double latitude = location.getLatitude(); 
      Double longitude = location.getLongitude(); 

      Bundle bundle = new Bundle(); 
      bundle.putDouble("latitude", latitude); 
      bundle.putDouble("longitude", longitude); 

      Message message = new Message(); 
      message.setData(bundle); 

      handler.sendMessage(message); 
     } 
    }); 
    thread.start(); 
} 

Хорошее кодирование.

Смежные вопросы