2012-05-17 2 views
0

위치 경고 종류의 응용 프로그램을 구현하려고합니다. 하지만 내 응용 프로그램이 열릴 때마다. 내 현재 위치가 null로 표시됩니다.oncreate 메서드에서 위치 업데이트 요청

아래 코드는 제 코드입니다.

package com.hrupin; 

import android.app.Activity; 
import android.app.AlertDialog; 
import android.app.AlertDialog.Builder; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.location.Criteria; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.TextView; 
import android.widget.Toast; 

public class HelloAndroidGpsActivity extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener, LocationListener { 


    private TextView setLat, setLong, destLat, destLong, currLat, currLong, tjd, fromhome, toward; 
    private Button setmyLoc, setDest; 

    private EditText editLat, editLong; 

    private LocationManager orgManager; 
    //private LocationListener orgListener; 
    // private LocationListener destListener = new destListener(); 

    private boolean gps_enabled = false; 
    private boolean network_enabled = false; 

    private String bestProvider; 


    double orginLongitude, orginLatitude, destLongtitude, destLatitude, currLatitude, currLongtitude; 
    float firstLat, firstLang, secLat, secLang; 
    Location destinationLocation = new Location("gps"); 
    Location originLocation = new Location("gps"); 
    Location currLocation = new Location("gps"); 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     setLat = (TextView) findViewById(R.id.setLat); 
     setLong = (TextView) findViewById(R.id.setLong); 
     destLat = (TextView) findViewById(R.id.destLat); 
     destLong = (TextView) findViewById(R.id.destLong); 
     currLat = (TextView) findViewById(R.id.currLat); 
     currLong = (TextView)findViewById(R.id.currLong); 
     tjd = (TextView)findViewById(R.id.setmeter); 
     fromhome = (TextView)findViewById(R.id.destmeter); 
     toward = (TextView)findViewById(R.id.currmeter); 

     setDest = (Button)findViewById(R.id.SetLocation); 

     editLat = (EditText)findViewById(R.id.editLat); 
     editLong = (EditText)findViewById(R.id.editLong); 

     orgManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE); 


     try { 
      gps_enabled = orgManager 
        .isProviderEnabled(LocationManager.GPS_PROVIDER); 
     } catch (Exception ex) { 
      Log.i("gps_enabled", ex.toString()); 
     } 
     try { 
      network_enabled = orgManager 
        .isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
     } catch (Exception ex) { 
      Log.i("network_enabled", ex.toString()); 
     } 

     // don't start listeners if no provider is enabled 
     if (!gps_enabled && !network_enabled) { 
      AlertDialog.Builder builder = new Builder(
        HelloAndroidGpsActivity.this); 
      builder.setTitle("Attention!"); 
      builder.setMessage("Sorry, location is not determined. Please enable location providers"); 
      builder.setPositiveButton("OK", 
        HelloAndroidGpsActivity.this); 
      builder.setNeutralButton("Cancel", 
        HelloAndroidGpsActivity.this); 
      builder.create().show(); 
     } 


     Criteria criteria = new Criteria(); 
     bestProvider = orgManager.getBestProvider(criteria, false); 
     orgManager.requestLocationUpdates(bestProvider, 0, 0, this); 
     Location location = orgManager.getLastKnownLocation(bestProvider); 

     if (location!=null){ 
      setLat.setText("Latitude:" + currLatitude); 
      setLong.setText("Longitude:" + currLongtitude); 
      originLocation.setLatitude(currLatitude); 
      originLocation.setLongitude(currLongtitude); 
     } 
     //else Toast.makeText(getBaseContext(), "Error in GPS", Toast.LENGTH_SHORT).show(); 

     setDest.setOnClickListener(new View.OnClickListener() { 

      public void onClick(View v) { 


       destLat.setText("Lat:"+editLat.getText().toString().trim()); 
       destLong.setText("Long"+editLong.getText().toString().trim()); 

       destLatitude = Double.parseDouble(String.valueOf(editLat.getText().toString().trim())); 
       destLongtitude = Double.parseDouble(String.valueOf(editLong.getText().toString().trim())); 

       destinationLocation.setLatitude(destLatitude); 
       destinationLocation.setLongitude(destLongtitude); 

       float distance = originLocation.distanceTo(destinationLocation); 
       tjd.setText(String.valueOf(distance/1000)+ " Kms "); 

      } 
     }); 
    } 

    /** Register for the updates when Activity is in foreground */ 
    @Override 
    protected void onResume() { 
     super.onResume(); 
     orgManager.requestLocationUpdates(bestProvider, 60000, 1, this); 
    } 

    /** Stop the updates when Activity is paused */ 
    @Override 
    protected void onPause() { 
     super.onPause(); 
     orgManager.removeUpdates(this); 
    } 

    public void onClick(DialogInterface dialog, int which) { 
     if (which == DialogInterface.BUTTON_NEUTRAL) { 
      setLat.setText("Sorry, location is not determined. To fix this please enable location providers"); 
     } else if (which == DialogInterface.BUTTON_POSITIVE) { 
      startActivity(new Intent(
        android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)); 
     } 
    } 

    public void onClick(View v) { 
     // TODO Auto-generated method stub 

    } 

    public void onLocationChanged(Location location) { 
     // TODO Auto-generated method stub 
     if (location != null) { 
      // This needs to stop getting the location data and save the 
      // battery power. 
      //orgManager.removeUpdates(orgListener); 

      currLatitude = location.getLatitude(); 
      currLongtitude = location.getLongitude(); 

      currLocation.setLatitude(currLatitude); 
      currLocation.setLongitude(currLongtitude); 

      currLat.setText(String.valueOf(currLatitude)); 
      currLong.setText(String.valueOf(currLongtitude)); 

      float fromhome = originLocation.distanceTo(currLocation); 

      float toward = currLocation.distanceTo(destinationLocation); 

      HelloAndroidGpsActivity.this.fromhome.setText(String.valueOf(fromhome/1000)+ " Kms "); 
      HelloAndroidGpsActivity.this.toward.setText(String.valueOf(toward/1000) + " Kms "); 

      if (toward/1000 <= 14){ 

       Toast.makeText(getBaseContext(), "You are "+ toward/1000 + " Kms towards Destination ", Toast.LENGTH_SHORT).show(); 
      } 
     } 
    } 


    public void onProviderDisabled(String provider) { 
     // TODO Auto-generated method stub 

    } 

    public void onProviderEnabled(String provider) { 
     // TODO Auto-generated method stub 

    } 

    public void onStatusChanged(String provider, int status, Bundle extras) { 
     // TODO Auto-generated method stub 

    } 
} 

