通过ShareActionProvider与社交媒体共享文件

时间:2018-10-13 19:19:27

标签: android share social-media appcompatactivity shareactionprovider

我的代码获取一个JSON文件,将其转换为QR码并保存该文件。我想做的下一件事是使用ShareActivity机制,让用户通过电子邮件,facebook等共享该文件。

我犯了很多错误,这就是为什么我一直在更新这个问题。在这一点上,我认为我已经设置好了一切,可以告诉我它应该已经设置好了。不幸的是,共享图标是黑色的。我不知道为什么。

我很确定自己在做一些愚蠢的事情,所以我只是在寻找一个可以指引我正确方向的人。

首先菜单XML

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/menu_item_share"
        android:icon="@android:drawable/ic_menu_share"
        android:title="@string/mnu_share"
        app:showAsAction="always"
        app:actionProviderClass="android.support.v7.widget.ShareActionProvider" />

</menu>

接下来是“活动”代码(如果我误判了相关内容,则包括了所有内容。):

public class CreateDineQRCode extends AppCompatActivity {

    public final static int WHITE = 0xFFFFFFFF;
    public final static int BLACK = 0xFF000000;
    public final static int WIDTH = 500;
    public final static int HEIGHT = 500;

    private final static int MAX_TAG_LEN = 23;
    private final static String TAG = "CreateDineQRCode";
    //private final static String DINEQRCODE_DIRECTORY = "dineQRCode";

    private ShareActionProvider mShareActionProvider;
    private String bitmapFilePath = "";

    private final static int MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE = 1; // Used for permission callback

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_dine_qrcode);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);

        testJSONCreation();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        final String tag = TAG + ".onCreatedOptions";
        // Inflate menu resource file
        getMenuInflater().inflate(R.menu.create_dineqr_code_menu, menu);

        // Locate MenuItem with ShareActionProvider
        MenuItem shareItem = menu.findItem(R.id.menu_item_share);
        // Fetch and store ShareActionProvider
        Log.d(tag.substring(tag.length() - MAX_TAG_LEN), "fetch and store action provider.");
        mShareActionProvider = new ShareActionProvider(this);
        MenuItemCompat.setActionProvider(shareItem, mShareActionProvider);

        return super.onCreateOptionsMenu(menu);
    } // onCreateOptionsMenu()

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        String tag = TAG + ".onOptionsItemSelected";
        switch (item.getItemId()) {
            case R.id.menu_item_share:
                //Uri uriToImage = Uri.fromFile(new File(bitmapFilePath));
                Intent shareIntent = new Intent();
                shareIntent.setAction(Intent.ACTION_SEND);
                shareIntent.setType("text/plain");
                shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject here");
                shareIntent.putExtra(Intent.EXTRA_TEXT, "Testing Testing Testing");
                Log.d(tag.substring(tag.length() - MAX_TAG_LEN), "Sharing:: Test Text");
                startActivity(Intent.createChooser(shareIntent, "Sharing Option"));
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }

    }

    void testJSONCreation() {
        final String tag = TAG + ".testJSONCreation";
        NutritionRecord rec = NutritionRecord.createTestNutritionRecord();
        String jsonText = rec.toJSON();

        // find interface elements
        TextView jsonTextView = findViewById(R.id.json_code);
        ImageView qrCodeView = findViewById(R.id.qr_code_view);

        jsonTextView.setText(jsonText);
        try {
            Bitmap bm = encodeAsBitmap(jsonText);
            if (null != bm) {
                qrCodeView.setImageBitmap(bm);
                if (getPermission()) {
                    bitmapFilePath = saveImage(bm);
                } else {
                    Log.d(tag.substring(tag.length() - MAX_TAG_LEN),"Unable to get permission");
                }
            } else {
                Log.e(tag.substring(tag.length() - MAX_TAG_LEN), "Error creating bitmap.");
                bitmapFilePath = null;
            }
        } catch (WriterException e) {
            e.printStackTrace();
        }
    } // testJSONCreation()

    Bitmap encodeAsBitmap(String str) throws WriterException {
        BitMatrix result;
        try {
            result = new MultiFormatWriter().encode(str,
                    BarcodeFormat.QR_CODE, WIDTH, HEIGHT, null);
        } catch (IllegalArgumentException iae) {
            // Unsupported format
            return null;
        }
        int w = result.getWidth();
        int h = result.getHeight();
        int[] pixels = new int[w * h];
        for (int y = 0; y < h; y++) {
            int offset = y * w;
            for (int x = 0; x < w; x++) {
                pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
            }
        }
        Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, WIDTH, 0, 0, w, h);
        return bitmap;
    } // encodeAsBitmap()


    private String saveImage(Bitmap myBitmap) {
        final String tag = TAG + ".saveImage";
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
        File qrCodeDirectory; // + "/" + DINEQRCODE_DIRECTORY);
        qrCodeDirectory = Environment.getExternalStorageDirectory();

        if (!qrCodeDirectory.exists()) {
            Log.d(tag.substring(tag.length() - MAX_TAG_LEN), "Directory does not exist. " + qrCodeDirectory.mkdirs());
            if (!qrCodeDirectory.mkdirs()) {
                Log.e(tag.substring(tag.length() - MAX_TAG_LEN), "Unable to create directory:" + qrCodeDirectory.getAbsolutePath());
                return "";
            }
        }

        try {
            File f = new File(qrCodeDirectory, "DineQRCode" + Calendar.getInstance()
                    .getTimeInMillis() + ".jpg");
            if (!f.createNewFile()) { //give read write permission
                Log.e(tag.substring(tag.length() - MAX_TAG_LEN), "Unable to create file. It already exists.");
                return "";
            }

            FileOutputStream fo = new FileOutputStream(f);
            fo.write(bytes.toByteArray());
            MediaScannerConnection.scanFile(this,
                    new String[]{f.getPath()},
                    new String[]{"image/jpeg"}, null);
            fo.close();
            Log.d(tag.substring(tag.length() - MAX_TAG_LEN), "File Saved::--->" + f.getAbsolutePath());

            return f.getAbsolutePath();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return "";

    } // end saveImage()

    private boolean getPermission() {
        String tag = TAG + ".getPermission";
        boolean result = false;

        Log.d(tag.substring(tag.length() - MAX_TAG_LEN), "Entered.");

        // First Check to see we have permission
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // Permission is not granted
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
                Log.d(tag.substring(tag.length() - MAX_TAG_LEN), "Explain why we need permission.");
                Snackbar.make(findViewById(R.id.create_dine_qrcode_coord_layout), R.string.write_external_permission_explanation, Snackbar.LENGTH_INDEFINITE).show();
            } else {
                // No explanation needed; request the permission
                Log.d(tag.substring(tag.length() - MAX_TAG_LEN), "Request WRITE_EXTERNAL_STORAGE permission");
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE);
            }
        } else {
            Log.d(tag.substring(tag.length() - MAX_TAG_LEN), "WRITE_EXTERNAL_STORAGE: Permission granted.");
            result = true;
        }
        return result;
    } // end getPermission()


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        String tag = TAG + ".onRequestPermissionsResult";
        Log.d(tag.substring(tag.length() - MAX_TAG_LEN),"entered.");
        switch (requestCode) {
            case MY_PERMISSIONS_WRITE_EXTERNAL_STORAGE: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.
                    Log.d(tag.substring(tag.length() - MAX_TAG_LEN), "Permission granted");
                } else {
                    Log.d(tag.substring(tag.length() - MAX_TAG_LEN), "Permission NOT granted.");
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request.
        }
    } // end onRequestPermissionResult()
}

