Android開發入門之Service用法分析_Android

來源:互聯網
上載者:User

本文執行個體講述了Android中Service用法。分享給大家供大家參考,具體如下:

關於Service的講解網上已經很多了,這裡是關於自己通過寫代碼Service的一點體會 還有結合其他人對Service的一點總結

Service可以理解為一個隱形的Activity 但它又與Activity有些不同,首先Service是沒介面,使用者看不到 可互動的組件 層級是與Activity是差不多的

Service中定義了一系列和自身聲明周期相關的方法:

onBind(...)是必須實現的方法,返回一個綁定介面給Service
onCreate(); 當Service第一次被建立時 由系統調用
onStart(...)當通過startService()方法調用啟動Service時被調用
onDestroy();當Service不再使用,系統調用該方法....

本次代碼分別有MainActivity,Java,MyService.java main.xml這幾個重要檔案 下面通過這幾個檔案對Service進行理解 見注釋

老規矩 先開始布局 挺簡單的 就是幾個Button

<?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="Service測試" android:gravity="center_horizontal" /><Button android:id="@+id/startButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Start Service"/><Button android:id="@+id/stopButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Stop Service"/><Button android:id="@+id/bindButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Bind Service"/><Button android:id="@+id/unBindButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Unbind Service"/></LinearLayout>

布局效果圖:

開始服務檔案, MyService繼承Service

public class MyService extends Service{ final static String TAG = "MyService"; @Override public IBinder onBind(Intent intent) {  Log.i(TAG,"OnBind()......");  showInfo("Onbind()......");  return null; } // Setvice建立時被調用 @Override public void onCreate() {  Log.i(TAG,"onCreate()......");   showInfo("onCreate()......");  super.onCreate(); } //當客戶調用startService()啟動Service時被調用 @Override public void onStart(Intent intent, int startId) {  Log.i(TAG,"onStart()........");  showInfo("onStart()........");  super.onStart(intent, startId); } @Override public void onDestroy() {  Log.i(TAG,"onDestroy()........");  showInfo("onDestroy()........");  super.onDestroy(); } @Override public boolean onUnbind(Intent intent) {  Log.i(TAG,"onUnbind()........");  showInfo("onUnbind()........");  return super.onUnbind(intent); } public void showInfo(String str) {  Toast.makeText(this, str, Toast.LENGTH_SHORT).show(); }}

上面主要是Service中幾個周期函數 這個MyService代表一個服務,當然在這裡面我們在裡面加什麼實質性的東西,例如可以在

Onstart(...)函數裡建立一個音樂播放器MediaPlayer 當服務被啟動時播放音樂.....

你建立了Service  就跟你建立Activity一樣 必須在Manifest裡註冊 下面開始註冊

<!-- 增加的Service --><service android:name=".MyService"><intent-filter > <action android:name="com.study.android.action.MY_SERVICE"/></intent-filter></service>

服務就這樣 註冊成功。光註冊成功還沒有完成任務哦......  還有啟動服務,停止服務,綁定服務,解除綁定的服務

package com.study.android;import android.app.Activity;import android.app.Service;import android.content.ComponentName;import android.content.Intent;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.Toast;public class MainActivity extends Activity { final static String ACTION = "com.study.android.action.MY_SERVICE"; private Button startButton,stopButton; private Button bindButton,unbindButton; @Override public void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  setContentView(R.layout.main);  startButton = (Button)findViewById(R.id.startButton);  stopButton = (Button)findViewById(R.id.stopButton);  bindButton = (Button)findViewById(R.id.bindButton);  unbindButton = (Button)findViewById(R.id.unBindButton);  // 開啟服務  startButton.setOnClickListener(new OnClickListener() {  @Override  public void onClick(View v)  {   // 啟動服務   startService(buildIntent());  } });  //startButton按下後 周期函數執行順序 onCreate()----->onStart()  /******************************************/  // 停止服務  stopButton.setOnClickListener(new OnClickListener() {  @Override  public void onClick(View v)  {   stopService(buildIntent());  } });  //stopButton按下後 周期函數執行順序 onDestroy()   /******************************************/  // 綁定服務  bindButton.setOnClickListener(new OnClickListener() {  @Override  public void onClick(View v)  {   bindService(buildIntent(),conn,Service.BIND_AUTO_CREATE);   /*第三個參數:如何建立service 一般是制定綁定時自動建立*/  } });  // bindButton 被按下後(當前服務已經stop掉)周期函數執行順序 onCreate()------->onBind()   /******************************************/  // 接觸綁定Service  unbindButton.setOnClickListener(new OnClickListener() {  @Override  public void onClick(View v)  {   unbindService(conn);  } });  //unbindButton按下後 周期函數執行順序onUnbind()------->onDestroy() } // 連線物件 private ServiceConnection conn = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) {   Log.i("SERVICE","串連服務成功!");   showInfo("串連服務成功!"); } @Override public void onServiceDisconnected(ComponentName name) {  Log.i("SERVICE","服務串連斷開!");  showInfo("服務串連斷開!"); } }; public Intent buildIntent() {  Intent intent = new Intent();  // 設定Intent屬性 注意:這裡action屬性要與Manifest裡服務對應  intent.setAction(ACTION);  return intent; } public void showInfo(String str) {   Toast.makeText(this, str, Toast.LENGTH_SHORT).show(); }}

更多關於Android相關內容感興趣的讀者可查看本站專題:《Android Service組件提示總結》、《Android編程之activity操作技巧總結》、《Android資源操作技巧匯總》、《Android檔案操作技巧匯總》、《Android操作SQLite資料庫技巧總結》、《Android操作json格式資料技巧總結》、《Android資料庫操作技巧總結》、《Android開發入門與進階教程》、《Android視圖View技巧總結》及《Android控制項用法總結》

希望本文所述對大家Android程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.