나는 이런 종류의 질문이 백만 번 있었다는 것을 알고있다. 답변에 지정된 모든 방법을 시도했습니다. 그러나 나는 어떤 결과도 얻지 못한다. 도와주세요.

답변

0

당신은에서 onCreate에 requestLocationUpdates를 호출하지 않아야합니다. 흐름은 onCreate -> onStart -> onResume입니다.

+0

그럼 어떻게? 제발 설명해주세요. 미리 감사드립니다. – Satheesh

+0

onCreate에서 호출을 제거 할 수 있습니다. onResume 호출만으로 충분합니다. 액티비티가 시작되면 onCreate가 먼저 호출되고 UI를보기 전에 onResume이 호출됩니다. 따라서 onCreate에서 LocationUpdates를 요청한 다음 다시 onResume을 호출하면 해당 함수를 두 번 호출했습니다.onResume에서 onCreate 및 requestLocationUpdates에 orgManager를 초기화하기 만하면됩니다. getLastKnownLocation을 호출하려면 requestLocationUpdates를 호출 할 필요가 없습니다. –

+0

하지만 그렇게한다면. 나에게 가치있는 보스를 제공합니다. – Satheesh

0

현재 위치를 보려면이 항목을 확인해보세요.

우리의 활동이


public class MainActivity extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener { 
/** Called when the activity is first created. */ 

private EditText showLocation; 
private Button btnGetLocation; 
private ProgressBar progress; 

private LocationManager locManager; 
private LocationListener locListener = new myLocationListener(); 

private boolean gps_enabled = false; 
private boolean network_enabled = false; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    showLocation = (EditText) findViewById(R.id.txtShowLoc); 
    showLocation.setEnabled(false); 

    progress = (ProgressBar) findViewById(R.id.progressBar); 
    progress.setVisibility(View.GONE); 

    btnGetLocation = (Button) findViewById(R.id.btnGetLoc); 
    btnGetLocation.setOnClickListener(this); 

    locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 


} 

@Override 
public void onClick(View v) { 
    // TODO Auto-generated method stub 

    progress.setVisibility(View.VISIBLE); 

    try{ 
     gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 
    } 
    catch(Exception ex){    
    } 
    try{ 
     network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);   
    } 
    catch(Exception ex){ 

    }  

    if (!gps_enabled && !network_enabled) { 
     AlertDialog.Builder builder = new Builder(this); 
     builder.setTitle("Attention!"); 
     builder.setMessage("Sorry, location is not determined. Please enable location providers"); 
     builder.setPositiveButton("OK", this); 
     builder.setNeutralButton("Cancel", this); 
     builder.create().show(); 
     progress.setVisibility(View.GONE); 
    } 

    if (gps_enabled) { 
     locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener); 
    } 
    if (network_enabled) { 
     locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener); 
    }  
} 

private class myLocationListener implements LocationListener{ 

