【问题标题】:Send SMS just once for GPS locationGPS定位只需发送一次短信
【发布时间】:2016-11-05 04:29:47
【问题描述】:

我正在制作一个在手机后台运行的应用程序。当我使用 HDPK GPS 发送短信时,应用程序应该以固定数字发送小区的 GPS 坐标。我收到了号码上的 GPS 坐标,但持续不断。我已经用 removeupdates 尝试了一切,但都是徒劳的!请帮我解决这个问题。此外,当应用程序在后台侦听 SMS 时,GPS 和应用程序在收到消息时也会崩溃,尽管我在崩溃前只得到了祝酒词。但如果应用程序在屏幕上运行,它不会崩溃并不断发送坐标消息。

public class RecActivity extends Activity {
double current_lat, current_lng;
boolean flag=true;
// String provider=LocationManager.GPS_PROVIDER;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
BroadcastReceiver SMSbr = new BroadcastReceiver() {

@Override
public void onReceive(Context context,Intent intent) {

Bundle bundle = intent.getExtras();
if (bundle != null) {

Object[] pdus = (Object[]) bundle.get("pdus");
final SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++)
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
if (messages.length > -1) {
String messagebody=messages[0].getMessageBody();
if(messagebody.toString().matches("HDPK GPS"))
{

LocationManager mlocManager = (LocationManager)getSystemService(RecActivity.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();                   

Toast.makeText(RecActivity.this,"GPS STARTED", Toast.LENGTH_LONG)
                                        .show();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000,1, mlocListener);                                 

}

                                                                                           }

}
}

};

IntentFilter SMSfilter = new IntentFilter(SMS_RECEIVED);
this.registerReceiver(SMSbr, SMSfilter);
}

public class MyLocationListener implements LocationListener
{

public void onLocationChanged(Location loc) {
Toast.makeText(RecActivity.this,"GPS WORKING", Toast.LENGTH_LONG).show();
current_lat=loc.getLatitude();
current_lng=loc.getLongitude();
String Text = "My location is: " +

"Latitude = " + current_lat +

"Longitude = " + current_lng;

SmsManager sender=SmsManager.getDefault();
sender.sendTextMessage("9762281814",null,Text , null, null);
Toast.makeText(RecActivity.this, "SMS SENT", Toast.LENGTH_LONG).show();



}



public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
SmsManager sender=SmsManager.getDefault();
sender.sendTextMessage("9762281814",null,"GPS Disabled" , null, null);

}

public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
SmsManager sender=SmsManager.getDefault();
sender.sendTextMessage("9762281814",null,"GPS Enabled" , null, null);

}

 public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub

}

}

}

清单文件:

<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".RecActivity"
android:label="@string/app_name" >
<intent-filter android:priority="100">
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

这是我的代码:

package RecSM.Rec.receiveharsh;

import android.app.Activity;
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.widget.Toast;

public class RecActivity extends Activity {
double current_lat, current_lng;
boolean flag=true;
LocationManager mlocManager;
LocationListener mlocListener;
// String provider=LocationManager.GPS_PROVIDER;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
BroadcastReceiver SMSbr = new BroadcastReceiver() {

@Override
public void onReceive(Context context,Intent intent) {

Bundle bundle = intent.getExtras();
if (bundle != null) {

Object[] pdus = (Object[]) bundle.get("pdus");
final SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++)
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
if (messages.length > -1) {


String messagebody=messages[0].getMessageBody();


if(messagebody.toString().matches("HDPK GPS"))
{

LocationManager mlocManager = (LocationManager)getSystemService(RecActivity.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();                   

Toast.makeText(RecActivity.this,"GPS STARTED", Toast.LENGTH_LONG)
                                        .show();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000,1, mlocListener);                                 

}


}

}
}

};

IntentFilter SMSfilter = new IntentFilter(SMS_RECEIVED);
this.registerReceiver(SMSbr, SMSfilter);
}

public class MyLocationListener implements LocationListener
{

public void onLocationChanged(Location loc) {


Toast.makeText(RecActivity.this,"GPS WORKING", Toast.LENGTH_LONG)
.show();

current_lat=loc.getLatitude();
current_lng=loc.getLongitude();
String Text = "My location is: " +

"Latitude = " + current_lat +

"Longitude = " + current_lng;

SmsManager sender=SmsManager.getDefault();
sender.sendTextMessage("9762281814",null,Text , null, null);
Toast.makeText(RecActivity.this, "SMS SENT", Toast.LENGTH_LONG).show();
mlocManager.removeUpdates(mlocListener);


}



public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
SmsManager sender=SmsManager.getDefault();
sender.sendTextMessage("9762281814",null,"GPS Disabled" , null, null);

}

public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
SmsManager sender=SmsManager.getDefault();
sender.sendTextMessage("9762281814",null,"GPS Enabled" , null, null);

}

public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub

}

}

}

