Android下載檔案(1)

來源:互聯網
上載者:User

標籤:

  • service下載檔案,加入標籤:

<service android:name=".MyService"></service>

添加相關許可權:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

  • 代碼如下:

    public class MainActivity extends Activity {
        private Button button;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.mainactivity);
            button = (Button) findViewById(R.id.button1);
            button.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    Intent intent = new Intent(MainActivity.this,MyService.class);
                    startService(intent);
                }
            });
        }
    }

    public class MyService extends Service {
        private final String DOWNPATH = "http://www.baidu.com/img/bdlogo.png";//下載連結

        @Override
        public void onCreate() {
            // TODO Auto-generated method stub
            super.onCreate();
        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            // TODO Auto-generated method stub
            // 不能直接使用Http協議使用網路,service在UI線程當中,需要建立線程,與主線程分離
            final Handler handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    // TODO Auto-generated method stub
                    super.handleMessage(msg);
                    if (msg.what == 1) {
                        stopSelf();
                        Toast.makeText(getApplicationContext(), "檔案下載完畢", 1).show();
                    }
                }
            };

            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(DOWNPATH);
                    HttpResponse httpResponse = null;
                    // 獲得SD卡的目錄
                    File file = Environment.getExternalStorageDirectory();
                    FileOutputStream outStream = null;
                    try {
                        httpResponse = httpClient.execute(httpPost);
                        if (httpResponse.getStatusLine().getStatusCode() == 200) {
                            byte[] result = EntityUtils.toByteArray(httpResponse
                                    .getEntity());
                            // 判斷SDK卡是否掛載,並且可以儲存資料
                            if (Environment.getExternalStorageState().equals(
                                    Environment.MEDIA_MOUNTED)) {
                                File new_file = new File(file, "bdlogo.png");
                                outStream = new FileOutputStream(new_file);
                                outStream.write(result, 0, result.length);
                                Message message = Message.obtain();
                                message.what = 1;
                                handler.sendMessage(message);
                                // 關閉service

                            }
                        }
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } finally {
                        try {
                            outStream.close();
                            httpClient.getConnectionManager().shutdown();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                    }
                }
            });
            thread.start();
            return super.onStartCommand(intent, flags, startId);
        }

        @Override
        public IBinder onBind(Intent arg0) {
            // TODO Auto-generated method stub
            return null;
        }

    }

Android下載檔案(1)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.