編輯:Android開發實例
- public class AndroidTest extends Activity {
- private static final String TAG = "AndroidTest";
- private ProgressBar progressBar = null;
- private Button startButton = null;
- private EditText filenameText = null;
- private MyHandler handler = null;
- private Message message = null;
- private boolean flag = true;
- private int size = 1;
- private int hasRead = 0;
- private int len = 0;
- private byte buffer[] = new byte[1024*4];
- private int index = 0;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- progressBar = (ProgressBar)findViewById(R.id.progress_horizontal);
- startButton = (Button)findViewById(R.id.mybutton);
- startButton.setOnClickListener(new ButtonClick());
- filenameText = (EditText)findViewById(R.id.fileNameID);
- handler = new MyHandler();
- }
- public boolean downloadFile(final String urlStr, final String filename) {
- new Thread(new Runnable(){
- public void run() {
- try {
- URL url = new URL(urlStr);
- HttpURLConnection connection = (HttpURLConnection)url.openConnection();
- size = connection.getContentLength();
- InputStream inputStream = connection.getInputStream();
- OutputStream outputStream = new FileOutputStream(Environment.getExternalStorageDirectory()+"/"+filename);
- while((len=inputStream.read(buffer))!=-1){
- outputStream.write(buffer);
- hasRead+=len;
- index = (int)(hasRead*100)/size;
- message = new Message();
- message.what = 1;
- handler.sendMessage(message);
- Log.d(TAG, "index = " + index);
- System.out.println("has = "+hasRead+" size = "+size+" index = "+index);
- }
- inputStream.close();
- outputStream.close();
- } catch (Exception e) {
- flag = false;
- e.printStackTrace();
- }
- }
- }).start();
- return flag;
- }
- class ButtonClick implements OnClickListener {
- public void onClick(View v) {
- String url = filenameText.getText().toString();
- String filename = url.substring(url.lastIndexOf('/') + 1);
- Log.d(TAG, "url = " + url);
- Log.d(TAG, "filename = " + filename);
- if(!downloadFile(url, filename)) {
- String rs = "下載失敗 ";
- Toast.makeText(AndroidTest.this, rs, Toast.LENGTH_SHORT).show();
- }
- }
- }
- class MyHandler extends Handler{
- @Override
- public void handleMessage(Message msg) {
- if (msg.what == 1) {
- progressBar.setProgress(index);
- Log.d(TAG, "setProgress index:" + index);
- if (index >= 99) {
- String rs = "下載完成";
- Toast.makeText(AndroidTest.this, rs, Toast.LENGTH_SHORT).show();
- }
- }
- super.handleMessage(msg);
- }
- }
- }
例如,屏幕的上方或下方。要實現這種效果。就需要獲得對話框的Window對象,獲得這個Window對象有多種方法。最容易的就是直接通過AlertDialog類的ge
HelloWorld的目錄結構有: src:存放應用程序的邏輯代碼,這裡面的代碼是人工寫的gen:存放資源代碼,這裡面的代碼是自動生成的assets:存放mp
shimmer開源庫介紹 Shimmer是Fa
Android應用程序可以在許多不同地區的許多設備上運行。為了使應用程序更具交互性,應用程序應該處理以適合應用程序將要使用的語言環境方面的文字,數字,文件等。在本章中,我