2015-06-30 55 views
0

我是新來的android和堆棧溢出。我正在嘗試非常簡單的應用程序,我想觸發一個事件或行動。即如果我收到一封祝福我的短信「Happy bday」,我需要自動回覆「謝謝」。如何在接收短信時啓動一個動作或活動

發送短信部分我建立了(我知道這很簡單)。如何在收到短信時觸發該事件或行爲或活動?

回答

2

給權限

<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission> <uses-permission android:name="android.permission.READ_SMS" /> <uses-permission android:name="android.permission.SEND_SMS"></uses-permission>

用戶接收機

<receiver android:name="com.example.broadcastreceiver.IncomingSms"> <intent-filter> <action android:name="android.provider.Telephony.SMS_RECEIVED" /> </intent-filter> </receiver>

和類接收機

public class IncomingSms extends BroadcastReceiver { 

    // Get the object of SmsManager 
    final SmsManager sms = SmsManager.getDefault(); 

    public void onReceive(Context context, Intent intent) { 

     // Retrieves a map of extended data from the intent. 
     final Bundle bundle = intent.getExtras(); 

     try { 

      if (bundle != null) { 

       final Object[] pdusObj = (Object[]) bundle.get("pdus"); 

       for (int i = 0; i < pdusObj.length; i++) { 

        SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]); 
        String phoneNumber = currentMessage.getDisplayOriginatingAddress(); 

        String senderNum = phoneNumber; 
        String message = currentMessage.getDisplayMessageBody(); 

        Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + message); 


        // Show Alert 
        int duration = Toast.LENGTH_LONG; 
        Toast toast = Toast.makeText(context, 
           "senderNum: "+ senderNum + ", message: " + message, duration); 
        toast.show(); 

       } // end for loop 
       } // bundle is null 

     } catch (Exception e) { 
      Log.e("SmsReceiver", "Exception smsReceiver" +e); 

     } 
    }  
} 
相關問題