在服务中执行长时间运行的任务

作者:追风剑情 发布于:2015-7-27 22:28 分类:Android

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;//文件大小
	}
}

标签: Android

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号