如何在仿真器中获取当前的固定位置?

时间:2012-02-07 13:18:16

标签: android

我正在尝试显示纬度和经度位置的应用程序。我试着给拉特。 &安培; 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:没有位置

2 个答案:

答案 0 :(得分:0)

您需要将代码放入public void onLocationChanged(Location location) {}的{​​{1}}。这是通知位置变化的地方。

LocationListener不会为您提供当前位置,但上次已知位置(在模拟器上很可能是 null )。

使用Android SDK的DDMS发信号通知GPS位置。这将调用getLastKnownLocation()。您需要一种方法来保留班级中的新位置(例如,向onLocationChanged()添加Location班级对象。)

答案 1 :(得分:0)

你设置你的模拟器来接收模拟位置吗? 如果没有,那么这样做,并通过telnet发送模拟位置,看它是否有效

这是我的代码,它工作正常(长一个):你需要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;
    }
}
如果你需要我的布局,

不知道

这是我的布局:(你可能仍然需要两个或三个图像资源,如果你需要它们收件箱我在youssoua1@gmail.com

<?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>