获取位置(纬度和经度)

Posted

技术标签:

【中文标题】获取位置(纬度和经度)【英文标题】:Get Location (Latitude and Longitude) 【发布时间】:2012-11-08 07:44:33 【问题描述】:

我是安卓新手。我写了一个代码。我的目的是当我收到短信时,将我的位置发送到传入的短信号码。

我可以接收和发送短信,但我无法发送我的位置(如纬度和经度)。我怎样才能做到这一点。相信我,我不知道我是怎么做到的。我在 onlocationChange() 方法中写了一些代码。但它没有给我位置。

请给我一个建议。

感谢您的帮助。

这是我的代码:

package com.example.smsmessaging; 

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;

@SuppressLint("UnlocalizedSms")
public class SmsReceiver extends BroadcastReceiver implements LocationListener

    @SuppressLint( "NewApi", "NewApi", "NewApi" )  
    @Override
    public void onReceive(Context context, Intent intent) 
    
        Bundle bundle = intent.getExtras(); 
        SmsMessage[] mesaj = null;  
        String str = "";  
        String sender = ""; 
        if (bundle != null) 
                   

            Object[] obj = (Object[]) bundle.get("pdus");
            mesaj = new SmsMessage[obj.length]; 

            for (int i=0; i<mesaj.length; i++) 
                mesaj[i] = SmsMessage.createFromPdu((byte[])obj[i]);                 
                sender = mesaj[i].getOriginatingAddress();                    
                str += mesaj[i].getMessageBody().toString();
            

            Toast.makeText(context,"SMS," + sender + " tarafından gönderildi\n\nSMS in içeriği : " + 
            str, Toast.LENGTH_LONG).show(); 

            TelephonyManager tMgr =(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
            String mPhoneNumber = tMgr.getLine1Number();
            String mIMEINumber = tMgr.getDeviceId();
            Toast.makeText(context,"My Phone no : " + mPhoneNumber, Toast.LENGTH_LONG).show();
            Toast.makeText(context,"My IMEI no : " + mIMEINumber, Toast.LENGTH_LONG).show();

            SmsManager sms = SmsManager.getDefault();
            sms.sendTextMessage(sender.toString(), null, str, null, null); 

            Toast.makeText(context,"SMS sent ...", Toast.LENGTH_LONG).show();   

                                 
    

    public void onLocationChanged(Location location) 
        int lat = Integer.parseInt(location.getLatitude()+" ");
        int lon = Integer.parseInt(location.getLongitude()+" ");

        String efe = "Location  " + " Longitude : " + lon  + "\n Latitude : "  + lat;
        Context context = null;

        try 
              SmsManager sms = SmsManager.getDefault();
              sms.sendTextMessage("1555215554", null, efe, null, null);

              Toast.makeText(context,"location sent. Details : " + efe, Toast.LENGTH_LONG).show();                    
         catch (Exception e) 
                    e.printStackTrace();
        

    

    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

    


【问题讨论】:

你的位置的纬度和经度是否发生了变化? 是的,我可以,但我想在收到短信时发送我当前的位置。 你添加权限了吗? 我觉得这几行有问题。 int lat = Integer.parseInt(location.getLatitude()+" "); int lon = Integer.parseInt(location.getLongitude()+" ");您是否尝试用我在下面的答案中提到的代码替换它? 【参考方案1】:

终于找到了解决办法。我编辑的代码如下:

package com.example.donemprojesi;

import java.io.IOException;
import java.util.*;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.Menu;
import android.widget.Toast;
import android.location.*;
import android.content.*;

public class AnaActivity extends Activity 
    Location currentLocation;
    public static double currentLatitude=0.0;
    public static double currentLongitude=0.0;  
    public static String currentAddress=" ";
    public static String str = "efe";
    public static final int NOTIFICATION_ID = 1;
    @Override
    public void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ana);
        finish();
        LocationManager locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);

            LocationListener locationListener = new LocationListener() 
                public void onLocationChanged(Location location) 
                    updateLocation(location);
                    SmsManager sms = SmsManager.getDefault();

                    if("efe".equals(str) && SmsReceiver.flag == true)
                        try
                            sms.sendTextMessage(SmsReceiver.sender.toString(), null,"Koordinatlar : Enlem = " +currentLatitude + 
                                    ", Boylam = " +currentLongitude, null, null);

                            sms.sendTextMessage(SmsReceiver.sender.toString(), null,"Adres : " + currentAddress + 
                                    " Haritadaki Konum : " + "https://maps.google.com/maps?q=" + currentLatitude + 
                                    "," + currentLongitude, null, null);
                        catch(Exception ex)
                            Toast.makeText(getApplicationContext(), "Mesaj gönderiminde bir hata ile karşılaşıldı...", Toast.LENGTH_SHORT).show();
                            sms.sendTextMessage(SmsReceiver.sender.toString(), null,"Konum gönderiminde bir hata ile karşılaşıldı...", null, null);
                        
                        finally
                            SmsReceiver.flag =false;
                            finish();
                        
                    
                
                public void onStatusChanged(
                        String provider, int status, Bundle extras) 
                public void onProviderEnabled(String provider) /*Toast.makeText(getApplicationContext(), "GPS Enabled", Toast.LENGTH_SHORT).show();*/
                public void onProviderDisabled(String provider) /*Toast.makeText(getApplicationContext(), "GPS Disabled", Toast.LENGTH_SHORT).show();*/
            ;

            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
            bildirim();
    

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
        getMenuInflater().inflate(R.menu.activity_ana, menu);
        return true;
    

    public void bildirim()

        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

        int icon = android.R.drawable.ic_menu_view;
        CharSequence ticketText = "GPSMS Started";
        long when = System.currentTimeMillis();

        Notification notification = new Notification(icon, ticketText, when);

        Context context = getApplicationContext();
        CharSequence contentTitle = "GPSMS";
        CharSequence contentText = "GPSMS Enabled";
        Intent notificationIntent = new Intent(this, AnaActivity.class);
        notificationIntent.addFlags(Notification.FLAG_ONGOING_EVENT);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, notification);
        mNotificationManager.notify(BIND_AUTO_CREATE, notification);    
    

    public String getAddress()
        try
            Geocoder gcd = new Geocoder(this, Locale.getDefault());
            List<Address> addresses = gcd.getFromLocation(currentLatitude, currentLongitude,100);
            if (addresses.size() > 0) 
                StringBuilder result = new StringBuilder();

                    Address address =  (Address) addresses.get(0);
                    int maxIndex = address.getMaxAddressLineIndex();
                    for (int x = 0; x <= maxIndex; x++ )
                        if(address.getAddressLine(x) != null)
                            result.append(address.getAddressLine(x)).append("\n");
                        
                                   
                    if(address.getLocality() !=null)
                        result.append(address.getLocality()).append("\n");
                    
                    if(address.getPostalCode() !=null)
                        result.append(address.getPostalCode()).append("\n");
                    

                    if(address.getCountryName() !=null)
                        result.append(address.getCountryName()).append("\n");
                    
                return result.toString();
            
        
        catch(IOException ex)
            return ex.getMessage().toString();
        
        return "Location not found";
    

    void updateLocation(Location location)
        currentLocation = location;
        currentLatitude = currentLocation.getLatitude();
        currentLongitude = currentLocation.getLongitude();
        currentAddress = getAddress();
       

【讨论】:

我删除了指向sdrv.ms/WCBFRj 的链接,因为它似乎无法访问。如果您有更新的链接,请考虑在此答案中使用 edit。【参考方案2】:
String myLocation = "My current location is: " + "Latitude = "
                + loc.getLatitude() + "Longitude = " + loc.getLongitude();

这段代码对我有用。

【讨论】:

以上是关于获取位置(纬度和经度)的主要内容,如果未能解决你的问题,请参考以下文章

获取位置(纬度和经度)

使用gps从纬度和经度获取当前位置

给定两个位置,如何从谷歌地图获取所有纬度和经度

如何使用纬度和经度获取位置名称或城市?

给定纬度和经度,在 Sencha Touch 中获取位置名称

在不改变我的位置的情况下获取当前位置的经度和纬度