通过EventChannel将Android SMS BroadcastReceiver数据发送到Flutter

时间:2019-01-08 09:06:41

标签: java android flutter

我试图在Android设备上侦听所有传入的SMS消息,然后在收到SMS时在我的Flutter应用中显示吐司。我正在通过EventChannel连接到Flutter,并使用BroadcastReceiver检测SMS。每当广播接收机检测到SMS时,如何发送events.success(message)

我尝试直接在EventChannel内部添加BroadcastReceiver,但这没有用。乱七八糟的短信包似乎也不起作用。

这是我的MainActivity外观:

public class MainActivity extends FlutterActivity{
    public static final String STREAM = "com.myapp.thisapp/stream";
    public static final String TAG = "THIS IS A MESSAGE: ";


    @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    GeneratedPluginRegistrant.registerWith(this);

        new EventChannel(getFlutterView(), STREAM).setStreamHandler(
                new EventChannel.StreamHandler() {

                    @Override
                    public void onListen(Object args, final 
EventChannel.EventSink events) {
                        //Send events.success() when SMS received
                        Log.w(TAG, "adding listener");
                    }

                    @Override
                    public void onCancel(Object args) {
                        Log.w(TAG, "cancelling listener");
                    }
                }
        );
  }

}

这是我的BroadcastReceiver的代码:

public class IncomingSmsBroadcastReceiver extends BroadcastReceiver {

    private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";

    @Override
    public void onReceive(final Context context, final Intent intent) {

        if (intent != null && SMS_RECEIVED.equals(intent.getAction())) {
            final SmsMessage smsMessage = extractSmsMessage(intent);
            processMessage(context, smsMessage);
        }

    }

    private SmsMessage extractSmsMessage(final Intent intent) {

        final Bundle pudsBundle = intent.getExtras();
        final Object[] pdus = (Object[]) pudsBundle.get("pdus");
        final SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[0]);

        return smsMessage;

    }

    private void processMessage(final Context context, final SmsMessage smsMessage) {

        //TODO: Send message to event channel
    }

}

每当BroadCastReceiver遇到SMS时,我都希望将消息的内容发送到EventChannel,EventChannel将把消息文本发送到Flutter前端。我该怎么做?

3 个答案:

答案 0 :(得分:1)

这是您应该在MainActivity中使用的结果,存储

        public class MainActivity extends FlutterActivity{
            public static final String STREAM = "com.myapp.thisapp/stream";
            public static final String TAG = "THIS IS A MESSAGE: ";
            public Result resultLater;


            @Override
          protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            GeneratedPluginRegistrant.registerWith(this);

            new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
                    new MethodCallHandler() {
                        @Override
                        public void onMethodCall(MethodCall call, Result result) {
                            //store the reference for later access
                            resultLater = result;
                        }
                    });

           }

         public class IncomingSmsBroadcastReceiver extends BroadcastReceiver {

         private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";

          @Override
          public void onReceive(final Context context, final Intent intent) {

            if (intent != null && SMS_RECEIVED.equals(intent.getAction())) {
                final SmsMessage smsMessage = extractSmsMessage(intent);
                processMessage(context, smsMessage);
            }

        }

          private SmsMessage extractSmsMessage(final Intent intent) {

            final Bundle pudsBundle = intent.getExtras();
            final Object[] pdus = (Object[]) pudsBundle.get("pdus");
            final SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[0]);

            return smsMessage;

         }

       }

       private void processMessage(final Context context, final SmsMessage smsMessage) {

            //here send back result, like this
            if(smsMessage.getMessageBody()!=null){
                 result.success(smsMessage.getMessageBody());
            }else{
                 result.error("Error", "Sms not found", null);
            }

         }

  }

现在在您的主要活动中使sms广播成为子类,并在下面声明。并在收到短信时访问结果。从颤抖的一面,像往常一样拨打频道即可。

遵循docs sample的引用。

答案 1 :(得分:1)

根据您的第一条评论Laksh22,是可以的。

为“活动”创建一个构造函数,如下所示:

     _yourclassnameState() {
       platform.setMethodCallHandler(JavaMethodHandler);
     }

然后实现响应的处理程序

       Future<dynamic> JavaMethodHandler(MethodCall methodcall) async
       {
         switch(methodcall.method)
          {
           case 'SMSRecived':
            print('DataRecived is' + methodcall.arguments);
            break;
           default:
            break;
         }
       }

然后在“ BroadcastReceiver”中使用此代码来调用flutter方法:

    MethodChannel channel =new MethodChannel(view,CHANNEL);
    channel.invokeMethod("SMSRecived",args, new MethodChannel.Result() {
        @Override
        public void success(Object o) {
            System.out.println(o);
        }

        @Override
        public void error(String s, String s1, Object o) {

        }

        @Override
        public void notImplemented() {

        }
    });
  

别忘了CHANNEL。双方应该相同。

     

别忘了清单文件。

     

要在应用关闭时接收短信,请使用“ ForegroundService”。不幸的是Flutter尚不支持ForegroundService。您应该使用Java来实现。

答案 2 :(得分:0)

在 EventChannel 的 onListen 方法中注册您的广播接收器

override fun onListen(arguments: Any?, eventSink: EventSink) {

    val receiver = IncomingSmsBroadcastReceiver()

    receiver.setListener(object : SmsReceiveListener() {

       override fun onSmsReceive(sms: String?) {
         eventSink.success(sms)
       }
    })

    val filter = IntentFilter(IncomingSmsBroadcastReceiver.SMS_RECEIVED)
    context.registerReceiver(receiver, filter)
}

SmsReceiveListener 注册到 IncomingSmsBroadcastReceiver 以收听收到的消息。

有关更多详细信息,请查看以下网址:-

https://medium.com/cashify-engineering/event-channel-to-listen-to-broadcast-events-from-android-43a813672896