传递数据的一个更好的办法是直接将活动绑定到服务上,这样活动可以直接用服务的任何公共成员和方法。
活动
package com.example.androidtest;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
public class ServicesActivity2 extends Activity {
MyService2 serviceBinder;
Intent i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_services);
}
public void startService(View view){
i = new Intent(ServicesActivity2.this, MyService2.class);
bindService(i, connection, Context.BIND_AUTO_CREATE);
}
public void stopService(View view){
stopService(new Intent(ServicesActivity2.this, MyService2.class));
}
//监控服务连接状态
private ServiceConnection connection = new ServiceConnection(){
//连接成功
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
Toast.makeText(ServicesActivity2.this, "Service onServiceConnected", Toast.LENGTH_SHORT).show();
serviceBinder = ((MyService2.MyBinder)service).getService();
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")
};
serviceBinder.urls = urls;
}catch(MalformedURLException e){
Log.d("AndroidTest", e.getMessage());
}
startService(i);
}
//连接断开
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
Toast.makeText(ServicesActivity2.this, "Service onServiceDisconnected", Toast.LENGTH_SHORT).show();
serviceBinder = null;
}
};
}
服务
package com.example.androidtest;
import java.net.URL;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyService2 extends Service {
URL[] urls;
private final IBinder binder = new MyBinder();
//为了将活动绑定到一个服务,必须首先在服务中声明一个扩展Binder类的内部类。
public class MyBinder extends Binder {
MyService2 getService(){
return MyService2.this;
}
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return binder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId){
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
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();
}
}
}