Android - 简化我的代码:链接到一个方法的多个按钮

时间:2012-05-03 10:05:48

标签: java android pdf download simplify

正如标题所说,我正在尝试帮助简化我的代码。我有多个按钮,现在我只测试了三个,但我计划有大约三十个按钮选择。目前我有很长的代码部分,我认为可以使用数组大幅缩短?但我不确定如何正确实现它。如果有人以前做过这个或有想法请分享!谢谢大家!

public class myDL extends Activity { 

public static final int DIALOG_DOWNLOAD_PROGRESS = 0; 
private Button startBtn; 
private ProgressDialog mProgressDialog; 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.filechoice); 
mProgressDialog = new ProgressDialog(myDL.this); 
mProgressDialog.setMessage("The file is now downloading, it will be saved on the SD card for future use.  Please use WiFi to avoid operator charges."); 
mProgressDialog.setIndeterminate(false); 
mProgressDialog.setMax(100); 
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 

Button section = (Button) findViewById(R.id.section); 
section.setOnClickListener(new View.OnClickListener() { 

    public void onClick(View view) { 
        // TODO Auto-generated method stub 
        Intent section = new Intent(view.getContext(), 
                section.class); 
        startActivity(section); 

    } 
}); 

Button back = (Button) findViewById(R.id.back); 
back.setOnClickListener(new View.OnClickListener() { 

    public void onClick(View v) { 
        // TODO Auto-generated method stub 
        setResult(RESULT_OK); 
        finish(); 
    } 
}); 

secOne = (Button) findViewById(R.id.secOne); 
secOne.setOnClickListener(new OnClickListener() { 
    public void onClick(View v) { 
        startSecOne(); 
    } 

}); 
} 

private void startSecOne() { 
StartSecOne secOne = new StartSecOne(); 
secOne 
        .execute("www.website.com/document.pdf"); 

} 

class StartSecOne extends AsyncTask<String, Integer, String> { 

@Override 
protected void onPreExecute() { 
    super.onPreExecute(); 
    mProgressDialog.show(); 
} 

@Override 
protected void onProgressUpdate(Integer... progress) { 
    super.onProgressUpdate(progress); 
    mProgressDialog.setProgress(progress[0]); 
} 

@Override 
protected String doInBackground(String... aurl) { 

    String isFileThere = Environment.getExternalStorageDirectory() 
            + "/Android/Data/" 
            + getApplicationContext().getPackageName() 
            + "/files/test1.pdf"; 
    File f = new File(isFileThere); 

    if (f.exists()) { 
        showPdf(); 
    } else { 

        try { 

            URL url = new URL(aurl[0]); 
            URLConnection connection = url.openConnection(); 

            connection.connect(); 
            int fileLength = connection.getContentLength(); 
            int tickSize = 2 * fileLength / 100; 
            int nextProgress = tickSize; 

            Log.d( 

            "ANDRO_ASYNC", "Lenght of file: " + fileLength); 

            InputStream input = new BufferedInputStream( 
                    url.openStream()); 

            String path = Environment.getExternalStorageDirectory() 
                    + "/Android/Data/" 
                    + getApplicationContext().getPackageName() 
                    + "/files"; 
            File file = new File(path); 
            file.mkdirs(); 
            File outputFile = new File(file, "test1.pdf"); 

            OutputStream output = new FileOutputStream(outputFile); 

            byte data[] = new byte[1024 * 1024]; 
            long total = 0; 
            int count; 
            while ((count = input.read(data)) != -1) { 
                total += count; 
                if (total >= nextProgress) { 
                    nextProgress = (int) ((total / tickSize + 1) * tickSize); 
                    this.publishProgress((int) (total * 100 / fileLength)); 
                } 
                output.write(data, 0, count); 
            } 

            output.flush(); 
            output.close(); 
            input.close(); 
            mProgressDialog.dismiss(); 
            showPdf(); 

        } catch (Exception e) { 
        } 
    } 
    return null; 
} 
}
secTwo = (Button) findViewById(R.id.secTwo); 
secTwo.setOnClickListener(new OnClickListener() { 
    public void onClick(View v) { 
        startSecTwo (); 
    } 

}); 
} 

private void startSecTwo () { 
StartSecTwo secTwo = new StartSecTwo (); 
secTwo 
        .execute("www.website.com/document2.pdf"); 

} 

