使用webview下载视频文件

时间:2017-04-10 06:37:46

标签: android webview android-download-manager

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

我试过以下代码。

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

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 个答案:

答案 0 :(得分:0)

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

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