有没有办法让所有类都可以使用以下方法?

时间:2016-01-19 08:46:01

标签: android onclicklistener buttonclick

我在类pdfviewer(...)中编写了一个方法In_cs_3_s1,它基本上将文件路径,文件名和URL作为参数。它首先检查文件是否存在于指定的路径中,如果存在,则调用pdf查看器。否则,它会从指定的URL下载文件:要执行此操作,它会调用DOWNLOAD MANAGER。我想从很多地方调用此method(pdfviewer)

这是我的代码:

public void pdfviewer(String branch,String sem,String folder,String fname,String url,Context a)
{
     File file = new File(Environment.getExternalStorageDirectory()
                +File.separator+"name"+File.separator+branch+File.separator+sem+File.separator+folder,fname);        

        if(file.exists())
        {

             Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.fromFile(file),"application/pdf");
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                try 
                {
                    startActivity(intent);
                } 
                catch (ActivityNotFoundException e) 
                {
                     Toast.makeText( this, "NO pdf viewer found", Toast.LENGTH_SHORT).show();
                }
        }
        else
        {   
                file_download(url,branch,sem,folder,fname);
                Toast.makeText( this, "Downloading.....", Toast.LENGTH_LONG).show();
        }

}


public void file_download(String uRl,String branch,String sem,String folder,String fname) {
    File direct = new File(Environment.getExternalStorageDirectory()
            +File.separator+"name"+File.separator+branch+File.separator
            +sem+File.separator+folder);

    if (!direct.exists()) {
        direct.mkdirs();
    }

    DownloadManager mgr = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);

    Uri downloadUri = Uri.parse(uRl);
    DownloadManager.Request request = new DownloadManager.Request(
            downloadUri);
    request.allowScanningByMediaScanner();
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    request.setAllowedNetworkTypes(
            DownloadManager.Request.NETWORK_WIFI
                    | DownloadManager.Request.NETWORK_MOBILE)
            .setAllowedOverRoaming(false)
            .setDestinationInExternalPublicDir("/name"+File.separator+branch+File.separator
                    +sem+File.separator+folder,fname);

    mgr.enqueue(request);

}

我想从按钮的onclicklistener调用此方法。我是新手所以请放轻松。

1 个答案:

答案 0 :(得分:0)

为对象创建一个全局变量:(在onCreate方法之外)在第一个代码中

In_cs_3_s1 pobj;

问题在于onClick,它无法找到pobj对象;