    @Override 
    public void onLocationChanged(Location location) { 
     // TODO Auto-generated method stub 
     if(location!=null){ 

      locManager.removeUpdates(locListener); 

      String Speed = "Device Speed: " +location.getSpeed(); 
      String longitude = "Longitude: " +location.getLongitude(); 
      String latitude = "Latitude: " +location.getLatitude(); 
      String altitiude = "Altitiude: " + location.getAltitude(); 
      String accuracy = "Accuracy: " + location.getAccuracy(); 
      String time = "Time: " + location.getTime(); 

      String cityName=null; 

      Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault()); 
      //public List<Address> addresses= gcd.getFromLocation (double latitude1, double longitude1, int maxResults) 


      List<Address> addresses; 
      try { 
       addresses = gcd.getFromLocation(location.getLatitude(), location.getLongitude(), 1); 
       if (addresses.size() > 0) 
        System.out.println(addresses.get(0).getLocality()); 
       cityName=addresses.get(0).getLocality(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 



      showLocation.setText("City Name: "+cityName+"\n"+Speed + "\n"+longitude + "\n" + latitude + "\n" + altitiude + "\n" + accuracy + "\n" + time); 
      progress.setVisibility(View.GONE); 
     } 
    } 

    @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 

    } 

} 

@Override 
public void onClick(DialogInterface dialog, int which) { 
    // TODO Auto-generated method stub 
    if(which == DialogInterface.BUTTON_NEUTRAL){ 
     showLocation.setText("location is not getting due to location provider"); 

    } 
    else if (which == DialogInterface.BUTTON_POSITIVE){ 
     startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)); 

    } 
}} 

같이하고 main.xml에이


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="vertical" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:weightSum="1"> 
<TextView android:id="@+id/textView1" android:layout_width="match_parent" android:text="My Location is:" android:textSize="25sp" android:layout_height="wrap_content"></TextView> 
<EditText android:layout_height="wrap_content" android:layout_width="match_parent" android:layout_weight="0.24" android:lines="5" android:id="@+id/txtShowLoc"> 
    <requestFocus></requestFocus> 
</EditText> 
<LinearLayout android:id="@+id/linearLayout2" android:layout_height="wrap_content" android:layout_width="match_parent" android:gravity="center"> 
    <ProgressBar android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/progressBar"></ProgressBar> 
</LinearLayout> 
<LinearLayout android:id="@+id/linearLayout1" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center"> 
    <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="Get Current Location" android:id="@+id/btnGetLoc"></Button> 
</LinearLayout> 


입니다

내 매니페스트 파일


<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="rdc.getCurrentLocaion" 
    android:versionCode="1" 
    android:versionName="1.0"> 
<uses-sdk android:minSdkVersion="8" /> 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission> 
<application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true"> 
    <activity android:name=".MainActivity" 
       android:label="@string/app_name"> 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 
      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 

당신이 어떤 문제를 얻는 경우에 알려입니다!

+0

단추를 유지하는 방법으로, 해당 gps 쿼리를 oncreate 메서드 내에 유지하십시오. 당신이 무엇을 말하고 있는지 알아야합니다 – Satheesh

+0

OnCreate 메서드는 first와 OnResume이라고 불렀습니다. 나중에지도가 방황하고있는 상태에서 현재 위치를 얻고 싶을 때 첫 번째 위치를 기다리는 동안 앱이 강제 종료되는 것을 원하지 않으면 나중에해야합니다. 먼저지도가 렌더링 될 때까지 기다렸다가 위치 업데이트 코드를 호출합니다. 또는이 링크를 확인해야합니다. http://stackoverflow.com/questions/7556738/android-gps-location-update-method-does-not-work-in-oncreate-of-map-activity – swiftBoy

+0

솔루션에서 계속 알려줍니다. 위치 공급자를 사용하도록 설정해야하지만 내 네트워크 위치 공급자가 설정에서 사용하도록 설정되어 있습니다. – Jules

0

@Ramdhan 코드 주셔서 감사합니다. 하지만 내 코드에서 실수를 바로 잡았어.

Criteria criteria = new Criteria(); 
     bestProvider = orgManager.getBestProvider(criteria, false); 
     orgManager.requestLocationUpdates(bestProvider, 0, 0, this); 
     Location location = orgManager.getLastKnownLocation(bestProvider); 

    if (location!=null){ 
     setLat.setText("Latitude:" + currLatitude); 
     setLong.setText("Longitude:" + currLongtitude); 
     originLocation.setLatitude(currLatitude); 
     originLocation.setLongitude(currLongtitude); 
    } 

Cheanged 코드 :이 중복으로 코드가 onResume에 전화 때문에

if (location != null) { 
     setLat.setText("Latitude:" + location.getLatitude()); 
     setLong.setText("Longitude:" + location.getLongitude()); 
     originLocation.setLatitude(location.getLatitude()); 
     originLocation.setLongitude(location.getLongitude()); 
    }