检测传入消息是否具有关键字

时间:2017-02-01 22:02:51

标签: android

我正在开发一个Android应用程序,我想检查设备上的每个传入消息,以便检测是否有任何传入消息包含我的关键字。我希望这在后台完成(即使应用程序没有运行)。请告诉我该怎么做?

2 个答案:

答案 0 :(得分:0)

使用BroadcastReceiver捕获所有传入消息,然后将消息正文发送到服务以执行所有必需的任务。不要在BroadcastReceiver中执行任何长任务,因为它在主线程上运行。

以下是如何捕获传入短信的示例:

public class SmsListener extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(intent.getAction())) {
            for (SmsMessage smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)) {
                String messageBody = smsMessage.getMessageBody();
                // Send the message body to your custom service.
            }
        }
    }
}

答案 1 :(得分:0)

  1. 在您的清单中进行更改,以便为您的应用提供接收短信的权限(WRITE_SMS,READ_SMS,RECEIVE_SMS)

  2. 创建广播接收器以处理从服务

    收到的SMS意图
    private class SMSBroadcastReceiver extends BroadcastReceiver
    {    
        @Override
        public void onReceive(Context context, Intent intent)
        {
            Bundle intentExtras = intent.getExtras();
    
            String message = "";
    
            if ( extras != null )
            {
                Object[] extras = (Object[]) intentExtras.get( "pdus" );
    
                for ( int i = 0; i < extras.length; i++ )
                {
                    SmsMessage smsmsg = SmsMessage.createFromPdu((byte[])smsextras[i]);
    
                    String message = smsmsg.getMessageBody().toString();
                    //process your message
    
                 }
    
            }
    
        }
    

    }

  3. 创建一个服务类并注册它以接收android.provider.Telephony.SMS_RECEIVED意图过滤器:

    公共类SMSService扩展了Service     {         私人SMSBroadcastReceiver SMSreceiver;         private IntentFilter intentFilter;

        @Override
        public void onCreate()
        {
            super.onCreate();
    
            //SMS event receiver
            SMSreceiver = new SMSBroadcastReceiver();
            intentFilter = new IntentFilter();
            mIntentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
            registerReceiver(SMSreceiver, intentFilter);
        }
    
        @Override
        public void onDestroy()
        {
            super.onDestroy();
            unregisterReceiver(mSMSreceiver);
        }
    }