如何从HostApduService向一个Activity发送消息?

4

我希望能够轻松地将字符串传递给一个Activity。需要类似于回调的东西,因为当字符串需要传递时,Activity必须执行某些操作。

public class MyHostApduService extends HostApduService {
    @Override
    public byte[] processCommandApdu(byte[] apdu, Bundle extras) {
        if (selectAidApdu(apdu)) {
            Log.i("HCEDEMO", "Application selected");
            return getWelcomeMessage();
        }
        else {
            if (exchangeDataApdu(apdu)) {
                Log.i("HCEDEMO", "Data exchanged");

                // int _len_ = apdu[4];
                String _data_ = new String(apdu).substring(5, apdu.length - 1);
                // TODO: Send _data_ to an activity...

                return new byte[] { (byte)0x90, (byte)0x00 };
            }
            else {
                Log.i("HCEDEMO", "Received: " + new String(apdu));
                return getNextMessage();
            }
        }
    }
}
2个回答

5
您的问题非常广泛,答案取决于您没有向我们透露的应用程序设计方面的一些因素:

您想要启动活动并将一些数据传递给它

您可以使用意图启动活动,并将参数作为意图额外传递(还请参见this answer):

Intent intent = new Intent(this, YourActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("hcedata", _data_)
this.startActivity(intent);

你想将数据传递给正在运行的活动实例

在这种情况下,你可以从你的活动中注册一个BroadcastReceiver

public class YourActivity extends Activity {
    final BroadcastReceiver hceNotificationsReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if () {
                String hcedata = intent.getStringExtra("hcedata");
                // TODO: do something with the received data
            }
        }
    });

    @Override
    protected void onStart() {
        super.onStart();

        final IntentFilter hceNotificationsFilter = new IntentFilter();
       hceNotificationsFilter.addAction("your.hce.app.action.NOTIFY_HCE_DATA");
        registerReceiver(hceNotificationsReceiver, hceNotificationsFilter);
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(hceNotificationsReceiver);
    }

在您的服务中,您可以向该广播接收器发送一个意图(请注意,您可能需要使用接收器权限限制广播,以防止数据泄露给未经授权的接收器):
Intent intent = new Intent("your.hce.app.action.NOTIFY_HCE_DATA");
intent.putExtra("hcedata", _data_)
this.sendBroadcast(intent);

你想将数据传递到一个活动中,并从你的服务中接收响应

与上面类似,你可以在你的服务中使用广播接收器来从你的活动中得到通知。请注意,你不能绑定到你的HCE服务,因此不能直接从你的活动中调用它的方法。


0

你必须使用Intent机制。

如果要启动Activity,在你的服务中添加以下内容:

Intent intent = new Intent(context, MyActivity.class);
intent.putExtra("extra_key", "values you want to pass");
startActivity(intent);

并且在活动中:

String value = getIntent().getStringExtra("extra_key");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接