【Android開発チュートリアル】サービスでの時間のかかる操作

2115 ワード

この章は『Beginning-Android-4-Application-Development』から翻訳されていますが、翻訳が適切でないところがあれば、ご指摘ください.
原書購入住所http://www.amazon.com/Beginning-Android-4-Application-Development/dp/1118199545/
前節で作成したサービスは実際には何の役にも立たないが、この節では、ダウンロードファイルをシミュレートするタスクを実行するように修正します.
1.前節のサービスエンジニアリングを使用して、少し修正します.
public class MyService extends Service {

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// We want this service to continue running until it is explicitly
		// stopped, so return sticky.
		
		// Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
		
        try {
			int result = DownloadFile(new URL("http://www.abcd.com/file.zip"));
			Toast.makeText(getBaseContext(),
				"Downloaded " + result + " bytes",
				Toast.LENGTH_LONG).show();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }		
	
		return START_STICKY;
	}
	
    private int DownloadFile(URL url) {
        try {
            //---simulate taking some time to download a file---
            Thread.sleep(5000);
        } catch (InterruptedException e) {
             e.printStackTrace();
        }
        //---return an arbitrary number representing 
        // the size of the file downloaded---
        return 100;
    }
        
	@Override
	public void onDestroy() {
		super.onDestroy();
		Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
	}
}


2.シミュレータの上でデバッグします.startボタンをクリックして、ファイルのダウンロードを開始します.
【Android 开发教程】在服务中执行耗时操作