簡體   English   中英

通過ShareActionProvider與社交媒體共享文件

[英]Sharing files with social-media via 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()
}

問題似乎是在離開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");
    }

仍然存在的一個問題是圖標仍然很暗。 我確定我會弄清楚的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM