在BOOT_COMPLETED之后,BroadcastReceiver无法正常工作

时间:2011-07-29 20:44:09

标签: android sms broadcastreceiver

我正在尝试在boot_completed之后拦截传入的短信,但我在这一行中遇到NullPointerException问题:

Object[] rawMsgs=(Object[])intent.getExtras().get("pdus");

这是我的清单:                   

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

    <application android:icon="@drawable/icon" android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar">
        <receiver android:name=".SMSReceiver" 
            android:permission="android.permission.BROADCAST_SMS"
            > 
            <intent-filter android:priority="1000"> 
                <action     android:name="android.provider.Telephony.SMS_RECEIVED"></action>
                <action android:name="android.intent.action.BOOT_COMPLETED"></action>
            </intent-filter> 
        </receiver>
    </application>

接收器:

public class SMSReceiver extends BroadcastReceiver 
    { 


    private final LocationListener locationListener = new LocationListener() {
          public void onLocationChanged(Location location) {


          }

          public void onProviderDisabled(String provider){}
          public void onProviderEnabled(String provider) {}
          public void onStatusChanged(String provider, int status, Bundle extras) {} 
        };

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


        LocationManager lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE); 
        //Get as fine grained location as possible, while saving battery life.
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        String provider = lm.getBestProvider(criteria, true);
        Toast toast3 = Toast.makeText(context, "Provider: "+provider, Toast.LENGTH_LONG);
        toast3.show();

        Object[] rawMsgs=(Object[])intent.getExtras().get("pdus");

        for (Object raw : rawMsgs) {
            SmsMessage msg=SmsMessage.createFromPdu((byte[])raw);
            SmsManager sms = SmsManager.getDefault();
            if (msg.getMessageBody().toUpperCase().contains("LOC")) {
                Log.w("SMS:"+msg.getOriginatingAddress(),
                            msg.getMessageBody());
                Toast toast1 = Toast.makeText(context, "Phone Number: "+msg.getOriginatingAddress()+" Message: "+msg.getMessageBody(), Toast.LENGTH_LONG);
                toast1.show();
                abortBroadcast();

                if(provider!=null){


                    lm.requestLocationUpdates(provider, 0, 0, locationListener);

                    if(lm != null)
                    {

                        Location last_good = lm.getLastKnownLocation(provider);
                        if(last_good != null)
                        {
                            Toast.makeText(context, "Got Message from " + msg.getOriginatingAddress() + " , Sending" + last_good.toString(),     Toast.LENGTH_SHORT).show();
                            //sendSMS(msg.getOriginatingAddress(), "http://maps.google.com?q=" + last_good.convert(last_good.getLatitude(), Location.FORMAT_DEGREES) + "," + last_good.convert(last_good.getLongitude(), Location.FORMAT_DEGREES), context);

                            //sendSMS(msg.getOriginatingAddress(), last_good.getLatitude() + "," + last_good.getLongitude(), context);
                            sms.sendTextMessage(msg.getOriginatingAddress(), null, last_good.getLatitude() + "," + last_good.getLongitude(), null, null); 
                            lm.removeUpdates(locationListener);
                        }
                        else
                        {
                            lm.removeUpdates(locationListener);
                                sendSMS(msg.getOriginatingAddress(),"Location Not Available. Possible Reasons: Phone is Off, GPS is Off, No Satellites in sight", context);

                        }
                    }

                }
                else{
                    sendSMS(msg.getOriginatingAddress(),"Location Not Available. Possible Reasons: Phone is Off, GPS is Off, No Satellites in sight", context);

                }



            }
        }
     }

感谢。

1 个答案:

答案 0 :(得分:16)

这里的问题是你的BroadcastReceiver实现已经映射到两个意图 - android.provider.Telephony.SMS_RECEIVEDandroid.intent.action.BOOT_COMPLETED - 但是在onReceive实现中你没有检查你正在处理的意图。

我的猜测是收到android.intent.action.BOOT_COMPLETEDintent.getExtras()返回null。您可以通过向方法添加一些日志记录并观察logcat窗口(如果您正在使用Eclipse)来确认这一点。

如果您编写服务或广播接收器并将其映射到多个意图,那么检查已收到哪个意图并进行适当处理是一种良好的做法 - 不可或缺。我个人会这样做:

if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
    // boot-related processing here
}
else if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
    // SMS-related processing here
}
else {
    // intent not handled - log as a warning as you've registered to receive it
}

您无法承担故障安全行为。为清楚起见,将意图处理逻辑移动到单独的方法中:

if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
    processBootCompletedIntent(intent);
}
else if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
    processSmsReceivedIntent(intent);
}
else {
    // intent not handled - log as a warning as you've registered to receive it
}

PS - 大多数(如果不是全部)“原生”意图动作字符串在相关类中保持为常量。例如,android.intent.action.BOOT_COMPLETED被定义为Intent.ACTION_BOOT_COMPLETED。使用它们存在的常量,它可以节省您输入错误。

相关问题