Androidサービスがバックグラウンドダウンロードを実現

功能:点击按钮,启动一个Service下载指定地址的内容,并且将内容保存到Sdcard卡,下载时发送一个进度条通知到通知栏。

ここに写真の説明を書きます

活動クラス:

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;

public class MainActivity extends Activity {
    private String PATH = "http://e.hiphotos.baidu.com/image/pic/item/63d9f2d3572c11dfbdb69872612762d0f703c27f.jpg";//数据地址,这里给了一张图片地址
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.button1).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(MainActivity.this, GetPictures.class);
                intent.putExtra("PATH", PATH);//传递一个参数
                startService(intent);//开启服务
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

サービス継承クラス:

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.widget.Toast;

public class GetPictures extends Service {
    private String PATH = "";
    private Notification.Builder builder;
    private NotificationManager manager;
    private Handler handler = new Handler() {// 消息队列
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                stopSelf();
                Toast.makeText(getApplicationContext(), "下载完成", 1).show();
            }
        }
    };

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

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        builder = new Notification.Builder(getApplicationContext());
        builder.setSmallIcon(R.drawable.ic_launcher).setTicker("下载图片")
                .setContentTitle("图片下载").setContentText("正在下载图片")
                .setAutoCancel(true);// 用户点击浏览一次后,通知消失;
    }

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        PATH = intent.getStringExtra("PATH");// 接受传递过来的参数
        new myTast().start();// 创建一个新的线程并且启动
        return super.onStartCommand(intent, flags, startId);

    }

    public class myTast extends Thread implements Runnable {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            super.run();
            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(PATH);
            HttpResponse httpResponse;
            InputStream inputStream = null;
            ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
            int len = 0;
            int len_data = 0;
            byte[] data = new byte[512];
            try {
                httpResponse = client.execute(get);
                long len_long = httpResponse.getEntity().getContentLength();
                if (httpResponse.getStatusLine().getStatusCode() == 200) {
                    ToSdcard to = new ToSdcard();
                    inputStream = httpResponse.getEntity().getContent();
                    while ((len = inputStream.read(data)) != -1) {
                        arrayOutputStream.write(data, 0, data.length);
                        len_data += len;
                        int progress_value = (int) ((len_data / (float) len_long) * 100);//进度条刻度计算
                        builder.setProgress(100, progress_value, false);
                        manager.notify(1000, builder.build());
                    }
                    boolean flag = to.saver("bb.png",//保存的文件名
                            arrayOutputStream.toByteArray());// 数据保存到本地Sdcard
                    builder.setContentText("下载完成!");
                    manager.notify(1000, builder.build());
                    if (flag) {
                        handler.sendEmptyMessage(1);
                    }
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
布局文件中只有一个按钮,就不贴源码了,记得在清单文件中声明服务以及获取连网权限和Sdcard卡读写权限
<service android:name=".GetPictures"></service>
 <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

http://blog.csdn.net/q296264785/article/details/53155739

元の記事34件を公開 10のような 30,000以上の訪問

おすすめ

転載: blog.csdn.net/q296264785/article/details/53395057