举例说明如何在android中使用Service

来源:互联网 发布:淘宝生意经 编辑:程序博客网 时间:2024/05/22 09:01
在android中,Service是以分时进程的方式运行,这表示即便在Activity里运行Service,它们也不会在同一个程序中运行,而是在两个不同的程序中运行。服务的启动可以没有Activity的存在,所以,即便是利用Activity带起服务,也会有各自独立的事件及焦点要处理。许多Android底层的系统服务(System Service)也是继承自Android.app.Service,一旦程序继承自Service类,那么服务的生态链就先从onCreate开始(如果有重写的话),接着应付进入启动服务onStart(),默认继承的Service类并不一定要有onStart(),但一定要重写public IBinder onBind(Intent intent)方法。

       一旦服务在onStart()被启动后,程序就写完了,只要继承Service对象里,编写如BrocastReceiver这类对象,就可以开始聆听操作系统的广播的信息了。

       如果直接编写Service的话,无法证明服务真的在后台运行,所示在程序中开户一个Runnable进程,每一秒都在控制台(console)里输出的微尘数(整数counter),用来证明系统服务在运行中。

 

程序如下所示:

 

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class A04Activity extends Activity {
 private Button b01,b02;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        b01=(Button)findViewById(R.id.button01);
        b02=(Button)findViewById(R.id.button02);
        b01.setBackgroundColor(Color.GREEN);
        b02.setBackgroundColor(Color.RED);
        b01.setText("启动Service");
        b02.setText("停止Service");
        b01.setOnClickListener(new OnClickListener(){
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub

/**

*虽然打开Service的方法与打开Activity都用Intent对象,但是它们的方法有明显的不同之处:

*1.打开服务用startService(Intent   intent),而打开Activity用startActivity(Intent  intent)

*2.结束服务用stopService(Intent   intent),而结束Activity用finish();

*/
    Intent i=new Intent(A04Activity.this,ServiceTest.class);

//设置新Task的方式
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startService(i);
   }         
        });
        b02.setOnClickListener(new OnClickListener(){
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Intent i=new Intent(A04Activity.this,ServiceTest.class);
    stopService(i);
   }         
        });
    }
}

 

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

public class ServiceTest extends Service{
 //创建Handler对象,作为进程传递postDelayed之用
 Handler h=new Handler();
 int counter;
 //创建线程
 Runnable r=new Runnable(){

  @Override
  public void run() {
   // TODO Auto-generated method stub
   counter++;
   //调用Log对象,在LogCat中显示信息,以验证Service正在运行
   Log.i("I LOVE YOU", "count:"+Integer.toString(counter));   
   System.out.println("--------------------------");//注意用此语句输出与Log.i(tag,String s);的不同之处
   //每一秒调用线程,反复运行
   h.postDelayed(r, 1000);
  }
  
 };
 
 public void onStart(Intent intent,int startId){
  //服务开始,每一秒调用线程
  h.postDelayed(r, 3000);
  super.onStart(intent, startId);
 }
 public void onCreate(){
  super.onCreate();
 }

 @Override
 public IBinder onBind(Intent intent) {
  // TODO Auto-generated method stub
  return null;
 }
 public void onDestory(){
  //若服务结束,则删除线程r
  h.removeCallbacks(r);
  super.onDestroy();
 }

}

注意要在AndroidManifest.xml中配置Service如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="
http://schemas.android.com/apk/res/android"
    package="com.my.a04"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".A04Activity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- 创建Service类,并指定类的名称 -->
        <!-- 指定exported属性为true.说明其他程序可以访问该类 -->
        <service
            android:name=".ServiceTest"
            android:exported="true"
            android:process=":remote"
            ></service>
    </application>

</manifest>