1 个答案:

答案 0 :(得分:0)

问题似乎是我离开CreateOptionsMenu()之前没有Intent设置。

这很笨拙,会重做,但是以下方法可以解决

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        final String tag = TAG + ".onCreatedOptions";
        // Inflate menu resource file
        getMenuInflater().inflate(R.menu.create_dineqr_code_menu, menu);

        // Locate MenuItem with ShareActionProvider
        MenuItem shareItem = menu.findItem(R.id.menu_item_share);
        // Fetch and store ShareActionProvider
        Log.d(tag.substring(tag.length() - MAX_TAG_LEN), "fetch and store action provider.");
        mShareActionProvider = new ShareActionProvider(this);
        mShareIntent = new Intent();
        updateShareIntent();
        mShareActionProvider.setShareIntent(mShareIntent);
        MenuItemCompat.setActionProvider(shareItem, mShareActionProvider);
        shareItem.setEnabled(true);
        if (shareItem.isEnabled()) {
            Log.d(tag.substring(tag.length() - MAX_TAG_LEN), "shareItem is enabled.");
        }

        return super.onCreateOptionsMenu(menu);
    } // onCreateOptionsMenu()

    void updateShareIntent() {
        mShareIntent.setAction(Intent.ACTION_SEND);
        mShareIntent.setType("text/plain");
        mShareIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject here");
        mShareIntent.putExtra(Intent.EXTRA_TEXT, "Testing Testing Testing");
    }

仍然存在的一个问题是图标仍然很暗。我确定我会弄清楚的。