android - 将消息从广播传递到活动

时间:2016-05-16 19:07:15

标签: android

我正在阅读一些帖子,但没有一个对我有好的答案。

那么,这是将数据从广播传递到活动而不重新启动活动的最佳方法吗?

其实我正在使用它。

SMSListener:

public class SmsListener extends BroadcastReceiver  {
private OnSmsReceivedListener listener = null;
@Override
public void onReceive(Context context, Intent intent) {

    try {
        if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(intent.getAction())) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                for (SmsMessage smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)) {
                    String messageBody = smsMessage.getMessageBody();
                    String phoneNumber = smsMessage.getDisplayOriginatingAddress();
                    if (listener != null) {
                        listener.onSmsReceived(phoneNumber, messageBody);
                    } 
                }
            }
        }
    } catch (Exception e)
    {
        Log.e("Error", "Some some");
    }
}

public void setOnSmsReceivedListener(Context context) {
    this.listener = (OnSmsReceivedListener) context;    
}
}

OnSmsReceivedListener:

public interface OnSmsReceivedListener {
void onSmsReceived(String sender, String message);
}

的活动:

public class MainActivity extends AppCompatActivity implements OnSmsReceivedListener {
   private SmsListener receiver;

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test);

        /***********/
           receiver = new SmsListener();
        receiver.setOnSmsReceivedListener(this);
    }

    @Override
    public void onSmsReceived(String sender, String message) {
        Log.e("Test", "Sender: "+sender+" - Message: "+message);
    }

}

我的另一个问题是为什么我从未在我的活动中获得日志“测试”。就像监听器总是为空,为什么?

1 个答案:

答案 0 :(得分:1)

您应该在onCreate()

的末尾添加
final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";
IntentFilter intentFilter = new IntentFilter(SMS_RECEIVED_ACTION);
registerReceiver(receiver, intentFilter);

和onPause()

unregisterReceiver(receiver);

在AndroidManifest.xml上添加以下权限

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