Android-Service的用法

來源:互聯網
上載者:User

標籤:

Service是後台運行,不可見,沒有介面的頁面,優先順序高於Activity,可以用來播放音樂、記錄地理資訊位置的改變、監聽某種動作,類型有兩種,一是本地服務,有start和bind兩種啟動方式,另一種是遠程服務。

目標效果:

 

程式運行顯示所有的按鈕控制項,分為兩類,上邊是start的啟動和停止,下邊是bind的啟動和停止,點擊輸出對應的生命週期的方法內容。


1.activity_main.xml頁面放置所有按鈕控制項。

activity_main.xml頁面:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity" >    <TextView        android:id="@+id/tvStart"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_alignParentTop="true"        android:text="Start:" />    <Button        android:id="@+id/btStart"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_alignParentRight="true"        android:layout_below="@+id/tvStart"        android:text="StartService" />    <Button        android:id="@+id/btStop"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_alignParentRight="true"        android:layout_below="@+id/btStart"        android:text="StopService" />    <TextView        android:id="@+id/tvBind"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_below="@+id/btStop"        android:text="Bind:" />    <Button        android:id="@+id/btBind"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_alignParentRight="true"        android:layout_below="@+id/tvBind"        android:text="BindService" />    <LinearLayout        android:id="@+id/changeOne"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@+id/btBind"        android:orientation="horizontal" >        <Button            android:id="@+id/btPrevious"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_alignParentRight="true"            android:layout_weight="1"            android:text="上一首" />        <Button            android:id="@+id/btNext"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_alignParentRight="true"            android:layout_weight="1"            android:text="下一首" />    </LinearLayout>    <LinearLayout        android:id="@+id/changeTwo"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_below="@+id/changeOne"        android:orientation="horizontal" >        <Button            android:id="@+id/btPlay"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_alignParentRight="true"            android:layout_weight="1"            android:text="播放" />        <Button            android:id="@+id/btPause"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_alignParentRight="true"            android:layout_weight="1"            android:text="暫停" />    </LinearLayout>    <Button        android:id="@+id/btUnBind"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_alignParentRight="true"        android:layout_below="@+id/changeTwo"        android:text="UnBindService" /></RelativeLayout>


2.建立myStartService.java頁面繼承Service,重寫方法start方式啟動時調用。myStartService.java頁面:
package com.example.service;import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.util.Log;public class myStartService extends Service{@Overridepublic IBinder onBind(Intent arg0) {Log.i("MainActivity","startService--onBind()");return null;}@Overridepublic void onCreate() {Log.i("MainActivity","startService--onCeate()");super.onCreate();}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {Log.i("MainActivity","startService--onStartCommand()");return super.onStartCommand(intent, flags, startId);}@Overridepublic void onDestroy() {super.onDestroy();Log.i("MainActivity","startService--onDestroy()");}}


3.建立myBindService.java頁面繼承Service,重寫方法,bind方式啟動時調用。myBindService.java頁面:
package com.example.service;import android.app.Service;import android.content.Intent;import android.content.ServiceConnection;import android.os.Binder;import android.os.IBinder;import android.util.Log;public class myBindService extends Service{/*定義類繼承Binder返回服務物件*/public class MyBinder extends Binder{public myBindService getService(){return myBindService.this;}}@Overridepublic IBinder onBind(Intent arg0) {Log.i("MainActivity","bindService--onBind()");return new MyBinder();//執行個體服務物件並返回}@Overridepublic void onCreate() {super.onCreate();Log.i("MainActivity","bindService--onCeate()");}@Overridepublic void unbindService(ServiceConnection conn) {super.unbindService(conn);Log.i("MainActivity","bindService--unbindService()");}@Overridepublic void onDestroy() {super.onDestroy();Log.i("MainActivity","bindService--onDestroy()");}public void play(){Log.i("MainActivity","播放");}public void pause(){Log.i("MainActivity","暫停");}public void previous(){Log.i("MainActivity","上一首");}public void next(){Log.i("MainActivity","下一首");}}


4.對於建立的兩個Service,都需要在AndroidManifest.xml頁面進行註冊。AndroidManifest.xml頁面:
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.service"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="17"        android:targetSdkVersion="19" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.example.service.MainActivity"            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 -->        <service android:name="com.example.service.myStartService"></service>        <service android:name="com.example.service.myBindService"></service>    </application></manifest>


5.MainActivity.java頁面進行點擊事件的綁定。MainActivity.java頁面:
package com.example.service;import com.example.service.myBindService.MyBinder;import android.os.Bundle;import android.os.IBinder;import android.app.Activity;import android.app.Service;import android.content.ComponentName;import android.content.Intent;import android.content.ServiceConnection;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends Activity implements OnClickListener {private Button btStart, btStop, btBind, btPrevious, btNext, btPlay,btPause, btUnBind;private Intent intentStart,intentBind;private myBindService service;/*得到服務物件*/private ServiceConnection conn=new ServiceConnection() {/*當啟動源跟Service的串連意外丟失的時候會調用這個方法,比如當Service崩潰了或者被強行殺死了*/@Overridepublic void onServiceDisconnected(ComponentName arg0) {}/*當啟動源跟Service成功串連之後將會自動調用這個方法*/@Overridepublic void onServiceConnected(ComponentName name, IBinder binder) {service=((MyBinder)binder).getService();//得到服務物件}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);getId();bindClick();}private void getId() {btStart = (Button) findViewById(R.id.btStart);btStop = (Button) findViewById(R.id.btStop);btBind = (Button) findViewById(R.id.btBind);btPrevious = (Button) findViewById(R.id.btPrevious);btNext = (Button) findViewById(R.id.btNext);btPlay = (Button) findViewById(R.id.btPlay);btPause = (Button) findViewById(R.id.btPause);btUnBind = (Button) findViewById(R.id.btUnBind);}private void bindClick() {btStart.setOnClickListener(this);btStop.setOnClickListener(this);btBind.setOnClickListener(this);btPrevious.setOnClickListener(this);btNext.setOnClickListener(this);btPlay.setOnClickListener(this);btPause.setOnClickListener(this);btUnBind.setOnClickListener(this);}@Overridepublic void onClick(View view) {switch (view.getId()) {case R.id.btStart:intentStart=new Intent(MainActivity.this,myStartService.class);startService(intentStart);break;case R.id.btStop:stopService(intentStart);break;case R.id.btPlay:service.play();break;case R.id.btPause:service.pause();break;case R.id.btPrevious:service.previous();break;case R.id.btNext:service.next();break;case R.id.btBind://綁定intentBind=new Intent(MainActivity.this,myBindService.class);//第一個參數為執行個體的intent對象,第二個參數為得到的服務物件bindService(intentBind, conn,Service.BIND_AUTO_CREATE);break;case R.id.btUnBind://解除綁定,只可點擊一次,並且如果想要結束啟動源,必須解除綁定unbindService(conn);break;}}}


6.運行就顯示目標效果了。






Android-Service的用法

聯繫我們

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