使用短信管理器发送带有GPS位置的短信

时间:2017-07-05 10:08:56

标签: android gps sms smsmanager

我需要帮助获取GPS位置并通过短信发送它以及相关消息。我开发了一个紧急按钮应用程序,它应该发送自定义消息+ GPS位置。我正在努力实施GPS定位功能。

没有GPS的原始代码: / 此代码很好用,但它不包含GPS位置 /

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    private EditText customMessage;



@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        customMessage=(EditText)findViewById(R.id.customMessage);

    }

    public void sendText(View view)
    {


        String message = "";
        if (view.getId() == R.id.fab)
        {
            message = customMessage.getText().toString();
        }
        else
        {
            Button sender = (Button)view;
            message = sender.getText().toString();
        }
        //Toast.makeText(this, "Test", Toast.LENGTH_SHORT).show();

        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage("6505551212", null,message + "(Location Here)", null, null);
    }


}

GPS代码: / 代码的问题是当我点击发送按钮时应用程序崩溃但它没有错误 /

import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    private EditText customMessage;



@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        customMessage=(EditText)findViewById(R.id.customMessage);

    }

    public void sendText (View view, String phoneNumber, Location currentLocation) {

        String message = "";
        if (view.getId() == R.id.fab)
        {
            message = customMessage.getText().toString();
        }
        else
        {
            Button sender = (Button)view;
            message = sender.getText().toString();
        }


        SmsManager smsManager = SmsManager.getDefault();
        StringBuffer smsBody = new StringBuffer();
        smsBody.append("http://maps.google.com?q=");
        smsBody.append(currentLocation.getLatitude());
        smsBody.append(",");
        smsBody.append(currentLocation.getLongitude());
        smsManager.sendTextMessage("6505551212", null, smsBody.toString(), null, null);
    }
}

1 个答案:

答案 0 :(得分:-1)

您之前的代码有效,因为其消息长度为&lt; = 160。但是另一条消息包含大于160个字符的url。要解决此问题,您需要以多个部分发送消息。使用下面给出的代码: SmsManager sms = SmsManager.getDefault(); ArrayList<String> parts = sms.divideMessage(messageString); sms.sendMultipartTextMessage(number, null, parts, null, null);