2012-02-07 4 views
0

위도와 경도 위치를 표시하는 응용 프로그램을 사용하고 있습니다. 나는 위도를 주려고 노력했다. & lon. 지오 픽스와 심지어 에뮬레이터 컨트롤을 사용하여 값을 얻지 만 출력이 나오지 않습니다. 누구든지 나를 도울 수 있습니까?에뮬레이터에서 현재 고정 위치를 얻는 방법은 무엇입니까?

여기에 내가 얻을 코드와 출력입니다 :

public class LocationTest extends Activity 
{ 
    private LocationManager mgr; 
    private TextView output; 
    private String best; 

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

     mgr = (LocationManager) getSystemService(LOCATION_SERVICE); 
     output = (TextView) findViewById(R.id.output); 
     StringBuilder sb = new StringBuilder("Enabled Provider:"); 

     Criteria criteria = new Criteria(); 
     String provider = mgr.getBestProvider(criteria, true); 

     mgr.requestLocationUpdates(provider, 1000, 0, 
     new LocationListener() 
     { 
      public void onLocationChanged(Location location) {} 
      public void onProviderDisabled(String provider) {} 
      public void onProviderEnabled(String provider) {} 
      public void onStatusChanged(String provider, int status, Bundle extras) {} 
     }); 
     sb.append("\n").append(provider).append(":"); 
     Location location = mgr.getLastKnownLocation(provider); 
     if (location != null) 
     { 
      double lat = location.getLatitude(); 
      double lng = location.getLongitude(); 
      sb.append(lat).append(",").append(lng); 
     } 
     else 
     { 
      sb.append("No Location"); 
     } 
     output.setText(sb); 
    } 
} 

출력 :

사용 제공자 : GPS : 당신은 당신의 LocationListenerpublic void onLocationChanged(Location location) {}에 코드를 삽입 할 필요가 없음 위치

답변

0

. 이것은 위치 변경에 대한 정보입니다. (대부분 에뮬레이터에 것)

getLastKnownLocation() 당신에게 현재 위치를 제공하지 않지만, 마지막으로 알려진 위치.

Android SDK의 DDMS를 사용하여 GPS 위치를 알립니다. 전화는 onLocationChanged()입니다. 클래스의 새 위치를 보존하는 방법이 필요합니다 (예 : ActivityLocation 클래스 객체 추가).

+0

전 C 아니에요 당신이 그 (것)들을 [email protected] 날받은 편지함 필요하면 당신은 여전히, 두 개 또는 3 이미지 능숙를해야 할 수도 있습니다 내 위치 매달려. 나는 우리가 먹는 가치를 얻을 필요가있다. 그러면 onLocationChanged (위치 정보)에 코드를 넣어야 할 필요가 있습니까? 그것은 올바르게 올바르게 작동해야합니까? – Nikunj

+0

상관 없어요. 첫 번째 위치 이벤트는 * onLocationChanged() *로 전송됩니다. 앞에서 설명한 것처럼 getLastKnownLocation은 null 일 수 있지만 onLocationChanged()는 유효한 Location 객체를 제공합니다. – m0skit0

+0

당신이 말했듯이 onLocationChanged()에 코드를 넣으려고 했는데도 응용 프로그램이 좌표를 표시하지 않습니다. – Nikunj

0

모의 위치를 ​​수신하도록 에뮬레이터를 설정 했습니까 ?? 하지 IF, 그렇게하고 내 코드 여기

를 작동하는지 확인하기 위해 그것을 축복하는 텔넷 모의 위치를 ​​전송하고 그것을 잘 (긴 하나) 작동 : 당신이 OnLocation에서 변경된 부분을 필요 ;-)

package tfe.rma.ciss.be; 

import java.io.BufferedReader; 
import java.util.List; 


import android.content.ComponentName; 
import android.content.Context; 
import android.content.Intent; 
import android.content.ServiceConnection; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.graphics.Canvas; 
import android.graphics.Point; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.location.LocationProvider; 
import android.os.Bundle; 
import android.os.IBinder; 

import android.util.Log; 
import android.view.Menu; 
import android.view.MenuInflater; 
import android.view.MenuItem; 
import android.view.MotionEvent; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.LinearLayout; 
import android.widget.TextView; 
import android.widget.Toast; 

import com.google.android.maps.GeoPoint; 
import com.google.android.maps.MapActivity; 
import com.google.android.maps.MapController; 
import com.google.android.maps.MapView; 
import com.google.android.maps.MyLocationOverlay; 
import com.google.android.maps.Overlay; 
import com.google.android.maps.MapView.LayoutParams; 

