使用startService启动服务与使用stopService的生命周期:
onCreate()---àonStartCommand()---àonDestroy()
启动方法:
Intent intent=new Intent(this,MyStarService.class);
startService(intent);
关闭方法:
Intent intent1=new Intent(this, MyStarService.class);
stopService(intent1);
启动一个服务并向服务中传入参数:
Intent intent=new Intent(MainActivity.this,LoadService.class);
intent.putExtra("URI",image_path);
startService(intent);
如何在服务中获得activity中传递的数据
在onStartCommand()方法中可以获取得到
如果需要获得服务返回来的信息,需要在服务的类中发送一个广播,在需要获得消息的类中定义一个广播接收者,接收信息
具体例子:
实现功能:前台发送一个图片下载路径给服务,服务进行下载,下载完了保存在sd卡中并且发送一个广播给前台,告诉前台已经下载完成
public class LoadService extends Service {
private String uri_path=null;
Handler handler=new Handler(){
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 1:
stopSelf();//自己停止自己
Intent intent =newIntent("ACTION_DOWNLOAD_PIC");
intent.putExtra("result","ok");
sendBroadcast(intent);
break;
default:
break;
}
};
};
@Override
public void onCreate() {
// TODO Auto-generatedmethod stub
super.onCreate();
}
public class MyThread implements Runnable{
@Override
public void run() {
HttpClient httpClient=new DefaultHttpClient();
HttpPost httpPost=new HttpPost(uri_path);
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode()==200) {
byte[]result=EntityUtils.toByteArray(httpResponse.getEntity());
boolean flag=SdCardHelper.saveFileToSdCard(result, "baidu.jpg");
if (flag) {
Message message=Message.obtain();
handler.sendEmptyMessage(1);
}
}
} catch (Exception e) {
// TODO Auto-generatedcatch block
e.printStackTrace();
}
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generatedmethod stub
//获得activity传递过来的信息
uri_path=intent.getStringExtra("URI");
new Thread(new MyThread()).start();
return super.onStartCommand(intent, flags, startId);
}
public IBinder onBind(Intent intent) {
// TODO Auto-generatedmethod stub
return null;
}
@Override
public boolean stopService(Intent name) {
// TODO Auto-generatedmethod stub
return super.stopService(name);
}
}
public class MainActivity extends Activity {
private Button button;
private ImageView imageView;
private MyBroadcastReceiver myBroadcastReceiver;
private final String image_path = "http://www.baidu.com/img/bdlogo.gif";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button) findViewById(R.id.button1);
imageView=(ImageView) findViewById(R.id.imageView1);
myBroadcastReceiver=newMyBroadcastReceiver();
button.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Intent intent=newIntent(MainActivity.this, LoadService.class);
intent.putExtra("URI",image_path);
startService(intent);
}
});
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
IntentFilter filter=new IntentFilter("ACTION_DOWNLOAD_PIC");
registerReceiver(myBroadcastReceiver, filter);
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
unregisterReceiver(myBroadcastReceiver);
}
/**
* 定义一个广播接收器
*/
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("ACTION_DOWNLOAD_PIC")) {
String result =intent.getStringExtra("result");
if (result.equals("ok")) {
// 从SdCard中获取数据
byte[] data = SdCardHelper
.readDataFromSdCardCustomDir("/mnt/sdcard/baidu.jpg");
Bitmap bitmap = BitmapFactory.decodeByteArray(data,0,
data.length);
imageView.setImageBitmap(bitmap);
}
}
}
}
}
1.写一个类继承IntentService类
1. 在该类的构造方法的super中传入参数super("aa");aa为线程名随便定义
2. 重写onHandleIntent方法,在该方法中实现耗时操作 ,不用自己开一个子线程进行耗时工作,与上面的服务方式不同,其他的服务一般都要自己开一个线程
3. 在清单文件中进行配置
4. 如果要获得服务中的信息还是要构建一个广播
如果一个服务想自己停止自己 调用stopSelf()方法,如果外部想停止一个服务,调用stopService()
package com.jason.android24_intentservicedownloadpic;import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.IntentService;
import android.content.Intent;
import android.os.Message;
public class DownLoadService extends IntentService {
public DownLoadService(String name) {
super(name);
// TODO Auto-generated constructor stub
}
@Override
/**
*重写 onHandleIntent,它是一个抽象方法,必须重写
*它的执行顺序是这样的:
*onCreate
* 1. 创建一个线程
* 2. 获取线程中的Looper
* 3. 构建一个Handler
*
*onStartCommand
* onStart
* 1. 构建消息,并且将Client端的Intent通过消息发送给了Handler
*Handler会去处理消息
*1. 直接调用了onHandleIntent -------
* |
* 自己重新的onHandleIntent <---------
*
*
*/
protected void onHandleIntent(Intent intent) {
// 完成耗时工作
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(intent.getStringExtra("URI"));
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
byte[] result = EntityUtils.toByteArray(httpResponse
.getEntity());
// 保存到SdCard中
boolean flag = SdCardHelper.saveFileToSdCard(result,
"baidu.jpg");
if (flag) {
// 发广播
Intent intent2 =new Intent("ACTION_DOWNLOAD_PIC");
intent2.putExtra("result", "OK");
sendBroadcast(intent2);
}
}
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}