鸟语天空
在服务中执行长时间运行的任务
post by:追风剑情 2015-7-27 22:28
package com.example.androidtest;

import java.net.MalformedURLException;
import java.net.URL;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId){
		Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
		try {
			int result = DownLoadFile(new URL("http://www.amazon.com/somefile.pdf"));
			Toast.makeText(getBaseContext(), "Downloaded "+result+" bytes", Toast.LENGTH_LONG).show();
		}catch(MalformedURLException e){
			Log.d("AndroidTest", e.getMessage());
		}
		return START_STICKY;
	}

	@Override
	public void onDestroy(){
		super.onDestroy();
		Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
	}
	
	private int DownLoadFile(URL url)
	{
		try{
			Thread.sleep(5000);//模拟文件下载
		}catch(InterruptedException e){
			Log.d("AndroidTest", e.getMessage());
		}
		return 100;//文件大小
	}
}
评论:
发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容