获取位置(经度和纬度)

问题描述:

我是android新手。我写了一个代码。而我的目的是当我得到一个短信发送我的位置传入短信号码。获取位置(经度和纬度)

我可以得到和发送短信,但我不能发送我的位置(作为经度和纬度)。我怎样才能做到这一点。相信我,我不知道我该怎么做。我在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 

    } 

} 
+0

是你在locationchanged上经纬度? – Sharmilee

+0

是的,我可以,但我想当我收到短信时,然后发送我的当前位置。 –

+0

您是否添加权限? –

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

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(); 
    } 
} 
+0

我编辑了链接到http://sdrv.ms/WCBFRj,因为它似乎无法访问。如果您有更新的链接,请考虑对此答案进行编辑。 –

String myLocation = "My current location is: " + "Latitude = " 
       + loc.getLatitude() + "Longitude = " + loc.getLongitude(); 

此代码已经为我工作。