关于活动销毁后服务结束的问题

zhuailhw123 2018-07-12 09:29:23
请教个问题: 现在创建一个活动 三个按钮 启动下载 暂停下载 取消下载 ,在MainActivity中通过startService和bindService启动服务,代码:申请权限的省略了
public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
private DownloadService.DownloadBinder downloadBinder;
Intent intent;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
}

@Override
public void onServiceConnected(ComponentName name, IBinder service) {
downloadBinder = (DownloadService.DownloadBinder) service;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startDownload = (Button) findViewById(R.id.start_download);
Button pauseDownload = (Button) findViewById(R.id.pause_download);
Button cancelDownload = (Button) findViewById(R.id.cancel_download);
startDownload.setOnClickListener(this);
pauseDownload.setOnClickListener(this);
cancelDownload.setOnClickListener(this);
intent = new Intent(this, DownloadService.class);
startService(intent); // 启动服务
bindService(intent, connection, BIND_AUTO_CREATE); // 绑定服务
}
@Override
public void onClick(View v) {
if (downloadBinder == null) {
return;
}
switch (v.getId()) {
case R.id.start_download:
String url = "https://raw.githubusercontent.com/guolindev/eclipse/master/eclipse-inst-win64.exe";
downloadBinder.startDownload(url);
break;
case R.id.pause_download:
downloadBinder.pauseDownload();
break;
case R.id.cancel_download:
downloadBinder.cancelDownload();
break;
default:
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
//stopService(intent);
Log.d("MainActivty","执行销毁");
unbindService(connection);
// android.os.Process.killProcess(android.os.Process.myPid());

}
}

下面是服务类的代码:
public class DownloadService extends Service {

private DownloadTask downloadTask;

private String downloadUrl;

private DownloadListener listener = new DownloadListener() {
@Override
public void onProgress(int progress) {
getNotificationManager().notify(1, getNotification("Downloading...", progress));
}

@Override
public void onSuccess() {
downloadTask = null;
// 下载成功时将前台服务通知关闭,并创建一个下载成功的通知
stopForeground(true);
getNotificationManager().notify(1, getNotification("Download Success", -1));
Toast.makeText(DownloadService.this, "Download Success", Toast.LENGTH_SHORT).show();
}

@Override
public void onFailed() {
downloadTask = null;
// 下载失败时将前台服务通知关闭,并创建一个下载失败的通知
stopForeground(true);
getNotificationManager().notify(1, getNotification("Download Failed", -1));
Toast.makeText(DownloadService.this, "Download Failed", Toast.LENGTH_SHORT).show();
}

@Override
public void onPaused() {
downloadTask = null;
Toast.makeText(DownloadService.this, "Paused", Toast.LENGTH_SHORT).show();
}

@Override
public void onCanceled() {
downloadTask = null;
stopForeground(true);
Toast.makeText(DownloadService.this, "Canceled", Toast.LENGTH_SHORT).show();
}

};

private DownloadBinder mBinder = new DownloadBinder();
@Override
public void onDestroy()
{
super.onDestroy();
Log.d("DownloadService","执行销毁");
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}

class DownloadBinder extends Binder {

public void startDownload(String url) {
if (downloadTask == null) {
downloadUrl = url;
downloadTask = new DownloadTask(listener);
downloadTask.execute(downloadUrl);
startForeground(1, getNotification("Downloading...", 0));
Toast.makeText(DownloadService.this, "Downloading...", Toast.LENGTH_SHORT).show();
}
}

public void pauseDownload() {
if (downloadTask != null) {
downloadTask.pauseDownload();
}
}

public void cancelDownload() {
if (downloadTask != null) {
downloadTask.cancelDownload();
} 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) {
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
builder.setContentIntent(pi);
builder.setContentTitle(title);
if (progress >= 0) {
// 当progress大于或等于0时才需显示下载进度
builder.setContentText(progress + "%");
builder.setProgress(100, progress, false);
}
return builder.build();
}

}

服务类中启动了一个DownloadTask 这是继承自AsyncTask
public class DownloadTask extends AsyncTask<String, Integer, Integer> {

private DownloadListener listener;
private boolean isCanceled = false;
private boolean isPaused = false;
private int lastProgress;
public DownloadTask(DownloadListener listener) {
this.listener = listener;
}
@Override
protected Integer doInBackground(String... params) {
//执行具体的下载任务
}

@Override
protected void onProgressUpdate(Integer... values) {
//更新界面
}
}
@Override
protected void onPostExecute(Integer status) {
//一些收尾代码
}


我现在的问题是
1 看到书上说 service不是运行在一个独立的进程,当创建服务的进程被杀掉时,服务也会停止,那么怎么杀死一个进程,通过在MainActivity中调用android.os.Process.killProcess(android.os.Process.myPid()); 可以杀死进程,我通过点击back键退出程序可以杀死进程吗? 通过点击任务键 点×号 可以关闭进程吗?
2 我如果在MainActivity中
@Override
protected void onDestroy() {
[b] super.onDestroy();
stopService(intent);
Log.d("MainActivty","执行销毁");
unbindService(connection);
}
}
同时调用了super.onDestroy();
stopService(intent); 服务业停止了为什么还能进行下载的任务呢?

...全文
207 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
没有鱼了 2018-07-12
  • 打赏
  • 举报
回复
killProcess可以杀死进程,点击任务键 点×号通常也可以杀死应用进程,我遇到某些工业手机不行,看厂家;正常执行完Activity的生命周期是不能杀死进程的,那只是销毁了activity,跟activity所在的进程没关系,去看activity源码;
service是在UI线程,也就是主线程,也就是ActivityThread,你任务是在AsyncTask里做的,是由线程池维护的其它线程去下载;所以这是两个线程,service销毁了,不影响AsyncTask
没有鱼了 2018-07-12
  • 打赏
  • 举报
回复
我们平时使用的手机从任务栏杀掉当前运行的app,意义就是杀掉进程,进程都没了,所以进程里的线程肯定也会销毁;但是你说的模拟器你可以用adb或者去手机设置里面去看下你的应用进程还在不在,如果还在,说明模拟器点击任务键 关闭程序 没有起到杀进程的作用
zhuailhw123 2018-07-12
  • 打赏
  • 举报
回复
引用 1 楼 qq_30993595 的回复:
killProcess可以杀死进程,点击任务键 点×号通常也可以杀死应用进程,我遇到某些工业手机不行,看厂家;正常执行完Activity的生命周期是不能杀死进程的,那只是销毁了activity,跟activity所在的进程没关系,去看activity源码;
service是在UI线程,也就是主线程,也就是ActivityThread,你任务是在AsyncTask里做的,是由线程池维护的其它线程去下载;所以这是两个线程,service销毁了,不影响AsyncTask

谢谢您的回答
我在魅族手机上 试验的时候 按 任务键关闭程序 就把服务 和AsyncTask的线程都关闭了 但是在androi studio的模拟器上 点击任务键 关闭程序 发现这个AsyncTask关闭不了 一直在下载 这是什么原因呢 谢谢

80,351

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