我们如何从另一个应用程序启动的应用程序获得响应?

时间:2018-01-04 14:26:04

标签: dart flutter

请有人帮助我如何从我的应用推出的应用中获取数据。

我实际上是在尝试将Google的Tez整合到我的扑克应用中。

我已成功启动该应用以向所请求的UPI付款。但是,我想得到Tez对我的应用程序的回复。

我已经使用url_launcher在我的flutter应用程序中启动Tez应用程序。 很遗憾,我无法收听Tez应用程序的任何回复。  我尝试使用StreamSubscription但无济于事。

我已发布代码以供参考。

代码:

import 'dart:async';

import 'dart:io';

import 'package:flutter/material.dart';

import 'package:url_launcher/url_launcher.dart';

void main() {
  runApp(new MaterialApp(
    title: 'UPI Demo',
    home: new UpiDemo(),
  ));
}

class UpiDemo extends StatefulWidget {
  @override
  _UpiDemoState createState() => new _UpiDemoState();
}

class _UpiDemoState extends State<UpiDemo> {
  String payeeAddress;
  String payeeName;
  String transactionNote;
  String amount;
  String currencyUnit;
  HttpClientRequest request;
  HttpClientResponse response;
  List data = new List();
  Uri uri;

  StreamSubscription<Map<String, Object>> _paymentSubscription;
  Stream<Object> _payment;
  Stream<Object> _currentPayment;

  @override
  void initState() {
    super.initState();
    payeeAddress = "mobilenumber@upi";
    payeeName = "payeename";
    transactionNote = "Test for Deeplinking";
    amount = "1";
    currencyUnit = "INR";

    uri = Uri.parse("upi://pay?pa=" +
        payeeAddress +
        "&pn=" +
        payeeName +
        "&tn=" +
        transactionNote +
        "&am=" +
        amount +
        "&cu=" +
        currencyUnit);
  }

  @override
  void dispose() {
    super.dispose();
    request.close();
  }
  Future launchTez()async {
          try {
            if (await canLaunch(uri.toString())) {

            _paymentSubscription = await launch(uri.toString()).asStream().listen((var result){
              setState((){
                _currentPayment = result;
                print(_currentPayment);
              });
            });
            setState((){
              _currentPayment = _payment;
            });

            } else {
              throw 'Could not launch tez ';
            }
          } catch (exception) {
                     print(exception);
          }
      }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: const Text('UPI Demo'),
      ),
      body: new Center(
        child: new RaisedButton(
          onPressed: (() {
            launchTez();
          }),
          child: new Text('Click to Pay Rs.1.0/-'),
        ),
      ),
    );
  }
}

启动应用程序后,我想听听响应,就像这个例子中的github here

当Tez应用程序启动时,flutter应用程序停止,并且在Tez上完成交易时,flutter应用程序将恢复。

有人可以告诉我该怎么做。 Android示例实际上是在听取响应,但我无法在flutter应用程序中执行此操作。

1 个答案:

答案 0 :(得分:1)

您可以实现一个启动Intent并等待结果的平台频道。

示例:

Android代码 -

package com.yourcompany.example;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import android.util.Log;
import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugins.GeneratedPluginRegistrant;

public class MainActivity extends FlutterActivity {
  private static final String CHANNEL = "upi/tez";

  private MethodChannel.Result callResult;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    GeneratedPluginRegistrant.registerWith(this);
    new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
            new MethodChannel.MethodCallHandler() {
              @Override
              public void onMethodCall(MethodCall call, MethodChannel.Result result) {
                if (call.method.equals("launchUpi")) {
                  Uri uri = Uri.parse(call.argument("url").toString());
                  Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                  startActivityForResult(intent,1);
                    Log.d("Call", "onMethodCall: launchUpi");
                  callResult = result;
                } else {
                  result.notImplemented();
                }
              }
            });
  }


  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data){
      Log.d("Result","Data");
    if(data!=null && callResult!=null) {
      String res = data.getStringExtra("response");
      String search = "SUCCESS";
      if (res.toLowerCase().contains(search.toLowerCase())) {
        callResult.success("Success");
      } else {
        callResult.success("Failed");
      }
    }else{
        Log.d("Result","Data = null (User canceled)");
        callResult.success("User Cancelled");
    }
    super.onActivityResult(requestCode,resultCode,data);
  }
}

飞镖码 -

void main() {
  runApp(new MaterialApp(
    title: "Upi Demo",
    home: new UpiDemo(),
  ));
}

class UpiDemo extends StatefulWidget {
  @override
  _UpiDemoState createState() => new _UpiDemoState();
}

class _UpiDemoState extends State<UpiDemo> {
  static const platform = const MethodChannel('upi/tez');
  String payeeAddress;
  String payeeName;
  String transactionNote;
  String amount;
  String currencyUnit;
  Uri uri;

  String paymentResponse;

  StreamSubscription<Map<String, Object>> _paymentSubscription;
  Stream<Object> _payment;
  Stream<Object> _currentPayment;

  @override
  void initState() {
    super.initState();
    payeeAddress = "mobilenumber@upi";
    payeeName = "payeename";
    transactionNote = "Test for Deeplinking";
    amount = "1";
    currencyUnit = "INR";

    uri = Uri.parse("upi://pay?pa=" +
        payeeAddress +
        "&pn=" +
        payeeName +
        "&tn=" +
        transactionNote +
        "&am=" +
        amount +
        "&cu=" +
        currencyUnit);
  }

  @override
  void dispose() {
    super.dispose();
  }

  Future launchTez()async {
    try {
      final String result = await platform.invokeMethod('launchUpi',<String,dynamic>{"url":uri.toString()});
      debugPrint(result);
    } on PlatformException catch (e) {
      debugPrint(e.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: const Text('UPI Demo'),
      ),
      body: new Center(
        child: new RaisedButton(
          onPressed: (() {
            launchTez();
          }),
          child: new Text('Click to Pay Rs.1.0/-'),
        ),
      ),
    );
  }
}

希望有所帮助!