public class TheMap extends MapActivity implements LocationListener 
{ // public ServiceMenace serviceMenace; 
    public MyInterface monInterface ; 
// public MonService monservice; 
    static final String tag = "Main"; // for Log 
    private MapView mapView = null; 
    private MapController mapController = null; 
    TextView txtInfo; 
    LocationManager lm; 
    StringBuilder sb; 
    int noOfFixes = 0; 
    double latitude=53, longitude= 4.16; 
    GeoPoint p,P2, p3; 
    double lat=53, latTest, longTest ; 
    double lng=4, A=2 ; 
    int clientID= 2; 
    BufferedReader bufferedReader= null; 
    public String update="", Data=""; 
    Intent myIntent; 
    private EditText goLat; 
    private EditText goLon; 

    private MyLocationOverlay me=null; 
    double i= 3; 
    Point screenP3ts = new Point(); 

    String _lat = "" , _long=""; 

    /*public void onReceive(Context contex,Intent intent){ 

     Data = intent.getStringExtra("datas"); 

    }*/ 

     @Override 
     protected boolean isLocationDisplayed() { 
     return false; 
     } 

    class MapOverlay extends com.google.android.maps.Overlay 
    { 
     @Override 
     public boolean draw(Canvas canvas, MapView mapView, 
     boolean shadow, long when) 
     { 
      super.draw(canvas, mapView, shadow);     

      //---translate the GeoPoint to screen pixels--- 
      Point screenPts = new Point(); 
      mapView.getProjection().toPixels(p, screenPts); 

      //---add the marker--- 
      Bitmap bmp = BitmapFactory.decodeResource(
       getResources(), R.drawable.blue);    
      canvas.drawBitmap(bmp, screenPts.x-15, screenPts.y-30, null); 



//   Point screenP2ts = new Point(); 
//   mapView.getProjection().toPixels(P2, screenP2ts); 
//    
//   //---add the marker--- 
//   Bitmap bmp2 = BitmapFactory.decodeResource(
//    getResources(), R.drawable.node_safe);    
//   canvas.drawBitmap(bmp2, screenP2ts.x-15, screenP2ts.y-30, null); 
//    
//    




      //---add the marker--- 
      Bitmap bmp3 = BitmapFactory.decodeResource(
       getResources(), R.drawable.maps_position_marker);    
      canvas.drawBitmap(bmp3, screenP3ts.x-15, screenP3ts.y-30, null); 


      return true; 
      } 
     public boolean onCreateOptionsMenu(Menu menu) { 
      MenuInflater inflater = getMenuInflater(); 
      inflater.inflate(R.menu.menu, menu); 
      return true; 
     } 

     @Override 
     public boolean onTouchEvent(MotionEvent event, MapView mapView) 
     { 
      //---when user lifts his finger--- 
      if (event.getAction() == 1) {     
       GeoPoint p = mapView.getProjection().fromPixels(
        (int) event.getX(), 
        (int) event.getY()); 
        Toast.makeText(getBaseContext(), 
         p.getLatitudeE6()/1E6 + "," + 
         p.getLongitudeE6() /1E6 , 
         Toast.LENGTH_SHORT).show(); 
      }        
      return false; 
     }   

    } 
    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     switch (item.getItemId()) { 
      case R.id.icon:  
      myIntent = new Intent (this, VisClass.class); 
      startActivity(myIntent);     
           break; 
      case R.id.text:  
      myIntent = new Intent (this, InfraredClass.class); 
      startActivity(myIntent); 
           break; 
      case R.id.icontext: 
      myIntent = new Intent (this, RadarClass.class); 
      startActivity(myIntent); 
           break; 
      case R.id.menu: 
       myIntent = new Intent (this, menu.class); 
       startActivity(myIntent); 
           break; 
     } 
     return true; 
    } 
    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     MenuInflater inflater = getMenuInflater(); 
     inflater.inflate(R.menu.menu, menu); 
     return true; 
    } 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.map);   
     final MapView mapView = (MapView) findViewById(R.id.mapView); 

     mapView.setBuiltInZoomControls(true); 