class StartSecTwo extends AsyncTask<String, Integer, String> { 

@Override 
protected void onPreExecute() { 
    super.onPreExecute(); 
    mProgressDialog.show(); 
} 

@Override 
protected void onProgressUpdate(Integer... progress) { 
    super.onProgressUpdate(progress); 
    mProgressDialog.setProgress(progress[0]); 
} 

@Override 
protected String doInBackground(String... aurl) { 

    String isFileThere = Environment.getExternalStorageDirectory() 
            + "/Android/Data/" 
            + getApplicationContext().getPackageName() 
            + "/files/test2.pdf"; 
    File f = new File(isFileThere); 

    if (f.exists()) { 
        showPdf(); 
    } else { 

        try { 

            URL url = new URL(aurl[0]); 
            URLConnection connection = url.openConnection(); 

            connection.connect(); 
            int fileLength = connection.getContentLength(); 
            int tickSize = 2 * fileLength / 100; 
            int nextProgress = tickSize; 

            Log.d( 

            "ANDRO_ASYNC", "Lenght of file: " + fileLength); 

            InputStream input = new BufferedInputStream( 
                    url.openStream()); 

            String path = Environment.getExternalStorageDirectory() 
                    + "/Android/Data/" 
                    + getApplicationContext().getPackageName() 
                    + "/files"; 
            File file = new File(path); 
            file.mkdirs(); 
            File outputFile = new File(file, "test2.pdf"); 

            OutputStream output = new FileOutputStream(outputFile); 

            byte data[] = new byte[1024 * 1024]; 
            long total = 0; 
            int count; 
            while ((count = input.read(data)) != -1) { 
                total += count; 
                if (total >= nextProgress) { 
                    nextProgress = (int) ((total / tickSize + 1) * tickSize); 
                    this.publishProgress((int) (total * 100 / fileLength)); 
                } 
                output.write(data, 0, count); 
            } 

            output.flush(); 
            output.close(); 
            input.close(); 
            mProgressDialog.dismiss(); 
            showPdf(); 

        } catch (Exception e) { 
        } 
    } 
    return null; 
} 
}

secThree = (Button) findViewById(R.id.secThree); 
secThree.setOnClickListener(new OnClickListener() { 
    public void onClick(View v) { 
        startSecThree (); 
    } 

}); 
} 

private void startSecThree () { 
StartSecThree secThree = new StartSecThree (); 
secThree 
        .execute("www.website.com/document3.pdf"); 

} 

class StartSecThree extends AsyncTask<String, Integer, String> { 

@Override 
protected void onPreExecute() { 
    super.onPreExecute(); 
    mProgressDialog.show(); 
} 

@Override 
protected void onProgressUpdate(Integer... progress) { 
    super.onProgressUpdate(progress); 
    mProgressDialog.setProgress(progress[0]); 
} 

@Override 
protected String doInBackground(String... aurl) { 

    String isFileThere = Environment.getExternalStorageDirectory() 
            + "/Android/Data/" 
            + getApplicationContext().getPackageName() 
            + "/files/test3.pdf"; 
    File f = new File(isFileThere); 

    if (f.exists()) { 
        showPdf(); 
    } else { 

        try { 

            URL url = new URL(aurl[0]); 
            URLConnection connection = url.openConnection(); 

            connection.connect(); 
            int fileLength = connection.getContentLength(); 
            int tickSize = 2 * fileLength / 100; 
            int nextProgress = tickSize; 

            Log.d( 

            "ANDRO_ASYNC", "Lenght of file: " + fileLength); 

            InputStream input = new BufferedInputStream( 
                    url.openStream()); 

            String path = Environment.getExternalStorageDirectory() 
                    + "/Android/Data/" 
                    + getApplicationContext().getPackageName() 
                    + "/files"; 
            File file = new File(path); 
            file.mkdirs(); 
            File outputFile = new File(file, "test3.pdf"); 

            OutputStream output = new FileOutputStream(outputFile); 

            byte data[] = new byte[1024 * 1024]; 
            long total = 0; 
            int count; 
            while ((count = input.read(data)) != -1) { 
                total += count; 
                if (total >= nextProgress) { 
                    nextProgress = (int) ((total / tickSize + 1) * tickSize); 
                    this.publishProgress((int) (total * 100 / fileLength)); 
                } 
                output.write(data, 0, count); 
            } 

            output.flush(); 
            output.close(); 
            input.close(); 
            mProgressDialog.dismiss(); 
            showPdf(); 

        } catch (Exception e) { 
        } 
    } 
    return null; 
} 
}



private void showPdf() { 
    // TODO Auto-generated method stub 
    mProgressDialog.dismiss(); 
    File file = new File(Environment.getExternalStorageDirectory() 
            + "/Android/Data/" 
            + getApplicationContext().getPackageName() 
            + "/files/test1.pdf"); 
    PackageManager packageManager = getPackageManager(); 
    Intent testIntent = new Intent(Intent.ACTION_VIEW); 
    testIntent.setType("application/pdf"); 
    List list = packageManager.queryIntentActivities(testIntent, 
            PackageManager.MATCH_DEFAULT_ONLY); 
    Intent intent = new Intent(); 
    intent.setAction(Intent.ACTION_VIEW); 
    Uri uri = Uri.fromFile(file); 
    intent.setDataAndType(uri, "application/pdf"); 
    startActivity(intent); 
} 


} 

1 个答案:

答案 0 :(得分:3)

final OnClickLisener listener = new OnClickListener() {
     public void onClick(View v){
         switch(v.getId()){ 
         case R.id.zero:
            break;
         case R.id.one:
            break;
         case R.id.two:
            break;
         }
     }
}
final int[] btnIds = new int[]{R.id.one, R.id.two, R.id.zero};
for(int i = 0; i < btnIds.length; i++) {
    final Button btn = (Button)findViewById(btnIds[i]);
    btn.setOnClickListener(listener);
}