活动
package com.example.androidtest; import java.net.MalformedURLException; import java.net.URL; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; public class ServicesActivity2 extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_services); } public void startService(View view){ Intent intent = new Intent(getBaseContext(), MyService2.class); try { URL[] urls = new URL[] { new URL("http://www.amazon.com/somefile.pdf"), new URL("http://www.wrox.com/somefile.pdf"), new URL("http://www.google.com/somefile.pdf"), new URL("http://www.learn.com/somefile.pdf") }; intent.putExtra("URLs", urls); }catch(MalformedURLException e){ Log.d("AndroidTest", e.getMessage()); } startService(intent); } public void stopService(View view){ stopService(new Intent(getBaseContext(), MyService2.class)); } }
服务
package com.example.androidtest; import java.net.URL; import android.app.Service; import android.content.Intent; import android.os.AsyncTask; import android.os.IBinder; import android.util.Log; import android.widget.Toast; public class MyService2 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(); //解析活动传过来的数据。 Object[] objUrls = (Object[]) intent.getExtras().get("URLs"); URL[] urls = new URL[objUrls.length]; //在Java中,不能直接将数组从一个类型转换到另一个类型,因此必须创建一个循环, //对数组中的每个成员单独进行转换。 for(int i=0; i<objUrls.length; i++){ urls[i] = (URL) objUrls[i]; } new DoBackgroundTask().execute(urls); 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;//文件大小 } private class DoBackgroundTask extends AsyncTask<URL, Integer, Long> { /** * 这个方法用于放置需要长时间运行的代码并在后台线程中执行。 * @param progress 参数类型(Integer)由AsyncTask<>的第1个泛型参数类型定义 * @return 返回类型(Long)由AsyncTask<>的第3个泛型参数类型定义 */ @Override protected Long doInBackground(URL... urls) { int count = urls.length; long totalBytesDownloaded = 0; for (int i=0; i<count; i++) { totalBytesDownloaded += DownLoadFile(urls[i]); //报告进度 publishProgress((int) (((i+1)/(float)count)*100)); } return totalBytesDownloaded; } /** * 这一方法在UI线程中启动并在调用publishProgress()方法时调用。 * @param progress 参数类型(Integer)由AsyncTask<>的第2个泛型参数类型定义 */ protected void onProgressUpdate(Integer... progress) { String percent = String.valueOf(progress[0]) + "% downloaded"; Log.d("AndroidTest", percent); Toast.makeText(getBaseContext(), percent, Toast.LENGTH_SHORT).show(); } /** * 这一方法在UI线程中启动并在doInBackground()方法执行完毕后调用。 * @param result 参数类型(Long)由AsyncTask<>的第3个泛型参数类型定义 */ protected void onPostExecute(Long result) { String str = "Downloaded "+result+" bytes"; Toast.makeText(getBaseContext(), str, Toast.LENGTH_SHORT).show(); //注意: 当后台线程执行完毕时,需要手动调用stopSelf()方法来停止服务 //stopSelf()方法相当于调用stopService()方法来停止服务。 stopSelf(); } } }