下载实践
public interface DownloadListener {
void onProgress(int progress);
void onSuccess();
void onFailed();
void onPaused();
void onCanceled();
}
public class DownloadTask extends AsyncTask<String,Integer,Integer> {
public static final int TYPE_SUCCESS = 0;
public static final int TYPE_FAILED = 1;
public static final int TYPE_PAUSED = 2;
public static final int TYPE_CANCELED = 3;
private DownloadListener mDownloadListener;
private boolean isCanceled = false;
private boolean isPaused = false;
private int lastProgress;
public DownloadTask(DownloadListener listener) {
mDownloadListener = listener;
}
@Override
protected Integer doInBackground(String... strings) {
InputStream inputStream = null;
RandomAccessFile randomAccessFile = null;
File file = null;
try {
long downloadedLength = 0;
String downloadUrl = strings[0];
String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/"));
String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
file = new File(directory + fileName);
if (file.exists()) {
downloadedLength = file.length();
}
long contentLength = getContentLength(downloadUrl);
if (contentLength == 0) {
return TYPE_FAILED;
} else if (contentLength == downloadedLength) {
return TYPE_SUCCESS;
}
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.addHeader("RANGE","bytes=" + downloadedLength + "-")
.url(downloadUrl)
.build();
Response response = okHttpClient.newCall(request).execute();
if (response != null) {
inputStream = response.body().byteStream();
randomAccessFile = new RandomAccessFile(file,"rw");
randomAccessFile.seek(downloadedLength);
byte[] bytes = new byte[2014];
int total = 0;
int len;
while ((len = inputStream.read(bytes)) != -1) {
if (isCanceled) {
return TYPE_CANCELED;
} else if (isPaused) {
return TYPE_PAUSED;
} else {
total += len;
randomAccessFile.write(bytes,0,len);
int progress = (int)((total + downloadedLength) * 100 / contentLength);
publishProgress(progress);
}
}
response.body().close();
return TYPE_SUCCESS;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (randomAccessFile != null) {
randomAccessFile.close();
}
if (isCanceled && file != null) {
file.delete();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return TYPE_FAILED;
}
@Override
protected void onProgressUpdate(Integer... values) {
int progress = values[0];
if (progress > lastProgress) {
mDownloadListener.onProgress(progress);
lastProgress = progress;
}
}
@Override
protected void onPostExecute(Integer integer) {
switch (integer) {
case TYPE_SUCCESS:
mDownloadListener.onSuccess();
break;
case TYPE_FAILED:
mDownloadListener.onFailed();
break;
case TYPE_PAUSED:
mDownloadListener.onPaused();
break;
case TYPE_CANCELED:
mDownloadListener.onCanceled();
break;
default:
break;
}
}
public void pauseDownload() {
isPaused = true;
}
public void canceledDownload() {
isCanceled = true;
}
private long getContentLength(String downloadUrl) throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(downloadUrl)
.build();
Response response = client.newCall(request).execute();
if (response != null && response.isSuccessful()) {
long contentLength = response.body().contentLength();
response.body().close();
return contentLength;
}
return 0;
}
}
public class DownloadService extends Service {
private DownloadTask mDownloadTask;
private String downloadUrl;
private DownloadListener mDownloadListener = new DownloadListener() {
@Override
public void onProgress(int progress) {
getNotificationManager().notify(1,getNotification("Downloading...",progress));
}
@Override
public void onSuccess() {
mDownloadTask = null;
stopForeground(true);
getNotificationManager().notify(1,getNotification("Download Success",-1));
Toast.makeText(DownloadService.this,"Download Success",Toast.LENGTH_SHORT).show();
}
@Override
public void onFailed() {
mDownloadTask = null;
stopForeground(true);
getNotificationManager().notify(1,getNotification("Download Failed",-1));
Toast.makeText(DownloadService.this,"Download Failed",Toast.LENGTH_SHORT).show();
}
@Override
public void onPaused() {
mDownloadTask = null;
Toast.makeText(DownloadService.this,"Download Failed",Toast.LENGTH_SHORT).show();
}
@Override
public void onCanceled() {
mDownloadTask = null;
stopForeground(true);
Toast.makeText(DownloadService.this,"Canceled",Toast.LENGTH_SHORT).show();
}
};
private DownloadBinder mDownloadBinder = new DownloadBinder();
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mDownloadBinder;
}
class DownloadBinder extends Binder {
@RequiresApi(api = Build.VERSION_CODES.Q)
public void startDownload(String url) {
if (mDownloadTask == null) {
downloadUrl = url;
mDownloadTask = new DownloadTask(mDownloadListener);
mDownloadTask.execute(downloadUrl);
startForeground(1,getNotification("Downloading...",0));
Toast.makeText(DownloadService.this,"Downlading...",Toast.LENGTH_SHORT).show();
}
}
public void pauseDownload() {
if (mDownloadTask != null) {
mDownloadTask.pauseDownload();
}
}
public void cancelDownload() {
if (mDownloadTask != null) {
mDownloadTask.canceledDownload();
} else {
if (downloadUrl != null) {
String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/"));
String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
File file = new File(directory + fileName);
if (file.exists()) {
file.delete();
}
getNotificationManager().cancel(1);
stopForeground(true);
Toast.makeText(DownloadService.this,"Canceled",Toast.LENGTH_SHORT).show();
}
}
}
}
private NotificationManager getNotificationManager() {
return (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
}
private Notification getNotification(String title, int progress) {
String ID = "com.example.servicebestpractice";
String NAME = "Channel One";
Intent intent = new Intent(this,MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,0);
NotificationCompat.Builder notification = new NotificationCompat.Builder(this);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(ID, NAME, manager.IMPORTANCE_HIGH);
channel.enableLights(true);
channel.setShowBadge(true);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
manager.createNotificationChannel(channel);
notification.setChannelId(ID);
}
notification.setContentTitle(title)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setContentIntent(pendingIntent);
if (progress >= 0) {
notification.setContentText(progress + "%");
notification.setProgress(100,progress,false);
}
return notification.build();
}
}
<Button
android:id="@+id/start_download"
android:layout_width="198dp"
android:layout_height="62dp"
android:layout_marginTop="68dp"
android:text="@string/start_download"
android:onClick="startDownload"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/pause_download"
android:layout_width="198dp"
android:layout_height="62dp"
android:layout_marginTop="16dp"
android:text="@string/pause_download"
android:onClick="pauseDownload"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/start_download" />
<Button
android:id="@+id/stop_download"
android:layout_width="198dp"
android:layout_height="62dp"
android:layout_marginTop="16dp"
android:text="@string/stop_download"
android:onClick="cancelDownload"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/pause_download" />
public class MainActivity extends AppCompatActivity {
private DownloadService.DownloadBinder mDownloadBinder;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mDownloadBinder = (DownloadService.DownloadBinder)service;
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this,DownloadService.class);
startService(intent);
bindService(intent,mConnection,BIND_AUTO_CREATE);
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
}
}
@RequiresApi(api = Build.VERSION_CODES.Q)
public void startDownload(View view) {
if (mDownloadBinder == null){
return;
}
String url = "https://raw.githubusercontent.com/guolindev/eclipse/master/eclipse-inst-win64.exe";
mDownloadBinder.startDownload(url);
}
public void pauseDownload(View view) {
mDownloadBinder.pauseDownload();
}
public void cancelDownload(View view) {
mDownloadBinder.cancelDownload();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this,"拒绝权限将无法使用程序",Toast.LENGTH_SHORT).show();
finish();
}
break;
default:
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(mConnection);
}
}
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<service
android:name=".DownloadService"
android:enabled="true"
android:exported="true"></service>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>