我在发送截图时遇到了一个错误。

huangapple go评论64阅读模式
英文:

I'm getting an error while sending a screenshot

问题

当用户点击按钮后,我要求他截取屏幕并将截图发送给另一个朋友。

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
        Bitmap bitmap = getScreenShot(rootView);
        File file = store(bitmap, "文件名");
        shareImage(file);
    }
});

public static Bitmap getScreenShot(View view) {
    View screenView = view.getRootView();
    screenView.setDrawingCacheEnabled(true);
    Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
    screenView.setDrawingCacheEnabled(false);
    return bitmap;
}

public static File store(Bitmap bm, String fileName){
    final String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Screenshots";
    File dir = new File(dirPath);
    if(!dir.exists())
        dir.mkdirs();
    File file = new File(dirPath, fileName);
    try {
        FileOutputStream fOut = new FileOutputStream(file);
        bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
        fOut.flush();
        fOut.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return file;
}

private void shareImage(File file){
    Uri uri = Uri.fromFile(file);
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_SEND);
    intent.setType("image/*");

    intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
    intent.putExtra(android.content.Intent.EXTRA_TEXT, "");
    intent.putExtra(Intent.EXTRA_STREAM, uri);
    try {
        startActivity(Intent.createChooser(intent, "分享截图"));
    } catch (ActivityNotFoundException e) {
        Toast.makeText(this, "没有可用的应用", Toast.LENGTH_SHORT).show();
    }
}

我看到调试时位图的值为空。我的错误消息中也有这些内容。

错误日志图片

我在清单文件中使用了它们。

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}.provider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/provider_path" />
</provider>

请问能帮助我吗?

英文:

As soon as the user clicks the button, I ask him to take a screenshot and send it to another friend.

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
Bitmap bitmap = getScreenShot(rootView);
File file = store(bitmap,&quot;File-Name&quot;);
shareImage(file);
}
});
public static Bitmap getScreenShot(View view) {
View screenView = view.getRootView();
screenView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
screenView.setDrawingCacheEnabled(false);
return bitmap;
}
public static File store(Bitmap bm, String fileName){
final String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + &quot;/Screenshots&quot;;
File dir = new File(dirPath);
if(!dir.exists())
dir.mkdirs();
File file = new File(dirPath, fileName);
try {
FileOutputStream fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
private void shareImage(File file){
Uri uri = Uri.fromFile(file);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType(&quot;image/*&quot;);
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, &quot;&quot;);
intent.putExtra(android.content.Intent.EXTRA_TEXT, &quot;&quot;);
intent.putExtra(Intent.EXTRA_STREAM, uri);
try {
startActivity(Intent.createChooser(intent, &quot;Share Screenshot&quot;));
} catch (ActivityNotFoundException e) {
Toast.makeText(this, &quot;No App Available&quot;, Toast.LENGTH_SHORT).show();
}
}

I see that the bitmap value is "" when I debug. I also have these in my error message.

Error Log Image

I used them in my manifest file.

&lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot; /&gt;
&lt;uses-permission android:name=&quot;android.permission.READ_EXTERNAL_STORAGE&quot; /&gt;
&lt;provider
android:name=&quot;androidx.core.content.FileProvider&quot;
android:authorities=&quot;${applicationId}.provider&quot;
android:exported=&quot;false&quot;
android:grantUriPermissions=&quot;true&quot;&gt;
&lt;meta-data
android:name=&quot;android.support.FILE_PROVIDER_PATHS&quot;
android:resource=&quot;@xml/provider_path&quot; /&gt;
&lt;/provider&gt;

Could you please help me?

答案1

得分: 0

你应该使用这段代码:

button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
                Bitmap bitmap = getScreenShot(rootView);
                File file = store(bitmap, "name.png");

                if (file.exists()) {
                    shareImage(file);
                } else {
                    Log.e("file exist", "NO");
                }
            }
        });



public static Bitmap getScreenShot(View view) {
        View screenView = view.getRootView();
        screenView.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
        screenView.setDrawingCacheEnabled(false);
        return bitmap;
    }

public File store(Bitmap bm, String fileName) {
        final String dirPath = getExternalCacheDir().getAbsolutePath() + "/Screenshots";
        File dir = new File(dirPath);
        if (!dir.exists())
            dir.mkdirs();
        File file = new File(dirPath, fileName);
        try {
            FileOutputStream fOut = new FileOutputStream(file);
            bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
            fOut.flush();
            fOut.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return file;
    }

private void shareImage(File file) {
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(file.getPath()));
        shareIntent.setType("image/*");
        startActivity(Intent.createChooser(shareIntent, "Share Screenshot"));
    }
英文:

You should use this code

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
Bitmap bitmap = getScreenShot(rootView);
File file = store(bitmap, &quot;name.png&quot;);
if (file.exists()) {
shareImage(file);
} else {
Log.e(&quot;file exist&quot;, &quot;NO&quot;);
}
}
});
public static Bitmap getScreenShot(View view) {
View screenView = view.getRootView();
screenView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
screenView.setDrawingCacheEnabled(false);
return bitmap;
}
public File store(Bitmap bm, String fileName) {
final String dirPath = getExternalCacheDir().getAbsolutePath() + &quot;/Screenshots&quot;;
File dir = new File(dirPath);
if (!dir.exists())
dir.mkdirs();
File file = new File(dirPath, fileName);
try {
FileOutputStream fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
private void shareImage(File file) {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(file.getPath()));
shareIntent.setType(&quot;image/*&quot;);
startActivity(Intent.createChooser(shareIntent, &quot;Share Screenshot&quot;));
}
</details>
# 答案2
**得分**: 0
```java
使用以下代码从视图中捕获位图。您的方法将不再起作用,无法再使用绘图缓存。
```java
public void drawBitmap(View view, int width, int height) {
Bitmap bm = Bitmap.createBitmap(width,
height,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bm);
canvas.drawColor(previewBgColor);
view.draw(canvas);
// 将位图存储在目标文件中
File dstFile = new File("路径/至/文件");
storeBitmap(dstFile, bm);
}
public String storeBitmap(File file, Bitmap bmp) {
FileOutputStream stream;
try {
stream = new FileOutputStream(file, false);
bmp.compress(Bitmap.CompressFormat.JPEG, 99, stream);
} catch (Exception e) {
} finally {
stream.close();
}
return file.getPath();
}

如果文件异常仍然存在,请告诉我们。我假设它出现错误是因为位图文件返回了“”空字符串?此处的文档应足以指引您。


<details>
<summary>英文:</summary>
Use this to capture a bitmap from a view. Your method will not work anymore using the drawing cache.

public drawBitmap(View view, int width, int height) {
Bitmap bm = Bitmap.createBitmap(width,
height,
Bitmap.Config.ARGB_8888)

    Canvas canvas = Canvas(bm)
canvas.drawColor(previewBgColor)
view.draw(canvas)
// Store bitmap in dest file,
File dstFile = File(&quot;path/to/file&quot;)
storeBitmap(dstFile, bm)

}

public String storeBitmap(File file, Bitmap bmp) {
FileOutputStream stream;
try {
stream = FileOutputStream(file, false)
bmp.compress(Bitmap.CompressFormat.JPEG,99,it)
} catch (e: Exception) {

   } finally {
stream.close()
}
return file.path
}

If the file exception persists let us know. I am assuming it&#39;s giving that error because the bitmap file returns &quot;&quot;? [The docs here should be enough to get you through.][1]
[1]: https://developer.android.com/training/sharing/send
</details>
# 答案3
**得分**: 0
以下是翻译好的内容:
我能够通过这样的结构解决了这个问题。非常感谢[P Fuster][1]对他所有的帮助。
首先,我们将这些权限添加到清单文件中。
```xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

然后,我们将它们添加到主活动的onCreate方法中。

StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());

现在,让我们为我们的按钮添加点击效果。

share_friends.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
        Bitmap bitmap = getScreenShot(rootView);
        File file = store(bitmap, "name.png");

        if (file.exists()) {
            shareImage(file);
            System.out.println(file.getPath());
        } else {
            Log.e("file exist", "NO");
        }

    }
});

按钮中使用的函数:

public static Bitmap getScreenShot(View view) {
    View screenView = view.getRootView();
    screenView.setDrawingCacheEnabled(true);
    Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
    screenView.setDrawingCacheEnabled(false);
    return bitmap;
}

public File store(Bitmap bm, String fileName) {
    final String dirPath = Environment.getExternalStorageDirectory().getPath() + "/Screenshots";
    File dir = new File(dirPath);
    if (!dir.exists())
        dir.mkdirs();
    File file = new File(dirPath, fileName);
    try {
        FileOutputStream fOut = new FileOutputStream(file);
        bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
        fOut.flush();
        fOut.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return file;
}

private void shareImage(File file) {
    Intent shareIntent = new Intent();
    shareIntent.setAction(Intent.ACTION_SEND);
    shareIntent.setType("image/*");
    shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
    shareIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    startActivity(Intent.createChooser(shareIntent, "Share Screenshot"));
}

问题通过以下方式解决

[1]: https://stackoverflow.com/users/8050896/p-fuster


<details>
<summary>英文:</summary>

I was able to solve the problem with such a structure. Thank you very much to [P Fuster][1] for all his help.


We add these permissions first to the manifests file.

    
    &lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot; /&gt;
    &lt;uses-permission android:name=&quot;android.permission.READ_EXTERNAL_STORAGE&quot; /&gt;

then we add them to the onCreate method in mainActivity. 

    StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
    StrictMode.setVmPolicy(builder.build());

Now let&#39;s give the click effect of our button.

    share_friends.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                View rootView = getWindow().getDecorView().findViewById(android.R.id.content);
                Bitmap bitmap = getScreenShot(rootView);
                File file = store(bitmap, &quot;name.png&quot;);

                if (file.exists()) {
                    shareImage(file);
                    System.out.println(file.getPath());
                } else {
                    Log.e(&quot;file exist&quot;, &quot;NO&quot;);
                }

            }
        });


Functions used in the button


    public static Bitmap getScreenShot(View view) {
        View screenView = view.getRootView();
        screenView.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
        screenView.setDrawingCacheEnabled(false);
        return bitmap;
    }

    public File store(Bitmap bm, String fileName) {
        final String dirPath = Environment.getExternalStorageDirectory().getPath() + &quot;/Screenshots&quot;;
        File dir = new File(dirPath);
        if (!dir.exists())
            dir.mkdirs();
        File file = new File(dirPath, fileName);
        try {
            FileOutputStream fOut = new FileOutputStream(file);
            bm.compress(Bitmap.CompressFormat.PNG, 85, fOut);
            fOut.flush();
            fOut.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return file;
    }

    private void shareImage(File file) {
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.setType(&quot;image/*&quot;);
        shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
        shareIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(Intent.createChooser(shareIntent, &quot;Share Screenshot&quot;));
    }


the problem was solved like this.

  [1]: https://stackoverflow.com/users/8050896/p-fuster

</details>



huangapple
  • 本文由 发表于 2020年9月6日 21:47:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/63764849.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定