//  
     lm = (LocationManager) getSystemService(LOCATION_SERVICE); 

     LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom); 
     View zoomView=mapView.getZoomControls(); 
     zoomLayout.addView(zoomView, 
       new LinearLayout.LayoutParams(
        LayoutParams.WRAP_CONTENT, 
        LayoutParams.WRAP_CONTENT)); 
      mapView.displayZoomControls(true); 
      /* mapView.setSatellite(true); 
      mapView.setStreetView(true); 
      mapView.setTraffic(true);*/ 
      mapView.setBuiltInZoomControls(true); 
      mapController=mapView.getController(); 
      String coordinates[] = {"53", "4.6"};//schuman/ 



      //---Add a location marker--- 
      MapOverlay mapOverlay = new MapOverlay(); 
      List<Overlay> listOfOverlays = mapView.getOverlays(); 
      listOfOverlays.clear(); 
      listOfOverlays.add(mapOverlay); 



      mapView.invalidate(); 


      p = new GeoPoint(
        (int) (lat * 1E6), 
        (int) (lng * 1E6)); 
      mapController.animateTo(p); 
      mapController.setCenter(p); 

      ((Button)findViewById(R.id.goMap)).setOnClickListener(
         new OnClickListener() { 
        @Override 
        public void onClick(View v) { 
         // On récupère notre EditText 
         EditText UserName = ((EditText)findViewById(R.id.getLon)); 
         EditText Password = ((EditText)findViewById(R.id.getLat)); 

         // On garde la chaîne de caractères 
          _lat = UserName.getText().toString(); 
          _long = Password.getText().toString(); 

         latTest = Double.parseDouble(_lat)* 1E6; 
         longTest = Double.parseDouble(_long)* 1E6; 

         p3 = new GeoPoint(
            (int) (latTest), 
            (int) (longTest)); 

         mapView.getProjection().toPixels(p3, screenP3ts); 
          mapController.animateTo(p3); 
          mapController.setCenter(p3); 

         Toast.makeText(TheMap.this, "lat=" + latTest + " et " + "long= " + longTest, Toast.LENGTH_SHORT).show(); 


         } 
         }); 




         ((Button)findViewById(R.id.sat)).setOnClickListener(
           new OnClickListener() { 
          @Override 
          public void onClick(View v) { 
           mapView.setSatellite(true); 


           } 
           }); 

         ((Button)findViewById(R.id.normal)).setOnClickListener(
           new OnClickListener() { 
          @Override 
          public void onClick(View v) { 
           mapView.setSatellite(false); 
           mapView.setStreetView(false); 
           mapView.setTraffic(false); 


           } 
           }); 


         ((Button)findViewById(R.id.traffic)).setOnClickListener(
           new OnClickListener() { 
          @Override 
          public void onClick(View v) { 
           mapView.setTraffic(true); 


           } 
           }); 

         ((Button)findViewById(R.id.street)).setOnClickListener(
           new OnClickListener() { 
          @Override 
          public void onClick(View v) { 
           mapView.setStreetView(true); 


           } 
           }); 




    } 



    @Override 
    protected void onResume() { 
     /* 
     * onResume is is always called after onStart, even if the app hasn't been 
     * paused 
     * 
     * add location listener and request updates every 1000ms or 10m 
     */ 
     lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10f, this); 
     super.onResume(); 
    } 

    @Override 
    protected void onPause() { 
     /* GPS, as it turns out, consumes battery very much */ 
     lm.removeUpdates(this); 
     super.onResume(); 
    } 


    @Override 
    public void onLocationChanged(Location location) { 
     Log.v(tag, "Location Changed"); 

     lat= (int) (location.getLatitude()); 
     lng= (int) (location.getLongitude()); 

     sb = new StringBuilder(512); 

     noOfFixes++; 

     p = new GeoPoint(
       (int) (location.getLatitude()*1E6), 
       (int) (location.getLongitude()*1E6)); 
     mapController.animateTo(p); 
     mapController.setCenter(p); 

     Toast.makeText(this, "Lat= " + lat + " Long= " + lng, Toast.LENGTH_SHORT).show(); 




     } 








    @Override 
    public void onProviderEnabled(String provider) { 
     Log.v(tag, "Enabled"); 
     Toast.makeText(this, "GPS Enabled", Toast.LENGTH_SHORT).show(); 

    } 



    @Override 
    public void onProviderDisabled(String provider) { 
     /* this is called if/when the GPS is disabled in settings */ 
     Log.v(tag, "Disabled"); 

     /* bring up the GPS settings */ 
     Intent intent = new Intent(
       android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
     startActivity(intent); 
    } 

    @Override 
    public void onStatusChanged(String provider, int status, Bundle extras) { 
     /* This is called when the GPS status alters */ 
     switch (status) { 
     case LocationProvider.OUT_OF_SERVICE: 
      Log.v(tag, "Status Changed: Out of Service"); 
      Toast.makeText(this, "GPS prvider: Out of Service", 
        Toast.LENGTH_SHORT).show(); 

      break; 

     case LocationProvider.TEMPORARILY_UNAVAILABLE: 
      Log.v(tag, "Status Changed: Temporarily Unavailable"); 
      Toast.makeText(this, "GPS provider: Temporarily Unavailable", 
        Toast.LENGTH_SHORT).show(); 

      break; 

     case LocationProvider.AVAILABLE: 
      Log.v(tag, "Status Changed: Available"); 
      Toast.makeText(this, "GPS Provider: Available", 
        Toast.LENGTH_SHORT).show(); 
      break; 
     } 
    } 


    @Override 
    protected void onStop() { 
     /* may as well just finish since saving the state is not important for this toy app */ 
     finish(); 
     super.onStop(); 
    } 

    ServiceConnection updateConnection = new ServiceConnection() { 
      public void onServiceConnected1(ComponentName className, IBinder service) { 
        // This is called when the connection with the service has been 
        // established, giving us the service object we can use to 
        // interact with the service. 
//    ServiceMenace ServiceMenace = ((ServiceMenace.UpdateBinder)service).getService(); 
       monInterface = (MyInterface) service ; 
       Log.v("ViewMap.ServiceConnection.onServiceConnected", "connected to the update service"); 
       } 

       public void onServiceDisconnected(ComponentName className) { 
        // This is called when the connection with the service has been 
        // unexpectedly disconnected -- that is, its process crashed. 
        // Because it is running in our same process, we should never 
        // see this happen. 
       Object ServiceMenace = null; 

       Log.v("ViewMap.ServiceConnection.onServiceDisconnected", "disconnected from the update service"); 
       } 

      @Override 
      public void onServiceConnected(ComponentName arg0, IBinder arg1) { 
       // TODO Auto-generated method stub 

      }  
      }; 



    @Override 
    protected boolean isRouteDisplayed() { 
     return false; 
    } 
} 
을 당신이 내 레이아웃이 필요

