停止Android服务
我在停止Android服务,android,android-asynctask,android-service,Android,Android Asynctask,Android Service,我在service中使用AsyncTask编写了一个从web下载图像的程序。下载过程正常。我使用通知指示下载进度,我还有两个按钮用于开始下载和停止下载但当我单击停止按钮时,正在进行的下载无法停止。通知管理器将继续执行相同的操作 主要活动: public class ServicedownloadActivity extends Activity implements OnClickListener { @Override public void onCreate(
service
中使用AsyncTask
编写了一个从web下载图像的程序。下载过程正常。我使用通知
指示下载进度,我还有两个按钮用于开始下载和停止下载但当我单击停止按钮时,正在进行的下载无法停止。通知管理器将继续执行相同的操作 主要活动:
public class ServicedownloadActivity extends Activity implements
OnClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1 = (Button) findViewById(R.id.button1);
b2 = (Button) findViewById(R.id.button2);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.button1) {
Intent intent = new Intent(ServicedownloadActivity.this,
Myclass.class);
startService(intent);
}
if (v.getId() == R.id.button2) {
Intent intent = new Intent(ServicedownloadActivity.this,
Myclass.class);
stopService(intent);
}
}
}
类包含serivce和asynchTask
public class Myclass extends Service {
URLConnection connection;
private final Random mGenerator = new Random();
@Override
public IBinder onBind(Intent intent) {
return null;
}
public int getRandomNumber() {
return mGenerator.nextInt(100);
}
@Override
public void onCreate() {
super.onCreate();
Log.d("df", "From oncreate");
Toast.makeText(this, "on create", Toast.LENGTH_SHORT).show();
}
class DownloadWebPageTask extends AsyncTask<String, String, String> {
String responseTextt;
NotificationManager notificationManager;
Notification notification;
CharSequence contentText;
Context context;
CharSequence contentTitle;
PendingIntent contentIntent;
int HELLO_ID = 1;
long time;
int icon;
CharSequence tickerText;
public void downloadNotification() {
String ns = Context.NOTIFICATION_SERVICE;
notificationManager = (NotificationManager) getSystemService(ns);
icon = R.drawable.ic_launcher;
tickerText = "Downloading...";
time = System.currentTimeMillis();
notification = new Notification(icon, tickerText, time);
context = getApplicationContext();
contentTitle = "Your download is in progress";
contentText = "0% complete";
Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
notificationIntent.setType("audio/*");
contentIntent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle,
contentText, contentIntent);
notificationManager.notify(HELLO_ID, notification);
}
@Override
protected String doInBackground(String... urls) {
try {
Log.d("trys:", "try");
URL url = new URL(
"http://www.zapiture.com/resources/IMG_6812.JPG");
connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
InputStream input = new BufferedInputStream(url
.openStream());
OutputStream output = new FileOutputStream(Environment
.getExternalStorageDirectory()
+ "/img23.jpg");
byte data[] = new byte[1024];
long total = 0;
int count;
int previousProgress = 0;
while ((count = input.read(data)) != -1) {
total += count;
if ((int) (total * 100 / fileLength) > previousProgress) {
previousProgress = (int) (total * 100 / fileLength);
publishProgress(""
+ (int) (total * 100 / fileLength));
output.write(data, 0, count);
}
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPreExecute() {
downloadNotification();
super.onPreExecute();
;
}
@Override
public void onProgressUpdate(String... progress) {
contentText = Integer.parseInt(progress[0]) + "% complete";
notification.setLatestEventInfo(context, contentTitle,
contentText, contentIntent);
notificationManager.notify(HELLO_ID, notification);
super.onProgressUpdate(progress);
}
}
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Log.d("sf", "On Start");
Toast.makeText(this, "on start", Toast.LENGTH_SHORT).show();
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute();
}
@Override
public void onDestroy() {
stopSelf();
super.onDestroy();
Log.d("df", "From on Destroy");
Toast.makeText(this, "on destroy", Toast.LENGTH_SHORT).show();
}
}
公共类Myclass扩展服务{
URL连接;
私有最终随机生成器=新随机();
@凌驾
公共IBinder onBind(意向){
返回null;
}
public int getRandomNumber(){
返回MGGenerator.nextInt(100);
}
@凌驾
public void onCreate(){
super.onCreate();
Log.d(“df”,“来自oncreate”);
Toast.makeText(这个“on create”,Toast.LENGTH_SHORT).show();
}
类下载WebPagetTask扩展异步任务{
字符串响应extt;
通知经理通知经理;
通知;
字符序列内容文本;
语境;
字符序列内容标题;
悬而未决的意图;
int HELLO_ID=1;
长时间;
int图标;
字符序列tickerText;
公共无效下载通知(){
字符串ns=Context.NOTIFICATION\u服务;
notificationManager=(notificationManager)getSystemService(ns);
icon=R.drawable.ic_启动器;
tickerText=“正在下载…”;
时间=System.currentTimeMillis();
通知=新通知(图标、tickerText、时间);
context=getApplicationContext();
contentTitle=“您的下载正在进行”;
contentText=“0%完成”;
Intent notificationIntent=新意图(Intent.ACTION\u视图);
notificationIntent.setType(“音频/*”);
contentIntent=PendingEvent.getActivity(上下文,0,
通知意图,0);
通知。SetLateStevenInfo(上下文、内容标题、,
contentText,contentIntent);
notificationManager.notify(HELLO_ID,notification);
}
@凌驾
受保护的字符串doInBackground(字符串…URL){
试一试{
Log.d(“trys:,“try”);
URL=新URL(
"http://www.zapiture.com/resources/IMG_6812.JPG");
connection=url.openConnection();
connection.connect();
int fileLength=connection.getContentLength();
InputStream输入=新的BufferedInputStream(url
.openStream());
OutputStream输出=新文件OutputStream(环境
.getExternalStorageDirectory()
+“/img23.jpg”);
字节数据[]=新字节[1024];
长总计=0;
整数计数;
int-previousProgress=0;
而((计数=输入。读取(数据))!=-1){
总数+=计数;
如果((int)(总计*100/文件长度)>以前的进度){
previousProgress=(int)(总计*100/文件长度);
出版进度(“”
+(int)(总计*100/文件长度);
输出.写入(数据,0,计数);
}
}
output.flush();
output.close();
input.close();
}捕获(例外e){
e、 printStackTrace();
}
返回null;
}
@凌驾
受保护的void onPreExecute(){
下载通知();
super.onPreExecute();
;
}
@凌驾
public void onProgressUpdate(字符串…进度){
contentText=Integer.parseInt(进度[0])+%complete;
通知。SetLateStevenInfo(上下文、内容标题、,
contentText,contentIntent);
notificationManager.notify(HELLO_ID,notification);
super.onProgressUpdate(进度);
}
}
@凌驾
公共无效启动(Intent Intent,int startId){
//TODO自动生成的方法存根
super.onStart(intent,startId);
日志d(“sf”,“启动时”);
Toast.makeText(这是“开始时”,Toast.LENGTH_SHORT).show();
DownloadWebPagetTask=新建DownloadWebPagetTask();
task.execute();
}
@凌驾
公共空间{
stopSelf();
super.ondestory();
日志d(“df”,“从销毁开始”);
Toast.makeText(这个“on destroy”,Toast.LENGTH_SHORT).show();
}
}
当您使用AsyncTask
下载时,您可以尝试通过以下方式取消AsyncTask本身:
当您使用
AsyncTask
下载时,您可以尝试通过以下方式取消AsyncTask本身:
始终记住,即使调用stopService,异步任务在处理过程中也不会停止。除非在服务的onDestroy实现中调用任务的cancel方法,否则它只会在完成后结束 所以在代码中进行以下修改 你基本上需要添加这个
@Override
public void onDestroy() {
task.canel();
super.onDestroy();
}
另外,您正在创建downloadwebagetask task=new downloadwebagetask()开始时代码>内部,因此您无法在onDestroy中调用task.cancel。而是定义下载WebPagetTask任务代码>
外部sotask.cancel
将在onDestroy
中有效。请记住,即使调用stopService,异步任务也不会在处理过程中停止。除非在服务的onDestroy实现中调用task的cancel方法,否则只有在完成后才会结束
@Override
public void onDestroy() {
task.canel();
super.onDestroy();
}