前面已经写过关于startService(Unbounded Service)的一篇文章:《Android菜鸟的成长笔记(16)——Service简介》本篇将在这一篇的基础上再来看一下startService的用法。先看一段代码:
TestService.java
- package com.example.myfirstapp;
- import android.app.Service;
- import android.content.Intent;
- import android.os.IBinder;
- import android.util.Log;
- public class TestService extends Service{
- private static final String TAG = "大碗干拌";
- @Override
- public IBinder onBind(Intent arg0) {
- // TODO Auto-generated method stub
- return null;
- }
- @Override
- public void onCreate() {
- // TODO Auto-generated method stub
- super.onCreate();
- task();
- }
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- // TODO Auto-generated method stub
- return super.onStartCommand(intent, flags, startId);
- }
- public void task(){
- int i=0;
- while(true){
- Log.i(TAG, "" + i);
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
- Button loginButton = (Button) findViewById(R.id.main_login_button);
- loginButton.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View arg0) {
- intent = new Intent(MainActivity.this, TestService.class);
- startService(intent);
- }
- });
- ImageView iv = (ImageView) findViewById(R.id.main_view_iv);
- iv.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View arg0) {
- stopService(intent);
- }
- });
会看到控制台会不断的打印,但是屏幕会失去焦点,不能操作,等十几秒后出现ANR异常。
我们再看看DDMS中进程和线程
可以看到即没有新的进程,也没有新的线程。
这充分说明Service即不是一个进程也不是一个 线程,而是一个绑定在进程中的服务,我们如果要在Service中处理延时操作应该放在线程中。
现在我们将输出Log的代码放入线程,启动Service后在MainActivity中用stopService来停止Service.
- public class TestService extends Service{
- private static final String TAG = "大碗干拌";
- @Override
- public IBinder onBind(Intent arg0) {
- // TODO Auto-generated method stub
- return null;
- }
- @Override
- public void onCreate() {
- // TODO Auto-generated method stub
- super.onCreate();
- task();
- }
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- // TODO Auto-generated method stub
- return super.onStartCommand(intent, flags, startId);
- }
- public void task(){
- new Thread(){
- public void run() {
- int i=0;
- while(true){
- Log.i(TAG, "" + i);
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- i++;
- }
- };
- }.start();
- }
- @Override
- public void onDestroy() {
- Log.i(TAG, "Service onDestory");
- super.onDestroy();
- }
- }
会发现已经调用了Service的onDestory方法,为什么还在打印Log?其实Service此时却是确实已经destroy了,但是我们启动的线程还存在,所以继续打印。
其实Service还有一个停止的方法stopSelf()
- public void task(){
- new Thread(){
- public void run() {
- int i=0;
- while(true){
- Log.i(TAG, "" + i);
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- i++;
- if(i == 10){
- stopSelf(1);
- }
- }
- };
- }.start();
- }