Загрузить несколько изображений в Android WebView

Я новичок в Android. Я создаю приложение с помощью Android Webview. В этом я могу загружать только один файл и не знаю, как выбрать и загрузить несколько изображений в веб-представлении Android. Любезно, помогите выполнить эту задачу.

Вот мой код для mainactivity.java. Я использовал Intent для загрузки изображений.

MainActivity.java

public class MainActivity extends AppCompatActivity{
WebView webView;
private static final String TAG = MainActivity.class.getSimpleName();
private String mCM;
private ValueCallback<Uri> mUM;
private ValueCallback<Uri[]> mUMA;
private final static int FCR = 1;
NotificationManager asw_notification;
Notification asw_notification_new;

private final static int loc_perm = 1;



static boolean ASWP_LOCATION    = true;

private static String ASWV_URL      = "http://example.com/"; //complete URL of your website or webpage
private static String ASWV_F_TYPE   = "*/*";  //to upload any file type using "*/*"; check file type references for more
public static String ASWV_HOST      = aswm_host(ASWV_URL);

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
    super.onActivityResult(requestCode, resultCode, intent);
    if(Build.VERSION.SDK_INT >= 21){
        Uri[] results = null;
        //Check if response is positive
        if(resultCode== Activity.RESULT_OK){
            if(requestCode == FCR){
                if(null == mUMA){
                    return;
                }
                if(intent == null){
                    //Capture Photo if no image available
                    if(mCM != null){
                        results = new Uri[]{Uri.parse(mCM)};
                    }
                }else{
                    String dataString = intent.getDataString();
                    if (dataString != null) {
                        results = new Uri[]{ Uri.parse(dataString) };
                    }
                }
            }
        }
        mUMA.onReceiveValue(results);
        mUMA = null;
    }else{
        if(requestCode == FCR){
            if(null == mUM) return;
            Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
            mUM.onReceiveValue(result);
            mUM = null;
        }
    }
}

@SuppressLint({"SetJavaScriptEnabled", "WrongViewCast"})
@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getSupportActionBar().hide();


    if(Build.VERSION.SDK_INT >=23 && (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
    }

    webView = (WebView) findViewById(R.id.webView1);
    assert webView != null;
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setAllowFileAccess(true);
    webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    webSettings.setGeolocationEnabled(true);
    webSettings.setAppCacheEnabled(true);
    webSettings.setDatabaseEnabled(true);
    webSettings.setDomStorageEnabled(true);


    get_location();

    if(Build.VERSION.SDK_INT >= 21){
        webSettings.setMixedContentMode(0);
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
    }else if(Build.VERSION.SDK_INT >= 19){
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
    }else if(Build.VERSION.SDK_INT < 19){
        webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }
    webView.setWebViewClient(new Callback());
    webView.loadUrl("http://example.com");
    webView.setWebChromeClient(new WebChromeClient(){
        public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
        }
        //For Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg){
            mUM = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            i.setAction(Intent.ACTION_GET_CONTENT);
            MainActivity.this.startActivityForResult(Intent.createChooser(i,"File Chooser"), FCR);
        }
        // For Android 3.0+, above method not supported in some android 3+ versions, in such case we use this
        public void openFileChooser(ValueCallback uploadMsg, String acceptType){
            mUM = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            i.setAction(Intent.ACTION_GET_CONTENT);
            MainActivity.this.startActivityForResult(
                    Intent.createChooser(i, "File Browser"),
                    FCR);
        }
        //For Android 4.1+
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
            mUM = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            i.setAction(Intent.ACTION_GET_CONTENT);
            MainActivity.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), MainActivity.FCR);
        }
        //For Android 5.0+
        public boolean onShowFileChooser(
                WebView webView, ValueCallback<Uri[]> filePathCallback,
                WebChromeClient.FileChooserParams fileChooserParams){
            if(mUMA != null){
                mUMA.onReceiveValue(null);
            }
            mUMA = filePathCallback;
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if(takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null){
                File photoFile = null;
                try{
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCM);
                }catch(IOException ex){
                    Log.e(TAG, "Image file creation failed", ex);
                }
                if(photoFile != null){
                    mCM = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                }else{
                    takePictureIntent = null;
                }
            }
            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("image/*");
            contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            contentSelectionIntent.setAction(Intent.ACTION_GET_CONTENT);
            Intent[] intentArray;
            if(takePictureIntent != null){
                intentArray = new Intent[]{takePictureIntent};
            }else{
                intentArray = new Intent[0];
            }

            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
            startActivityForResult(chooserIntent, FCR);

            return true;
        }
    });
}
public class Callback extends WebViewClient{
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
        Toast.makeText(getApplicationContext(), "Failed loading app!", Toast.LENGTH_SHORT).show();
    }
}
// Create an image file
private File createImageFile() throws IOException{
    @SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "img_"+timeStamp+"_";
    File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    return File.createTempFile(imageFileName,".jpg",storageDir);
}

