1

我想问个问题。
我制作了一个启动和停止后台服务的按钮。
我开设了一个SmsReceiver阅读传入短信的课程。
所以我想在服务开始时调用Sms BroadcastReceiver.
任何想法或任何其他想法如何阅读带有后台服务的短信?

4

1 回答 1

0

如果您已经可以SmsReceiver正常工作,您需要做的就是从 . 注册它。要Service做到这一点,您需要覆盖Service.onCreate()

您的服务应如下所示:

public class SmsService extends Service
{
  private SmsReceiver receiver; //global so we can unregister it when the time comes.
  public void onCreate ()
  {
    super.onCreate ();//call to super
    //make a new intent filter so that all incoming SMS get to you as well
    IntentFilter smsFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
    receiver = new SmsReceiver(); //make a new SmsReceiver
    registerReceiver(receiver, smsFilter); //register the Receiver
  }

  public void onDestroy ()
  {
    unregisterReceiver (receiver); //unregisters the Receiver if Service is killed
    super.onDestroy();
  }
}

在清单中,请务必包含必要的短信权限,并记得Service在清单中声明。

<service android:name=".SmsService" >
</service>
于 2012-12-24T23:20:03.020 回答