Обмен файлами с социальными сетями через ShareActionProvider - PullRequest
0 голосов
/ 13 октября 2018

Мой код берет файл 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 голосов
/ 14 октября 2018

Проблема заключается в том, что у меня не было настройки Intent до того, как я покинул onCreateOptionsMenu ().

Это глупо и будет переделано, но сработало следующее.

 @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");
    }

Осталась одна проблема - значок все еще темный.Я уверен, я это выясню.

...