//Using cookies to update user locations
public void get_location(){
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptCookie(true);
    if(ASWP_LOCATION) {
        //Checking for location permissions
        if (Build.VERSION.SDK_INT >= 23 && !check_permission(1)) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, loc_perm);
            show_notification(2, 2);

        } else {
            GPSTrack gps;
            gps = new GPSTrack(MainActivity.this);
            double latitude = gps.getLatitude();
            double longitude = gps.getLongitude();
            if (gps.canGetLocation()) {
                if (latitude != 0 || longitude != 0) {
                    cookieManager.setCookie(ASWV_URL, "lat=" + latitude);
                    cookieManager.setCookie(ASWV_URL, "long=" + longitude);
                    //Log.w("New Updated Location:", latitude + "," + longitude);  //enable to test dummy latitude and longitude
                } else {
                    Log.w("New Updated Location:", "NULL");
                }
            } else {
                show_notification(1, 1);
                Log.w("New Updated Location:", "FAIL");
            }
        }
    }
}

//Getting host name
public static String aswm_host(String url){
    if (url == null || url.length() == 0) {
        return "";
    }
    int dslash = url.indexOf("//");
    if (dslash == -1) {
        dslash = 0;
    } else {
        dslash += 2;
    }
    int end = url.indexOf('/', dslash);
    end = end >= 0 ? end : url.length();
    int port = url.indexOf(':', dslash);
    end = (port > 0 && port < end) ? port : end;
    Log.w("URL Host: ",url.substring(dslash, end));
    return url.substring(dslash, end);
}

//Creating custom notifications with IDs
public void show_notification(int type, int id) {
    long when = System.currentTimeMillis();
    asw_notification = (NotificationManager) MainActivity.this.getSystemService(Context.NOTIFICATION_SERVICE);
    Intent i = new Intent();
    if (type == 1) {
        i.setClass(MainActivity.this, MainActivity.class);
    } else if (type == 2) {
        i.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    } else {
        i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        i.addCategory(Intent.CATEGORY_DEFAULT);
        i.setData(Uri.parse("package:" + MainActivity.this.getPackageName()));
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
    }
    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

    Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(MainActivity.this);
    switch(type){
        case 1:
            builder.setTicker(getString(R.string.app_name));
            //builder.setContentTitle(getString(R.string.loc_fail));
            //builder.setContentText(getString(R.string.loc_fail_text));
           // builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getString(R.string.loc_fail_more)));
            builder.setVibrate(new long[]{350,350,350,350,350});
            builder.setSmallIcon(R.mipmap.ic_launcher);
            break;

        case 2:
            builder.setTicker(getString(R.string.app_name));
            builder.setContentTitle(getString(R.string.app_name));
            //builder.setContentText(getString(R.string.loc_perm_text));
            //builder.setStyle(new NotificationCompat.BigTextStyle().bigText(getString(R.string.loc_perm_more)));
            builder.setVibrate(new long[]{350, 700, 350, 700, 350});
            builder.setSound(alarmSound);
            builder.setSmallIcon(R.mipmap.ic_launcher);
            break;
    }
    builder.setOngoing(false);
    builder.setAutoCancel(true);
    builder.setContentIntent(pendingIntent);
    builder.setWhen(when);
    builder.setContentIntent(pendingIntent);
    asw_notification_new = builder.getNotification();
    asw_notification.notify(id, asw_notification_new);
}

//Checking if particular permission is given or not
public boolean check_permission(int permission){
    switch(permission){
        case 1:
            return ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;

        case 2:
            return ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;

        case 3:
            return ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;

    }
    return false;
}

@Override
public boolean onKeyDown(int keyCode, @NonNull KeyEvent event){
    if(event.getAction() == KeyEvent.ACTION_DOWN){
        switch(keyCode){
            case KeyEvent.KEYCODE_BACK:
                if(webView.canGoBack()){
                    webView.goBack();
                }else{
                    finish();
                }
                return true;
        }
    }
    return super.onKeyDown(keyCode, event);
}

@Override
public void onConfigurationChanged(Configuration newConfig){
    super.onConfigurationChanged(newConfig);
}

}

0 ответов

Другие вопросы по тегам