清单文件
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.bw.alice.servicestartprogress">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<service android:name=".ProgressService"/>
</application>
</manifest>
MainActivity
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
public class MainActivity extends AppCompatActivity {
private ProgressDialog dialog;
private ProgressReceiver receiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 注册广播
register();
// 初始化 Dialog
initDialog();
}
// 注册广播
private void register() {
receiver = new ProgressReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("com.phone.day22.progress");
registerReceiver(receiver, filter);
}
private void initDialog() {
dialog = new ProgressDialog(this);
dialog.setIcon(R.mipmap.ic_launcher);
dialog.setTitle("提示");
dialog.setMessage("图片正在下载中。。。");
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMax(100);
dialog.setIndeterminate(false);
}
public void onClick(View view) {
dialog.show();
// 开启服务
startService(new Intent(this, ProgressService.class));
}
class ProgressReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int progress = intent.getIntExtra("progress", 0);
// 接收下载进度 并更新dialog
dialog.setProgress(progress);
if (progress == 100) {
dialog.dismiss();
}
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
// 注销广播
unregisterReceiver(receiver);
}
}
ProgressService
import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.IBinder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class ProgressService extends Service {
private String path = "http://att2.citysbs.com/suzhou/2011/12/27/09/middle_095806_kuokioik_0afeb16ab6cdd89b4d3b8cf7f0ccda32.jpg";
private String filePath = "";
private String file_name = "xrk.jpg";
private int total_lenth;
private int current;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
super.onCreate();
// 初始化下载地址
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath()
+ File.separator + file_name;
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread() {
public void run() {
HttpURLConnection conn = null;
BufferedInputStream inputStream = null;
BufferedOutputStream outputStream = null;
try {
outputStream = new BufferedOutputStream(new FileOutputStream(filePath));
URL url = new URL(path);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setReadTimeout(5 * 1000);
inputStream = new BufferedInputStream(conn.getInputStream());
// 总长度
total_lenth = conn.getContentLength();
byte[] bytes = new byte[1024];
int line;
Intent intent = new Intent();
// 定义一个广播
intent.setAction("com.phone.day22.progress");
while ((line = inputStream.read(bytes)) != -1) {
current += line;
outputStream.write(bytes, 0, line);
outputStream.flush();
int progress = (int) ((float) current / (float) total_lenth * 100);
intent.putExtra("progress", progress);
// 发送广播
sendBroadcast(intent);
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (conn != null) {
conn.disconnect();
}
}
};
}.start();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
activity_main
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.bw.alice.servicestartprogress.MainActivity">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="18dp"
android:onClick="onClick"
android:text="开始下载" />
</RelativeLayout>