Hi guys I set this code in my MainActivity.java to add a share button on my app. I´m aware that action bar doesnt work well on previous android versions. One of the customers that has android 2.3 told me that when he hits the phone menu button the apps crash and its forced to close. From version 3.0 to above everythings goes fine, you see the share button. Is there some line of code I could add prior to this function to override o prevent using the share button action if the android version is below 3.0??
This is what I have in my code:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
MenuItem shareItem = (MenuItem) menu.findItem(R.id.action_share);
ShareActionProvider mShare = (ShareActionProvider)shareItem.getActionProvider();
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Download here https://www.apps.com");
mShare.setShareIntent(shareIntent);
return true;
}
My menu.xml file has the following (shows the icon, works ok):
<item android:id="@+id/action_share" android:title="@string/menu_share"
android:icon="@drawable/menu_share" android:showAsAction="ifRoom"
android:actionProviderClass="android.widget.ShareActionProvider"></item>
ActionBar is not available out of the box in Android 2.x. The crash is happening because the MenuItem does not understand getActionProvider()
, which was introduced in API 14 (Android 4.0 Ice Cream Sandwich).
You have two options:
This is what you could do to avoid the crash on 2.x devices. Guard the use of the newer APIs by checking that the device is running Ice Cream Sandwich or later:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
MenuItem shareItem = (MenuItem) menu.findItem(R.id.action_share);
ShareActionProvider mShare = (ShareActionProvider)shareItem.getActionProvider();
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Download here https://www.apps.com");
mShare.setShareIntent(shareIntent);
}
return true;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.