Java 从其他Android应用程序接收数据只工作一次
我正在尝试开发一个简单的应用程序,它从其他android应用程序接收文本,然后打开浏览器 我已经按照此处文档中的描述实施了它: 它起作用,但只有一次。 第一次从其他应用共享文本时,浏览器已正确打开。 但第二次只有我的应用被打开,而不是浏览器 这可能是什么原因Java 从其他Android应用程序接收数据只工作一次,java,android,android-intent,Java,Android,Android Intent,我正在尝试开发一个简单的应用程序,它从其他android应用程序接收文本,然后打开浏览器 我已经按照此处文档中的描述实施了它: 它起作用,但只有一次。 第一次从其他应用共享文本时,浏览器已正确打开。 但第二次只有我的应用被打开,而不是浏览器 这可能是什么原因 public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceSt
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the intent that started this activity
Intent intent = getIntent();
// Get the action of the intent
String action = intent.getAction();
// Get the type of intent (Text or Image)
String type = intent.getType();
// When Intent's action is 'ACTION+SEND' and Type is not null
if (Intent.ACTION_SEND.equals(action) && type != null) {
// When tyoe is 'text/plain'
if ("text/plain".equals(type)) {
handleSendText(intent); // Handle text being sent
}
}
}
private void handleSendText(Intent intent) {
// Get the text from intent
String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
if (sharedText != null) {
openBrowser(sharedText);
}
}
private void openBrowser(String text) {
Toast.makeText(this, text, Toast.LENGTH_LONG).show();
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://example.com/api.php?text=" + text));
startActivity(browserIntent);
}
}
openBrowser
方法是从handleSendText
方法调用的,该方法位于onCreate
方法上,当您第二次打开应用程序时(如果您没有按后退按钮),您的应用程序已创建!所以代码永远不会执行
请在下面检查android活动的生命周期
您可以编辑代码并调用onResume
方法上的openBrowser
方法,或者只需按一下按钮即可调用方法openBrowser