萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 獲取 GPS 經緯度並透過簡訊回傳位置完整實作

完整可執行範例:啟動 GPS 定位、監聽位置變更、接收特定指令簡訊(含「gpsl」關鍵字)自動回覆當前經緯度。

核心功能

  1. 向 LocationManager 註冊 GPS_PROVIDER 監聽器,每秒更新一次經緯度。
  2. 註冊簡訊接收 BroadcastReceiver(優先級 10000),攔截含「gpsl」的簡訊並自動回覆座標。
  3. 提供按鈕手動觸發顯示當前座標。

完整程式碼

package com.freshen.test;

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.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class TestLocationActivity extends Activity implements OnClickListener {
    TextView txt;
    Button getLc;
    EditText phoneNumber;
    LocationManager locationManager;
    Location location;
    Context mContext;
    SmsBroadcastReceiver smsbr;
    double latitude, longitude;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mContext = this;

        txt = (TextView) findViewById(R.id.tv_txt);
        txt.setMovementMethod(ScrollingMovementMethod.getInstance());
        getLc = (Button) findViewById(R.id.bt_getLc);
        phoneNumber = (EditText) findViewById(R.id.phone);
        getLc.setOnClickListener(this);

        // 簡訊發送/送達狀態廣播
        registerReceiver(sendMsg, new IntentFilter("SENT_SMS_ACTION"));
        registerReceiver(delivery, new IntentFilter("DELIVERED_SMS_ACTION"));

        // 接收簡訊廣播(高優先級攔截)
        IntentFilter smsitf = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
        smsitf.setPriority(10000);
        smsbr = new SmsBroadcastReceiver();
        registerReceiver(smsbr, smsitf);

        // GPS 定位
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER, 1000, 0, locationListener);
    }

    private final LocationListener locationListener = new LocationListener() {
        @Override public void onLocationChanged(Location loc) {
            if (loc != null) {
                latitude = loc.getLatitude();
                longitude = loc.getLongitude();
                Log.e("GPS", latitude + ":" + longitude);
            }
        }
        @Override public void onProviderDisabled(String p) {}
        @Override public void onProviderEnabled(String p) {}
        @Override public void onStatusChanged(String p, int s, Bundle e) {}
    };

    @Override public void onClick(View v) {
        if (v.getId() == R.id.bt_getLc) {
            Log.e("UI", "開始獲取經緯度");
            setTitle("開始獲取經緯度>>");
            String lc = getLocation();
            if (latitude < 1) txt.setText("獲取定位中...");
            txt.append(lc);
        }
    }

    public String getLocation() {
        return "緯度:(" + latitude + ")\t經度:(" + longitude + ")\n";
    }

    // 發送簡訊
    public void sendMsg(String msg, String num) {
        if (TextUtils.isEmpty(msg) || TextUtils.isEmpty(num)) return;
        SmsManager sms = SmsManager.getDefault();
        Intent sentIntent = new Intent("SENT_SMS_ACTION");
        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, sentIntent, 0);
        Intent deliverIntent = new Intent("DELIVERED_SMS_ACTION");
        PendingIntent deliveryPI = PendingIntent.getBroadcast(this, 0, deliverIntent, 0);
        sms.sendTextMessage(num, null, msg, sentPI, deliveryPI);
    }

    // 發送狀態接收器
    private BroadcastReceiver sendMsg = new BroadcastReceiver() {
        @Override public void onReceive(Context ctx, Intent intent) {
            Toast.makeText(ctx, getResultCode() == Activity.RESULT_OK ? "發送成功!" : "發送失敗!", Toast.LENGTH_LONG).show();
        }
    };
    private BroadcastReceiver delivery = new BroadcastReceiver() {
        @Override public void onReceive(Context ctx, Intent intent) {
            Toast.makeText(ctx, "接收完成!", Toast.LENGTH_LONG).show();
        }
    };

    @Override protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(sendMsg);
        unregisterReceiver(delivery);
        unregisterReceiver(smsbr);
        locationManager.removeUpdates(locationListener);
    }

    // 簡訊內容攔截與自動回覆
    class SmsBroadcastReceiver extends BroadcastReceiver {
        @Override public void onReceive(Context ctx, Intent intent) {
            Object[] pdus = (Object[]) intent.getExtras().get("pdus");
            for (Object o : pdus) {
                SmsMessage sm = SmsMessage.createFromPdu((byte[]) o);
                String sender = sm.getOriginatingAddress();
                String content = sm.getMessageBody();
                if (content.contains("gpsl")) {
                    this.abortBroadcast(); // 阻止其他應用收到
                    SmsManager smg = SmsManager.getDefault();
                    smg.sendTextMessage(sender, null, getLocation(), null, null);
                }
            }
        }
    }
}

Manifest 權限

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

注意事項

  • Android 6.0+ 需動態請求 ACCESS_FINE_LOCATION、SEND_SMS、RECEIVE_SMS 危險權限。
  • 簡訊攔截需 android.provider.Telephony.SMS_RECEIVED 廣播,Android 4.4+ 預設簡訊應用優先處理,第三方應用可能收不到;需設為預設簡訊應用或使用 KitKat 新 API。
  • GPS 定位需在戶外或靠近窗戶,首次定位可能需 30-60 秒。
  • 背景持續定位會大量耗電,實際產品建議使用 FusedLocationProviderClient 結合 Geofencing/Activity Recognition 智慧排程。
copyright © 萬盛學電腦網 all rights reserved