몰라 경우 여기를

내 레이아웃입니다 : (

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="vertical" android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
> 

<LinearLayout android:id="@+id/zoom" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentTop="true" 
     android:layout_centerHorizontal="true" 
     /> 

    <com.google.android.maps.MapView 
     android:id="@+id/mapView" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:enabled="true" 
     android:clickable="true" 
     android:apiKey="0lcrLCvFHx-8bK4lgE307_CyHXxgbjefMiI3w9w" 
     /> 
     <LinearLayout android:id="@+id/zoom" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentTop="true" 
     android:layout_centerHorizontal="true" 
     /> 

<SlidingDrawer 
     android:id="@+id/drawer" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:handle="@+id/handle" 
     android:content="@+id/content" 
     > 
     <ImageView 
      android:id="@id/handle" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:src="@drawable/tray_handle_normal" 
     /> 

     <LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="vertical" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:id="@id/content" 
android:background="@layout/background" 
> 

    <TableLayout 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:stretchColumns="1,2" 
    > 
    <TableRow> 
     <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:paddingLeft="2dip" 
     android:paddingRight="4dip" 
     android:text="Emplacement : " 
     /> 
     <EditText android:id="@+id/getLat" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:cursorVisible="true" 
     android:editable="true" 
     android:singleLine="true" 
     android:layout_weight="1" 
     android:inputType="numberDecimal" 
     /> 
     <EditText android:id="@+id/getLon" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:cursorVisible="true" 
     android:editable="true" 
     android:singleLine="true" 
     android:layout_weight="1" 
     android:inputType="numberDecimal" 
     /> 
    </TableRow> 
    </TableLayout> 
    <Button android:id="@+id/goMap" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Afficher !" 
    /> 
    <LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android" 
android:orientation="horizontal" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:id="@id/content" 
> 
<Button 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:id="@+id/sat" 
android:text="Satellite"> 
</Button> 

<Button 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:id="@+id/normal" 
android:text="normal"> 
</Button> 

<Button 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:id="@+id/traffic" 
android:text="traffic"> 
</Button> 
<Button 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:id="@+id/street" 
android:text="street"> 
</Button> 
</LinearLayout> 

</LinearLayout> 

    </SlidingDrawer> 

</RelativeLayout> 
+0

예전에 모의 위치를 ​​수신 할 수 있도록 에뮬레이터를 이미 설정했지만 그 후에도 출력이 표시되지 않습니다. 코드는 훌륭하지만 긴 코드입니다. 내 코드에서 문제를 해결할 수 있습니까? – Nikunj

+0

@ m0skit0으로 말하길, 문제는 가장 최근의 알려진 위치를 얻는 것입니다 ... 만약 당신이 locationChanged 방법에 있다면, 그것은 당신의 급식 위치와 같습니다. 당신이 진짜 장치를 가지고 있다면, 마지막으로 알고있는 위치는 아마도 null이 될 것이라는 것이 그 프롤레멘션입니다. 당신은 그것을 얻기 위해 실제 GPS 신호로 외부 활동을 laucnh해야합니다. – youssoua

+0

레이아웃도 지정하십시오. 귀하의 코드를 시도하고 내가 출력을 볼 수 있습니다. – Nikunj

관련 문제