如何在服务中收听SMS传递的广播?

时间:2019-09-11 22:12:38

标签: android broadcastreceiver android-service smsmanager

我正在尝试从后台服务发送SMS并在其发送时执行一些操作。

发送SMS可行。但是,即使发送了SMS,广播接收机的 OnReceive 方法也永远不会被调用。

我已经用其他动作测试了广播接收器,并且可以正常工作。

例如添加动作“ android.intent.action.SCREEN_OFF ”就可以了。

它只能与我在 PendingIntent 中发送的自定义操作“ SMS_DELIVERED ”一起使用。

下面是我的代码:

public class SendMessageService extends Service {

private static final String TAG = "SendMessageService";
public static final String SMS_DELIVERED = "SMS_DELIVERED";
private BroadcastReceiver deliveryBroadcastReceiver = null;

@Override
public void onCreate() {
    super.onCreate();

    IntentFilter intentFilter = new IntentFilter();

    intentFilter.addAction(SMS_DELIVERED);

    intentFilter.setPriority(100);

    deliveryBroadcastReceiver = new DeliverReceiver();

    registerReceiver(deliveryBroadcastReceiver, intentFilter);

    Log.d(TAG, "Service onCreate: deliveryBroadcastReceiver is registered.");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Bundle extras = intent.getExtras();

    String phoneNumber = extras.getString("PHONE_NUMBER");
    String msg = extras.getString("msg");

    sendSMS(phoneNumber, msg);

    Log.d(TAG, "onStartCommand: Sent SMS");

    return START_STICKY;
}

private void sendSMS (String phoneNumber, String msg){

    PendingIntent deliveredPI = PendingIntent.getBroadcast(getApplicationContext(), 0,
            new Intent(SMS_DELIVERED), 0);

    SmsManager smsManager = SmsManager.getDefault();
    smsManager.sendTextMessage(phoneNumber, null, msg, null, deliveredPI);
}

public class DeliverReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent arg1) {

        Log.d(TAG, "onReceive: Delivered onReceive called");

        // Do something here
    }
}

@Override
public void onDestroy() {
    super.onDestroy();
    unregisterReceiver(deliveryBroadcastReceiver);
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}
}

1 个答案:

答案 0 :(得分:0)

上面的代码实际上很好。似乎问题出在我的电信运营商(EthioTel)没有提供可靠的短信发送报告。