【问题讨论】:

    标签: android gps coordinates


    【解决方案1】:
    String Text = "My location is: " +
    
    "Latitude = " + current_lat +
    
    "Longitude = " + current_lng;
    
    SmsManager sender=SmsManager.getDefault();
    sender.sendTextMessage("9762281814",null,Text , null, null);
    Toast.makeText(RecActivity.this, "SMS SENT", Toast.LENGTH_LONG).show();
    
    mlocManager.removeUpdates(mlocListener); <<<<<<<<<<<< include this
    

    代码对我来说看起来不错。

    你的设备里有 GPS 硬件吗??

    您为什么不尝试从网络提供商处获取位置。 在尝试此代码之前,请确保清单中有 android.permission.internet。

    if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
                    .isConnected()
                    || connectivityManager.getNetworkInfo(
                            ConnectivityManager.TYPE_WIFI).isConnected())
            {
                /*Log.d("vipul", "WIFI or GPRS Connected");*/
                if (locationManager
                        .isProviderEnabled(LocationManager.NETWORK_PROVIDER))
                {
                    Constants.CONNECTED = true;
                    /*Log.v("tripSketch", "NETWORK Provider Enabled");*/
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER, 5000, 1, this);
                } else
                {
                    Constants.CONNECTED = false;
                    /*Log.d("vipul",
                            "Please enable Wireless networks in Location Setting!!");*/
                    Toast.makeText(
                            context,
                            "Please enable Wireless networks in Location Setting!!",
                            10000).show();
                }
    
            } else if (locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER))
            {
                Constants.CONNECTED = true;
                /*Log.d("vipul", "GPS Provider Enabled!");*/
                locationManager.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER, 120000, 100, this);
    
            } else
            {
                /*Log.d("vipul", "Neither GPS NOR EDGE/GPRS CONNECTED");*/
                Constants.CONNECTED = false;
                Toast.makeText(
                        context,
                        "Please connect EDGE/GPRS \nAlso Enable Wireless networks in Location Setting!!",
                        10000).show();
            }
        }
    

    【讨论】:

    • mlocaManager 不是全局的。因此我不能在那里调用它。如果我将其设为全局,则应用程序崩溃
    • 我将 locationmanager 和 listener 设为全局,并根据您的建议添加了行。现在我正在直接在我的单元上测试应用程序。一旦我安装并向它发送短信,当它收到消息时,什么也没有发生。现在,如果我打开应用程序查看界面,然后发送消息,GPS 将被激活,我得到了祝酒词。但很快应用程序崩溃了。有什么想法吗?
    • 是的,我有 GPS 硬件。我在 Sony Xperia Ray ST18i 上运行它。而且正如我告诉你的那样,我的代码向我发送了 GPS 位置,但它无法停止。继续发送。我不知道如何阻止它不断发送更改位置的消息。
    【解决方案2】:

    我不知道为什么,但它以某种方式起作用)))

    package net.learn2develop.SMSMessaging;
    
    import java.util.List;
    import android.annotation.TargetApi;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.location.Criteria;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.os.Build;
    import android.os.Bundle;
    import android.os.Looper;
    import android.telephony.SmsMessage;
    import android.telephony.SmsManager;
    import android.util.Log;
    
    
    public class SmsReceiver extends  BroadcastReceiver implements LocationListener {
    
    String strPhone;
    String strMessage;
    String strGPS;
    
    
    @TargetApi(Build.VERSION_CODES.DONUT)
    @Override
    
    public void onReceive(Context context, Intent intent) {
    
        Bundle bundle = intent.getExtras();
    
        SmsMessage[] msgs = null;
        strPhone = "";
        strMessage = "";
        strGPS="";
    
        if (bundle != null) {
            // ---retrieve the SMS message received---
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];
            for (int i = 0; i < msgs.length; i++) {
                msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
    
                strPhone+=msgs[i].getOriginatingAddress();
                strMessage+=msgs[i].getMessageBody().toString();
    
            }
    
            if (strMessage.contains(":)) ...")){
    
                LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);  
                List<String> providers = lm.getProviders(true);
                /* Loop over the array backwards, and if you get an accurate location, then break out the loop*/
                Location l = null;
    
                final int updateTime = 2000; // ms
                final int updateDistance = 10; // meter
                final Criteria criteria = new Criteria();
                criteria.setCostAllowed(false);
                criteria.setAccuracy(Criteria.ACCURACY_FINE);
                final String p = lm.getBestProvider(criteria, true);
                lm.requestLocationUpdates(p, updateTime, updateDistance,
                        this);
                double[] gps = new double[2];
    
                for (int ii=providers.size()-1; ii>=0; ii--) {
                        l = lm.getLastKnownLocation(providers.get(ii));
                        if (l != null) break;
                }
    
                if (l != null) {
                        gps[0] = l.getLatitude();
                        gps[1] = l.getLongitude();
                        Log.d("gps[0]", "gps[1]");
                }
    
          strGPS= String.valueOf(gps[0]) + " " + String.valueOf(gps[1]);
          sendSMS(strPhone, strGPS);
            }
            }
    }
    
    @TargetApi(Build.VERSION_CODES.DONUT)
    private void sendSMS(String phoneNumber, String message) {
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, null, null);
    }
    
    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
    
    }
    
    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    
    }
    
    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    
    }
    
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
    
    }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-14
      相关资源
      最近更新 更多