使用 webview 下载视频文件 [英] download video file using webview

查看:68
本文介绍了使用 webview 下载视频文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用单击按钮上的网络视图下载视频文件,当我单击按钮时,它开始下载,但是当我检查文件管理器时,里面没有任何内容.这是我的 url http://segoma.com/v.php?type=view&id=U5K8Q4F6DD 我必须下载视频.所以帮我解决这个问题.我也使用 webview 下载检查了很多方法,但对我没有帮助.

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.

我尝试了以下代码.

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);
    }
}

地图演示

Mapfrag.java

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

推荐答案

您在此行中设置的位置下载视频:

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

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

如果找不到此目录(abc),请将位置设置为您熟悉的位置,例如下载文件夹或使用getUriForDownloadedFile 获取下载的文件目录.有关更多信息,请访问 [此页面](https://developer.android.com/reference/android/app/DownloadManager.Request.html#setDestinationInExternalFilesDir(android.content.Context, java.lang.String, java.lang.String)).

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

这篇关于使用 webview 下载视频文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