如何基于标准将SMS传递到默认SMS应用程序



我正在寻找一款应用程序,它可以检查设备的速度(如果驾驶等),如果速度低于预设阈值,它会将短信与标准通知一起传递给标准接收设备。如果标准失败(移动过快)。我希望它仍然可以通过短信,支持通知,并自动向发件人发送回复。

目前,这是我只用于接收和发送的:

    package biz.midl.drivereply;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
public class MainActivity extends BroadcastReceiver {
    int MAX_SPEED = 1000; //will have a change method later
    @Override
    public void onReceive(Context arg0, Intent arg1) {
    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);  //context cannot be resolved
    Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (lastKnownLocation.getSpeed() > MAX_SPEED)
        {
            Bundle extras = intent.getExtras();  //intent cannot be resolved
            if (extras == null)
            {
                return;
            }
            abortBroadcast();
            Object[] pdus = (Object[]) extras.get("pdus");
            SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdus[0]);
            String origNumber = msg.getOriginatingAddress();            
            String reply = "The user is busy. Try again later.";
            SmsManager.getDefault().sendTextMessage(origNumber, null, reply, null, null);           
        }
    }
}

我用评论把错误显示在行后。

由于您只对收到短信时的速度感兴趣,因此不需要持续监控您的位置和速度。在这种情况下,您的BroadcastReceiver应该实现为在SMS_RECEIVED广播时启动。要做到这一点,请在您的清单中注册您的接收者,如下所示:

<receiver android:name=".SMSReceiver"> 
    <intent-filter android:priority="999"> 
        <action android:name="android.provider.Telephony.SMS_RECEIVED" /> 
    </intent-filter>
</receiver>

然后,在onReceive()方法中,只需检查最后一个已知位置的速度,并在必要时回复:

@Override
public void onReceive(Context context, Intent intent)
{
    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    if (lastKnownLocation.getSpeed() > MAX_SPEED)
    {
        Bundle extras = intent.getExtras();
        if (extras == null)
        {
            return;
        }
        abortBroadcast();
        Object[] pdus = (Object[]) extras.get("pdus");
        SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdus[0]);
        String origNumber = msg.getOriginatingAddress();            
        String reply = "The user is busy. Try again later.";
        SmsManager.getDefault().sendTextMessage(origNumber, null, reply, null, null);           
    }
}

在上面的例子中,接收器的优先级被设置为最大值(999),因此它将首先接收SMS_RECEIVED广播。然后,如果速度大于您定义的速度限制,广播将中止,并向发件人发送回复。否则,什么都不做,广播将继续发送给其他注册的接收者,比如平台短信应用程序。

最新更新