Android Service與Runnable整合并用

來源:互聯網
上載者:User

服務的啟動沒有Activity,即便是利用Activity帶起服務,也會有各看成獨立的事件及焦點要處理。

Service繼承自Android.app.Service。

服務的生態鏈就先從onCreate()開始(如果有重寫的話) ,接著應會進入啟動服務onStart(),預設繼承的Service類,並不一定要有onStart(),但是一定要重寫public IBinder onBind(Intent intent)方法。

 package cn.iimob;

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

public class demo extends Activity {
    private Button btnStartService,btnStopService;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnStartService=(Button)findViewById(R.id.btnStartService);
        btnStopService=(Button)findViewById(R.id.btnStopService);
        btnStartService.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                //構建 Intent 對象,指定開啟對象為 MyService服務
                Intent i=new Intent(demo.this, MyService.class);
                //設定新Task的方式
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                //以startService 方法啟動 Intent
                startService(i);
            }
        });
        btnStopService.setOnClickListener(new Button.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                // 構建 Intent對象,指定關閉的對象為MyService服務
                Intent i=new Intent(demo.this, MyService.class);
                
                //以stopService 方法關閉 Intent
                stopService(i);
            }
        });
    }
}

 package cn.iimob;

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

/**
 * 
 *  @Project       : servicedemo
 *  @Program Name  : cn.iimob.MyService.java
 *  @Class Name    : MyService
 *  @Description   : 自訂 MyService 類繼承 Service 類
 *  @Author        : zh
 *  @Creation Date : 2011-11-3 上午09:49:00 
 *  @ModificationHistory  
 *  Who        When          What 
 *  --------   ----------    -----------------------------------
 *  username   2011-11-3       TODO
 */
public class MyService extends Service {

    /**
     * 建立 Handler 對象,作為進程 傳遞 postDelayed 之用
     */
    private Handler myhandler = new Handler();
    
    /**
     * 為了確認系統服務運行情況
     */
    private int intCounter=0;
    
    /**
     * 成員變數 myTasks為Runnable對象,作為Timer之用
     */
    private Runnable myTasks=new Runnable() {
        /**
         * 進程運行
         */
        @Override
        public void run() {
            // TODO Auto-generated method stub
            //遞增counter整數,作為後台服務已耗用時間識別
            intCounter++;
            //以Log 對象在LogCat 裡輸出Log資訊,監看服務運行情況
            Log.i("Run Service", "Counter:"+Integer.toString(intCounter));
            myhandler.postDelayed(myTasks, 1000);
        }
    };
    
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    @Override
    public void onStart(Intent intent,int startId){
        myhandler.postDelayed(myTasks, 1000);
        super.onStart(intent, startId);
        Log.i("Start Service", "onStart");
    }
    
    @Override
    public void onCreate(){
        super.onCreate();
        Log.i("Create Service", "onCreate");
    }
    
    @Override
    public void onDestroy(){
        //當服務結束,刪除 mTasks 運行線程 
        myhandler.removeCallbacks(myTasks);
        super.onDestroy();
        Log.i("Destroy Service", "onDestroy");
    }
    
    
}

 

 <?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"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
<Button android:text="開始Service" android:id="@+id/btnStartService" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<Button android:text="終止Service" android:id="@+id/btnStopService" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>

 

 <?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="cn.iimob"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".demo"
                  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:exported屬情為true,表示此服務可被其他程式訪問  -->
        <service android:name=".MyService" android:exported="true" android:process=":remote"></service>
    </application>
    <uses-sdk android:minSdkVersion="8" />

</manifest> 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.