Android Webview允许使用当前的Android Studio访问相机 [英] Android webview allow access to camera with current Android Studio
问题描述
我一直试图在访问照相机和文件的Web视图上使用一个简单的输入按钮。我读过的解决方案有几行代码,没有说明我去Android Studio中下载并打开的盲目github项目链接(Os-Fileup等)的位置,它们通常有数十个文件,但没有任何内容
I have been trying to make a simple input button work on my webview that accesses the camera and files. The solutions I've read vary from a couple lines of code with no explanation of where they go to blind github project links (Os-Fileup and others) that I download and open in Android Studio and they often have dozens of files with nothing that really helps me as I don't know what I'm looking for.
我尝试了各种解决方案,包括此软件包或该软件包,请求权限等,但是没有已经为我解决了这个问题,因为我可能错误地实现了它们,或者它们适用于许多旧版本的Android或Android Studio。我使用的是最新版本的Android Studio,并且仅针对Oreo 8.1(minSdkVersion 27和targetSdkVersion 28)。
I've tried various solutions of including this package or that, requesting permissions, etc but none have solved the issue for me as I probably implemented them incorrectly or they were for much older versions of Android or Android Studio. I am using the very latest version of Android Studio and am targeting only Oreo 8.1 (minSdkVersion 27 and targetSdkVersion 28).
对于我的webview应用的初始设置,我遵循了我在某个地方找到了一个简单的教程,除了相机以外,其他所有东西都在工作。
For the initial setup of my webview app, I followed a simple tutorial I found somewhere and everything is working - other than the camera.
我终于读到了某个地方,而不是授予该应用程序许可(例如:访问摄像头,访问设备上的应用程序)不会传递到网络视图-因此我被困在那里。只有两个文件-AndroidManifest和MainActivity.java ...因此,这两个文件看起来像您在下面看到的一样-我到底在这些文件中进行了哪些更改,以使按钮在应用程序中可以正常使用
I finally read somewhere than granting permission to the app (eg: access to the camera, to the app on the device) does not carry through to the webview - so that's where I'm stuck. There are only two files - AndroidManifest and MainActivity.java ... so those two files look like what you see below - what in the world do I change in those files to just make the button work in the app that works just fine on the same device in a browser?
webview.loadURL页面中的按钮:
The button from the webview.loadURL page:
<input id='uploadImage' type='file' accept='image/*' name='image' />
AndroidManifest.xml
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="redacted.name.here">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="true" />
<uses-feature android:name="android.hardware.camera.front" android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_ns_n"
android:label="@string/app_name"
android:roundIcon="@drawable/ic_ns_n"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:configChanges="orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.java
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.CookieManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
private WebView webview;
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
onCreate(savedInstanceState);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview =(WebView)findViewById(R.id.webView);
webview.setWebViewClient(new WebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
webview.loadUrl("https://redacted.url.here");
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptThirdPartyCookies(webview,true);
}
}
推荐答案
经过更多搜索之后,我发现了一些新代码,我可以对其进行编辑以使其对我有用,在出现对话框的对话框中询问我是否要使用相机或选择文件。
After additional searching I found some newer code that I was able to edit to make it work for me where I got the dialog box asking if I wanted to use the Camera or pick a file.
编辑软件包名称和URL以匹配您的项目。我在下面的代码中复制了从代码中注释掉的所有部分,但我将在我自己的项目中删除其中的大部分内容。
Edit the package name and the URL to match your project. I left all the section that were commented out in the code I copied from in the code below but I will be removing most of them in my own project.
我希望这样做
我没有对HTML或AndroidManifest.xml文件进行任何更改。
I made no changes to my HTML or the AndroidManifest.xml file.
MainActivity。 java
MainActivity.java
package {put your package name here};
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.webkit.CookieManager;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.io.File;
public class MainActivity extends Activity {
private WebView webview;
private ValueCallback<Uri> mUploadMessage;
private ValueCallback<Uri[]> mUploadMessages;
private Uri mCapturedImageURI = null;
private static final int MY_CAMERA_REQUEST_CODE = 100;
private static final int FILECHOOSER_RESULTCODE = 1;
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview =(WebView)findViewById(R.id.webView);
webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
webview.loadUrl("https://{put your URL here");
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptThirdPartyCookies(webview,true);
webview.setWebViewClient(new WebViewClient());
WebSettings webSettings = webview.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.getSettings().setPluginState(WebSettings.PluginState.ON);
webview.getSettings().setAppCacheEnabled(false);
webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webview.getSettings().setUseWideViewPort(true);
webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setBuiltInZoomControls(false);
webview.getSettings().setSupportZoom(false);
webview.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
webview.getSettings().setDomStorageEnabled(true);
webview.getSettings().setDatabaseEnabled(true);
webview.getSettings().setDatabasePath("/data/data/" + webview.getContext().getPackageName() + "/databases/");
webview.setWebChromeClient(new WebChromeClient() {
// For api level bellow 24
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("http")) {
// Return false means, web view will handle the link
return false;
}
return false;
}
// From api level 24
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
/*Toast.makeText(mcontext, "New Method",Toast.LENGTH_SHORT).show();*/
// Get the tel: url
String url = request.getUrl().toString();
if (url.startsWith("http")) {
// Return false means, web view will handle the link
return false;
}
return false;
}
// openFileChooser for Android 3.0+
/* public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
openImageChooser();
}*/
// For Lollipop 5.0+ Devices
public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
mUploadMessages = filePathCallback;
openImageChooser();
return true;
}
// openFileChooser for Android < 3.0
/* public void openFileChooser(ValueCallback<Uri> uploadMsg) {
openFileChooser(uploadMsg, "");
}
//openFileChooser for other Android versions
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
openFileChooser(uploadMsg, acceptType);
}*/
});
}
private void openImageChooser() {
try {
File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "FolderName");
if (!imageStorageDir.exists()) {
imageStorageDir.mkdirs();
}
File file = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
mCapturedImageURI = Uri.fromFile(file);
final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{captureIntent});
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == this.mUploadMessage && null == this.mUploadMessages) {
return;
}
/* Uri result;
if (requestCode != RESULT_OK){
result = null;
}else {
result = intent == null ? this.mCapturedImageURI : intent.getData();
}
this.mUploadMessage.onReceiveValue(result);
this.mUploadMessage = null;*/
if (null != mUploadMessage) {
handleUploadMessage(requestCode, resultCode, intent);
} else if (mUploadMessages != null) {
handleUploadMessages(requestCode, resultCode, intent);
}
}
}
private void handleUploadMessage(int requestCode, int resultCode, Intent intent) {
Uri result = null;
try {
if (resultCode != RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = intent == null ? mCapturedImageURI : intent.getData();
}
} catch (Exception e) {
e.printStackTrace();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void handleUploadMessages(int requestCode, int resultCode, Intent intent) {
Uri[] results = null;
try {
if (resultCode != RESULT_OK) {
results = null;
} else {
if (intent != null) {
String dataString = intent.getDataString();
ClipData clipData = intent.getClipData();
if (clipData != null) {
results = new Uri[clipData.getItemCount()];
for (int i = 0; i < clipData.getItemCount(); i++) {
ClipData.Item item = clipData.getItemAt(i);
results[i] = item.getUri();
}
}
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
} else {
results = new Uri[]{mCapturedImageURI};
}
}
} catch (Exception e) {
e.printStackTrace();
}
mUploadMessages.onReceiveValue(results);
mUploadMessages = null;
}
}
这篇关于Android Webview允许使用当前的Android Studio访问相机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!