Android共享应用程序对话框显示错误

时间:2013-07-30 05:07:20

标签: android

我在实施菜单以分享我的应用时遇到问题。当我打开具有图标share_button的活动时,会立即显示“共享通过”对话框。我认为这行代码有问题“startActivity(Intent.createChooser(shareIntent(),”Share ...“));”

这是我的代码

private ShareActionProvider mShareActionProvider;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.mainpage, menu);
    MenuItem item = menu.findItem(R.id.menu_item_share);

    mShareActionProvider = (ShareActionProvider) item.getActionProvider();
    mShareActionProvider.setShareHistoryFileName(null);
    // Create the share Intent
    String playStoreLink = "https://play.google.com/store/apps/details?id=" +
        getPackageName();
    String yourShareText = "Install this app " + playStoreLink;
    Intent shareIntent = ShareCompat.IntentBuilder.from(this)
        .setType("text/plain").setText(yourShareText).getIntent();
    // Set the share Intent
    mShareActionProvider.setShareIntent(shareIntent);
    startActivity(Intent.createChooser(shareIntent(), "Share via"));
    return true;
}

菜单项

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

<item android:id="@+id/menu_item_share"
    android:showAsAction="ifRoom"
    android:title="Share"
    android:icon="@drawable/ic_share"
    android:actionProviderClass="android.widget.ShareActionProvider" />

2 个答案:

答案 0 :(得分:0)

像这样改变你的代码

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.mainpage, menu);
    MenuItem item = menu.findItem(R.id.menu_item_share);

    mShareActionProvider = (ShareActionProvider) item.getActionProvider();
    mShareActionProvider.setShareHistoryFileName(null);

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // TODO Auto-generated method stub
    switch (item.getItemId()) {
    case R.id.menu_item_share:


    String playStoreLink = "https://play.google.com/store/apps/details?id=" +
    getPackageName();
    String yourShareText = "Install this app " + playStoreLink;
    Intent shareIntent = ShareCompat.IntentBuilder.from(this)
        .setType("text/plain").setText(yourShareText).getIntent();
    // Set the share Intent
    mShareActionProvider.setShareIntent(shareIntent);
    startActivity(Intent.createChooser(shareIntent(), "Share via"));
        break;

    default:
        break;
    }

    return super.onOptionsItemSelected(item);
}
  • onCreateOptionsMenu会在您的活动致电时致电。
  • 您需要在Share button按下
  • 时启动共享意图
  • 因此,请在onOptionsItemSelected
  • 中调用共享意图

答案 1 :(得分:0)

您必须将此行代码startActivity(Intent.createChooser(shareIntent(), "Share via"));移出到按钮点击处理程序或菜单选择处理程序中。

将调用函数onCreateOptionsMenu()来设置菜单,这将在Activity启动时发生。