简体   繁体   English

仅使用意图来发送数据而无需转到其他类别/活动

[英]Using an intent just to send data without moving to a different class/activity

I have a method set up to send data to my MainActivty: 我已经设置了一种将数据发送到MainActivty的方法:

public void sendPlayerDataMethod() {
    String testt = "thissss is for testing";
    Intent sendPlayerData = new Intent(this, MainActivity.class);
    sendPlayerData.putExtra(Intent.EXTRA_TEXT, testt);
    startActivity(sendPlayerData);
}

Every time this method is called, it then takes the user to the MainActivity, as coded but how do I get it to just send the data without moving to another activity? 每次调用此方法时,它将按照编码将用户带到MainActivity,但是如何获取它以仅发送数据而不转移到另一个活动?

Thanks 谢谢

What I understand from what you wrote : You have an activity called MainActivity it is open and you are trying to send data to it from another activity. 从您写的内容中我了解到:您有一个名为MainActivity的活动,它处于打开状态,并且您正尝试从另一个活动向其发送数据。

Try this if this suits your case : 如果适合您的情况,请尝试以下方法:

Add this to your MainActivity in your manifest : android:launchMode="singleTask" This will prevent your activity from instantiating again and again. 将其添加到清单中的MainActivity中: android:launchMode="singleTask"这将防止您的活动一次又一次地实例化。

Override this method on your MainActivity 在您的MainActivity上重写此方法

@Override
protected void onNewIntent(Intent intent){
   super.onNewIntent(intent);
   //get and use your extra data
}

now when you call your activity via an intent, this onNewIntent method will be fired. 现在,当您通过意图调用活动时,将触发此onNewIntent方法。 Get your extra data there. 在此获取您的额外数据。

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM