Android Service基础用法

演示本地服务的使用方法。

布局文件,包含两个按钮,一个启动服务,一个终止服务。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<Button  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/btn_start"
    android:text="Start Service"
    />
<Button  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/btn_stop"
    android:text="Stop Service"
    />
</LinearLayout>

Activity文件,操作服务。

package com.xiyang.android.test.service;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class AndroidServiceActivity extends Activity implements OnClickListener{
    
    private final String TAG = "AndroidService";
    private Button btnStart;
    private Button btnStop;;
    private int counter = 1;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        btnStart = (Button) this.findViewById(R.id.btn_start);
        btnStop = (Button) this.findViewById(R.id.btn_stop);
        
        btnStart.setOnClickListener(this);
        btnStop.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.btn_start:
                Log.i(TAG,"starting service...counter:"+counter);
                Intent intent = new Intent(AndroidServiceActivity.this,BackgroundService.class);
                intent.putExtra("counter", counter++);
                startService(intent);
                break;
            case R.id.btn_stop:
                stopService();
                break;
        }
    }

    private void stopService() {
        Log.i(TAG, "stoping service");
        if(stopService(new Intent(AndroidServiceActivity.this,BackgroundService.class))){
            Log.i(TAG, "stoping service successful.");
        }else{
            Log.i(TAG, "stoping service unsuccessful");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopService();
    }
    
    
    
}

服务类,BackgroundService.java

package com.xiyang.android.test.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class BackgroundService extends Service {

    private final String tag = "AndroidService";
    private NotificationManager notificationMgr;
    private ThreadGroup myThreads = new ThreadGroup("ServiceWorker");

    @Override
    public IBinder onBind(Intent intent) {
        Log.i(tag, "onBind");
        return null;
    }

    @Override
    public void onCreate() {
        Log.i(tag, "onCreate");
        super.onCreate();
        notificationMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        displayNotificationMessage("Background Service is running");
    }

    private void displayNotificationMessage(String message) {
        Notification notification = new Notification(R.drawable.btn_home,
                message, System.currentTimeMillis());

        notification.flags = Notification.FLAG_NO_CLEAR;

        //指定通知对应的intent,打开相应的应用程序
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, AndroidServiceActivity.class), 0);

        notification.setLatestEventInfo(this, tag, message, contentIntent);

        notificationMgr.notify(0, notification);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        Log.i(tag, "onStartCommand");
        int counter = intent.getExtras().getInt("counter");
        Log.v(tag, "in onStartCommand(), counter = " + counter + ", startId = "
                + startId);
        new Thread(myThreads, new ServiceWorker(counter), "BackgroundService")
                .start();

        return START_STICKY;

    }

    /**
     * 可以执行Service的操作,完成实际的工作,比如和服务器通讯,更新页面UI,发送通知等
     * @author xie.xy
     */
    class ServiceWorker implements Runnable {
        private int counter = -1;

        public ServiceWorker(int counter) {
            this.counter = counter;
        }

        public void run() {
            final String TAG2 = "ServiceWorker:"
                    + Thread.currentThread().getId();
            // do background processing here... we’ll just sleep...
            try {
                Log.v(TAG2, "sleeping for 10 seconds. counter = " + counter);
                Thread.sleep(10000);
                Log.v(TAG2, "... waking up");
            } catch (InterruptedException e) {
                Log.v(TAG2, "... sleep interrupted");
            }
        }
    }

    @Override
    public void onDestroy() {
        Log.i(tag, "onDestroy");
        //唤醒进程
        myThreads.interrupt();
        //取消通知栏信息
        notificationMgr.cancelAll();
        super.onDestroy();
    }


    @Override
    public void onStart(Intent intent, int startId) {
        Log.i(tag, "onStart");
        super.onStart(intent, startId);
    }

}

最后在清单文件中定义Service

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.xiyang.android.test.service"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="5" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AndroidServiceActivity"
                  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 android:name="BackgroundService"></service>
    </application>
</manifest>

最终效果如下图

posted on 2012-04-28 10:08  lepfinder  阅读(449)  评论(0编辑  收藏  举报