MainActivity
public class MainActivity extends AppCompatActivity {
public static final String FILE_URL = "https://www.baidu.com/img/bd_logo1.png";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// 下载文件
public void downloadFile(View view) {
Intent intent = new Intent(this, DownloadService.class);
intent.putExtra("file_url", FILE_URL);
startService(intent);
}
}
public class MainActivity extends AppCompatActivity {
public static final String FILE_URL = “https://www.baidu.com/img/bd_logo1.png“;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// 下载文件
public void downloadFile(View view) {
Intent intent = new Intent(this, DownloadService.class);
intent.putExtra(“file_url”, FILE_URL);
startService(intent);
}
}
service
public class DownloadService extends Service implements Callback {
private String fileUrl;
// 文件下载管理者
private DownloadManager downloadManager;
public DownloadService() {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
// 初始化下载管理者
downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
fileUrl = intent.getStringExtra("file_url");
// 使用OkHttp下载文件
// downloadFile(fileUrl);
// 使用下载管理者下载文件
downloadFileByDownloadManager();
}
return super.onStartCommand(intent, flags, startId);
}
// 通过文件下载管理者下载文件
private void downloadFileByDownloadManager() {
// 下载请求对象
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(fileUrl));
// 指定下载路径
String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
// 设置下载并展示通知
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
// 将请求对象加入下载队列,开始下载
downloadManager.enqueue(request);
}
// 使用OkHttp下载数据并保存在本地
private void downloadFile(String fileUrl) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(fileUrl)
.build();
client.newCall(request)
.enqueue(this);
}
@Override
public void onFailure(Call call, IOException e) {
Log.d("1622", "okHttp faiure");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();
Log.d("1622", "successful body" + body.contentLength());
byte[] datas = body.bytes();
saveFile(datas);
}
// 将数据写入本地文件
private void saveFile(byte[] datas) {
String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(datas);
fos.flush();
Log.d("1622", "download successful");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
receiver
public class DownloadReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "下载成功", Toast.LENGTH_SHORT).show();
}
}
MyApplication
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
registerDownloadReceiver();
}
// 注册监听下载完成的广播接收器
private void registerDownloadReceiver() {
DownloadReceiver receiver = new DownloadReceiver();
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(receiver, filter);
}
}
布局
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="下载文件"
android:onClick="downloadFile"/>
清单文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.mobiletrain.android23_startservicedownloadfiledemo">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:name=".application.MyApplication"
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=".service.DownloadService"
android:enabled="true"
android:exported="true"></service>
</application>