我正在尝试在按下分享按钮时从其他应用接收数据。应用程序显示在选择器中,当我按下应用程序时,它会打开,但我无法获取文本!!
如果它有任何意义,这是我的启动画面。
Cover.java
public class Cover extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startActivity(new Intent(Cover.this,MainActivity.class));
this.finish();
}
}
MainActivity.java
onCreate(...)
setContentView(....)
Intent intent = getIntent();
String action = intent.getAction();
String type = intent.getType();
Log.d("nikesh"," "+action); //this prints null
Log.d("nikesh"," "+type); //this prints null
if (Intent.ACTION_SEND.equals(action) && type != null) {
if ("text/plain".equals(type)) {
handleSendText(intent);
}
}
private void handleSendText(Intent intent) {
String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);
Log.d("khee",sharedText); //these are
if (sharedText != null) { //not printed
Log.d("khee",sharedText);
textView.setText(sharedText);
// Update UI to reflect text being shared
}
}
的manifest.xml
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
答案 0 :(得分:0)
您使用的是明确的意图,系统和IntentFilters无法解析。
startActivity(new Intent(Cover.this, MainActivity.class));
如果您仍想使用课程开始活动,则必须致电setAction
on the Intent.
Intent intent = new Intent(Cover.this,MainActivity.class);
intent.setAction("android.intent.action.SEND");
startActivity(intent);
或忽略显式部分,只需设置动作
Intent intent = new Intent();
intent.setAction("android.intent.action.SEND");
startActivity(intent);
答案 1 :(得分:0)
我在启动画面中这样做了。 txt是关键所在。
Intent intent = new Intent(Cover.this,MainActivity.class);
intent.setAction("android.intent.action.SEND");
intent.setType("text/plain");
intent.putExtra("txt",getIntent().getStringExtra(Intent.EXTRA_TEXT));
startActivity(intent);
this.finish();
MainActivity.java
Intent intent = getActivity().getIntent();
String action = intent.getAction();
String type = intent.getType();
if (Intent.ACTION_SEND.equals(action) && type != null) {
if ("text/plain".equals(type)) {
handleSendText(intent);
}
}
}
public void handleSendText(Intent intent) {
String sharedText = getActivity().getIntent().getExtras().getString("txt");
if (sharedText != null) {
textView.setText(sharedText);
}
}
非常感谢 @Robert Estivill 让我发现问题!!