如何获取当前位置作为地理编码并发送为Android Android?

时间:2015-03-20 00:42:15

标签: java android google-maps geolocation smsmanager

我的短信应用工作正常,只想发送一个位置。这意味着一旦我输入消息并输入电话号码......我点击按钮,然后该位置也作为地理编码发送(我希望收件人可以通过地图打开手机上的链接)...

任何想法如何做到这一点? PS。我知道如何获取位置并将其放在textview中,但我不是在寻找...就像我点击按钮发送短信一样,位置是从位置管理器获取的,并与消息一起发送?

类别:

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;

public class SendSMS extends Activity {

    private Location mLastLocation;

    // Google client to interact with Google API
    private GoogleApiClient mGoogleApiClient;


    Button btnSendSMS;
    EditText txtPhoneNo;
    EditText txtMessage;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_sms);
        btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
        txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
        txtMessage = (EditText) findViewById(R.id.txtMessage);


        btnSendSMS.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                String phoneNo = txtPhoneNo.getText().toString();
                String message = txtMessage.getText().toString();
                displayLocation();
                if (phoneNo.length()>0 && message.length()>0)
                    sendSMS(phoneNo, message);
                else
                    Toast.makeText(getBaseContext(),
                            "Please enter both phone number and message.",
                            Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void displayLocation() {

        mLastLocation = LocationServices.FusedLocationApi
                .getLastLocation(mGoogleApiClient);

        if (mLastLocation != null) {
            double latitude = mLastLocation.getLatitude();
            double longitude = mLastLocation.getLongitude();

            txtMessage.setText("https://www.google.co.id/maps/@"+latitude+","+longitude + txtMessage);

        } else {

            txtMessage
                    .setText("(Couldn't get the location. Make sure location is enabled on the device)");
        }
    }

    //---sends a SMS message to another device---
    private void sendSMS(String phoneNumber, String message)
    {

        PendingIntent pi = PendingIntent.getActivity(this, 0,
                new Intent(this, SendSMS.class), 0);
            SmsManager sms = SmsManager.getDefault();
            sms.sendTextMessage(phoneNumber, null, message, pi, null);


        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";

        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
                new Intent(SENT), 0);

        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
                new Intent(DELIVERED), 0);

        //---when the SMS has been sent---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS sent",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case android.telephony.gsm.SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Generic failure",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case android.telephony.gsm.SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No service",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case android.telephony.gsm.SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Null PDU",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case android.telephony.gsm.SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Radio off",
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(SENT));

        //---when the SMS has been delivered---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS delivered",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(getBaseContext(), "SMS not delivered",
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(DELIVERED));

        android.telephony.gsm.SmsManager smms = android.telephony.gsm.SmsManager.getDefault();
        smms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_send_sm, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

2 个答案:

答案 0 :(得分:0)

我认为您需要先设置LocationManager,然后从getLastKnownLocation获取经度和纬度,而不是等待回拨。之后您可以将位置网址添加到消息中,如下所示:

    LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, new LocationListener() {
        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {}
        @Override
        public void onProviderEnabled(String s) {}
        @Override
        public void onProviderDisabled(String s) {}
        @Override
        public void onLocationChanged(final Location location) {}
    });
    Location myLocation = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
    double longitude = myLocation.getLongitude();
    double latitude = myLocation.getLatitude();
    message+="https://www.google.co.id/maps/@"+latitude+","+longitude;

= - = - edit - = - =

您需要在清单文件中请求访问用户位置的权限,如:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

希望这个帮助

答案 1 :(得分:0)

试试这个(使用Kotlin):

getLocation(context) { location ->
        val msg = location?.let {
            "As of: ${Date(it.time)}, " +
                    "I am at: http://maps.google.com/?q=" + // Note, if you used q=@, then the link will not open in iOS
                    "${it.latitude},${it.longitude} " +
                    "my speed is: ${it.speed}"
        } ?: run {
            "Sorry, it looks GPS is off, no location found\""
        }

        sendSMS(context, address, msg, subId)
}

fun getLocation(context: Context, callback: (Location?) -> Unit) {
    fusedLocationClient = LocationServices.getFusedLocationProviderClient(context)

    fusedLocationClient.lastLocation
            .addOnSuccessListener { location : Location? ->
                val l = location?.let {location}  ?: run { null }
                callback.invoke(l)
            }
}