0

我正在使用 Socket Mobile Capture SDK,它提供了一种从连接蓝牙的条形码扫描仪接收数据的简单方法,假设您可以将方法添加到 android Activity 类。

下面是我创建的 MainActivity 代码。每次使用外部蓝牙扫描仪时,onData 方法都会正确触发。我想将此信息转发给 inAppBrowser。这是可能的还是有更好的方法来做到这一点?

public class MainActivity extends CordovaActivity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        // enable Cordova apps to be started in the background
        Bundle extras = getIntent().getExtras();
        if (extras != null && extras.getBoolean("cdvStartInBackground", false)) {
            moveTaskToBack(true);
        }

        // Set by <content src="index.html" /> in config.xml
        loadUrl(launchUrl);

        Capture.builder(getApplicationContext())
        .enableLogging(BuildConfig.DEBUG)
        .build();        
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onData(DataEvent event) {
        System.out.println("onData fired from MainActivity");
        DeviceClient device = event.getDevice();
        String data = event.getData().getString();
        System.out.println(data);
    }
}

这是我在 index.js 中设置 InAppBrowser 的代码:

var app = {
    // Application Constructor
    initialize: function() {
        document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
    },

    onDeviceReady: function() {        
        this.receivedEvent('deviceready');
        alert('device ready');

        var url = environment == 'Development' ? developmentUrl : productionUrl;        
        inAppBrowserRef = cordova.InAppBrowser.open(url, '_blank', 'location=no'); //open the in app browser with no location bar
        inAppBrowserRef.addEventListener( "loadstop", function() { //Fired when browser is finished loading
            alert('inappbrowser loaded');          
        });        
    },    
    // Once the InAppBrowser finishes loading
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    }
};

app.initialize();
4

1 回答 1

1

我能够通过使用 loadUrl("javascript:onData(\""+data+"\")") 来实现它。以下是我所做的更改:

将 MainActivity.java 的 onData 方法修改为:

@Subscribe(threadMode = ThreadMode.MAIN)
public void onData(DataEvent event) {
    DeviceClient device = event.getDevice();
    String data = event.getData().getString();           
    loadUrl("javascript:onData(\""+data+"\")");
}

将此函数添加到我的 index.js 文件中:

function onData(data) {
    inAppBrowserRef && inAppBrowserRef.executeScript({ code: "onData(\""+data+"\")" 
}); // Clear out the command in localStorage for subsequent opens.
}
于 2018-09-12T16:16:53.917 回答