download video file using webview

会有一股神秘感。 提交于 2021-02-11 17:43:31

问题


i am trying to download video file using web view on click button when i click on button it start download but when i check on file manager there is nothing inside it. this is my url http://segoma.com/v.php?type=view&id=U5K8Q4F6DD which i have to download video. so help me to solve this issue. i have also check many ways using webview download but doesn't help me.

i have try following code.

public class TestActivity extends Activity {

    WebView webView;
    String image_url;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_test);

        if (android.os.Build.VERSION.SDK_INT > 14) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        webView = (WebView) findViewById(R.id.webView_certy);

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

            } else {
                ActivityCompat.requestPermissions(this,
                        new String[]{
                                Manifest.permission.WRITE_EXTERNAL_STORAGE
                        }, 23
                );
            }
        }

        final String stone_barcodeno = getIntent().getStringExtra("url");

        if (stone_barcodeno.equals("")) {
            Toast.makeText(this, "No image for this stone", Toast.LENGTH_SHORT).show();
        } else {

            image_url = stone_barcodeno;
            Log.d("1", image_url);
            webView.loadUrl(image_url);
            webView.setPadding(0, 0, 0, 0);
            //webView.setInitialScale(getScale());
            webView.getSettings().setBuiltInZoomControls(true);
            ///=========================
            webView.setInitialScale(1);
            webView.getSettings().setJavaScriptEnabled(true);
            webView.getSettings().setLoadWithOverviewMode(true);
            webView.getSettings().setUseWideViewPort(true);
            webView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
            webView.setScrollbarFadingEnabled(false);

        }

        /* Defining a button click listener for the Download button */
        View.OnClickListener downloadsListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                File direct = new File(Environment.getExternalStorageDirectory() + "/abc");

                if (!direct.exists()) {
                    if (!direct.mkdirs())
                        Log.w("","Failed to create dir!");
                }

                DownloadManager mgr = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                Uri downloadUri = Uri.parse(image_url);
                DownloadManager.Request request = new DownloadManager.Request(
                        downloadUri);
                request.setAllowedNetworkTypes(
                        DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
                        .setAllowedOverRoaming(false).setTitle("abc")
                        .setDescription("Image certi Downloading...")
                        .setDestinationInExternalPublicDir("/abc", stone_barcodeno + "_certi" + ".jpg");
                mgr.enqueue(request);
                Toast.makeText(TestActivity.this, "Image Downloaded Successfully on this Device.", Toast.LENGTH_LONG).show();
            }
        };

        btn_download.setOnClickListener(downloadsListener);
    }
}

Map Demo

Mapfrag.java

public class Mapfrag extends SupportMapFragment implements OnMapReadyCallback {

//    private GoogleMap mMap;
//    ArrayList<LatLng> MarkerPoints;
    GoogleApiClient mGoogleApiClient;
//    Location mLastLocation;
//    Marker mCurrLocationMarker;
//    LocationRequest mLocationRequest;
    private GoogleMap mMap;
    private List<LocationModel> mListMarker = new ArrayList<>();
    private List<ListAddress> addresslist;
    String add []={"surat","bombay","pune","delhi"};
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View root = inflater.inflate(R.layout.fragment_map, null, false);
        initilizeMap();
        return root;
    }
    private void initilizeMap() {
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            checkLocationPermission();
        }


        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        addresslist=new ArrayList<>();

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

       // getAllDataLocationLatLng();
        for (int p=0;p<add.length;p++){
            LatLng ll=getLocationFromAddress(getActivity(),add[p]);
            addresslist.add(new ListAddress(ll.latitude,ll.longitude));
        }
        //Initialize Google Play Services
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(getActivity(),
                    android.Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                //buildGoogleApiClient();
                mMap.setMyLocationEnabled(true);
            }
        }
        else {
           // buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }

        if(addresslist.size()>0){
            initMarker(addresslist);
        }

    }
    public LatLng getLocationFromAddress(Context context, String strAddress) {

        Geocoder coder = new Geocoder(context);
        List<Address> address;
        LatLng p1 = null;

        try {
            // May throw an IOException
            address = coder.getFromLocationName(strAddress, 5);
            if (address == null) {
                return null;
            }

            Address location = address.get(0);
            p1 = new LatLng(location.getLatitude(), location.getLongitude() );

        } catch (IOException ex) {

            ex.printStackTrace();
        }

        return p1;
    }
    private void getAllDataLocationLatLng(){
        final ProgressDialog dialog = new ProgressDialog(getActivity());
        dialog.setMessage("Menampilkan data marker ..");
        dialog.show();

        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        Call<ListLocationModel> call = apiService.getAllLocation();
        call.enqueue(new Callback<ListLocationModel>() {
            @Override
            public void onResponse(Call<ListLocationModel> call, Response<ListLocationModel> response) {
                dialog.dismiss();
                mListMarker = response.body().getmData();
                //initMarker(mListMarker);
            }

            @Override
            public void onFailure(Call<ListLocationModel> call, Throwable t) {
                dialog.dismiss();
                Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

    }

    private void initMarker(List<ListAddress> listData){
        //iterasi semua data dan tampilkan markernya
        for (int i=0; i<listData.size(); i++){
            //set latlng nya
            LatLng location = new LatLng(listData.get(i).getLatutide(),listData.get(i).getLongitude());
            //tambahkan markernya
            mMap.addMarker(new MarkerOptions().position(location).title(add[i]));
            //set latlng index ke 0
            LatLng latLng = new LatLng(listData.get(0).getLatutide(),listData.get(0).getLongitude());
            //lalu arahkan zooming ke marker index ke 0
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latLng.latitude,latLng.longitude), 4));
        }
    }


   /* protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }
    @Override
    public void onConnected(Bundle bundle) {


    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }*/
    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
    public boolean checkLocationPermission(){
        if (ContextCompat.checkSelfPermission(getActivity(),
                android.Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            // Asking user if explanation is needed
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                    android.Manifest.permission.ACCESS_FINE_LOCATION)) {

                // 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.

                //Prompt the user once explanation has been shown
                ActivityCompat.requestPermissions(getActivity(),
                        new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);


            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(getActivity(),
                        new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);
            }
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted. Do the
                    // contacts-related task you need to do.
                    if (ContextCompat.checkSelfPermission(getActivity(),
                            android.Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {

                        if (mGoogleApiClient == null) {
                           // buildGoogleApiClient();
                        }
                        mMap.setMyLocationEnabled(true);
                    }

                } else {

                    // Permission denied, Disable the functionality that depends on this permission.
                    Toast.makeText(getActivity(), "permission denied", Toast.LENGTH_LONG).show();
                }
                return;
            }

            // other 'case' lines to check for other permissions this app might request.
            // You can add here other case statements according to your requirement.
        }
    }
}

回答1:


You download video in the location you set yourself in this line:

.setDestinationInExternalPublicDir("/abc", stone_barcodeno + "_certi" + ".jpg");

if you can't find this directory(abc) set location to a place that are familiar to you such as download folder or use getUriForDownloadedFile to get your downloaded file directory. for more info go to [this page](https://developer.android.com/reference/android/app/DownloadManager.Request.html#setDestinationInExternalFilesDir(android.content.Context, java.lang.String, java.lang.String)).



来源:https://stackoverflow.com/questions/43316378/download-video-file-using-webview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!