参考上一篇博客:https://blog.csdn.net/cf8833/article/details/93905187
上一篇博客说到,如何在activity中下载文件,今天把程序改一下,在service中下载文件
服务需要注册,源码全部贴出来了,需要源码的给我留言
1.MainActivity启动服务
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button5:
startService(new Intent(getApplicationContext(),DownloadService.class));
break;
}
}
2.下载apk,主要就是把之前的线程,移植到了onCreate里面,注意,服务的启动两种方式startService 和 bindService,不管哪种方式启动,都会执行onCreate方法,我们把线程放到onCreate中即可
package com.example.administrator.testz;
import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.IBinder;
import android.print.PrinterId;
import android.support.annotation.Nullable;
import android.widget.Toast;
import java.io.File;
import cn.finalteam.okhttpfinal.FileDownloadCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
/**
* Created by wrs on 2019/9/17,16:59
* projectName: Testz
* packageName: com.example.administrator.testz
*/
public class DownloadService extends Service {
private DownThread mThread;
final String url = "https://raw.githubusercontent.com/wrs13634194612/Image/master/raw/test.apk";
String apkName = "test.apk";
final String FILE_DIR = "TestApk";
String apkPath = Environment.getExternalStoragePublicDirectory(FILE_DIR) + "/" + apkName;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
mThread = new DownThread();
mThread.start();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
}
class DownThread extends Thread{
@Override
public void run() {
final File saveFile = new File(apkPath);
System.out.println("filepath: "+apkPath);
HttpRequest.download(url, saveFile, new FileDownloadCallback() {
//开始下载
@Override
public void onStart() {
super.onStart();
System.out.println("start");
}
//下载进度
@Override
public void onProgress(int progress, long networkSpeed) {
super.onProgress(progress, networkSpeed);
System.out.println("process:" + progress);
//String speed = FileUtils.generateFileSize(networkSpeed);
}
//下载失败
@Override
public void onFailure() {
super.onFailure();
System.out.println("fail");
Toast.makeText(getBaseContext(), "下载失败", Toast.LENGTH_SHORT).show();
}
//下载完成(下载成功)
@Override
public void onDone() {
super.onDone();
System.out.println("success");
Toast.makeText(getBaseContext(), "下载成功", Toast.LENGTH_SHORT).show();
}
});
}
}
}
end
另外讲解一下service的两种启动方式
package com.example.administrator.testz;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button button,button2,button3,button4,button5;
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.e("MainActivity","onServiceConnected");
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.e("MainActivity","onServiceDisconnected");
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
button2 = (Button)findViewById(R.id.button2);
button3 = (Button)findViewById(R.id.button3);
button4 = (Button)findViewById(R.id.button4);
button5 = (Button)findViewById(R.id.button5);
button.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
button4.setOnClickListener(this);
button5.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button:
startService(new Intent(getApplicationContext(),MyServer.class));
break;
case R.id.button2:
stopService(new Intent(getApplicationContext(),MyServer.class));
break;
case R.id.button3:
Intent intent = new Intent(getApplicationContext(),MyServer.class);
bindService(intent,serviceConnection,BIND_AUTO_CREATE);
break;
case R.id.button4:
unbindService(serviceConnection);
break;
case R.id.button5:
startService(new Intent(getApplicationContext(),DownloadService.class));
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(serviceConnection);
}
}
自己创建的服务:
package com.example.administrator.testz;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
/**
* Created by wrs on 2019/9/17,16:06
* projectName: Testz
* packageName: com.example.administrator.testz
*/
public class MyServer extends Service {
private MyThread mThread;
private int num = 0;
private boolean isRunning = true;
@Nullable
@Override
public IBinder onBind(Intent intent) {
//bingservice 启动服务时 系统调用此方法
Log.e("MyServer","onBind");
return null;
}
@Override
public boolean onUnbind(Intent intent) {
// bingservice断开连接时,调用此方法
Log.e("MyServer","onUnbind");
return super.onUnbind(intent);
}
@Override
public void onRebind(Intent intent) {
//bindservice重新连接时,调用此方法
super.onRebind(intent);
Log.e("MyServer","onRebind");
}
@Override
public void onCreate() {
//不管哪种服务启动方式 都会调用此方法 只调用一次
super.onCreate();
Log.e("MyServer","onCreate");
mThread = new MyThread();
mThread.start();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//startservice启动服务时,系统自动调用此方法
Log.e("MyServer","onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
//服务不在使用,销毁时,调用此方法
super.onDestroy();
isRunning = false;
Log.e("MyServer","onDestroy");
}
class MyThread extends Thread{
@Override
public void run() {
while(isRunning){
try {
Thread.sleep(1000);
num++;
Log.e("MyServer","MyThread: "+num);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
1.当我们使用startService启动执行的方法:onCreate -> onStartCommand -> onDestroy
2.使用bingservice启动执行的方法:onCreate -> onBind -> onUnbind -> onDestroy
注意,bindService启动的服务,必须和activity同时运行,当activity销毁时,必须在ondestroy中销毁service,否则会报错