android service總結

來源:互聯網
上載者:User

標籤:android   線程   服務   

1、通過startservice方法啟動一個服務,service不能自己啟動自己。若在一個服務中啟動一個activity則,必須是申明一個全新的activity任務TASK。通過startservice方法啟動的服務不會隨著啟動組件的消亡而消亡,而是一直運行著。

Service生命週期 onCreate()-------->onStartCommand()----------->onDestroy() 

startService()啟動一個服務後,若在該服務做耗時操作且沒有寫線程,則會導致主線程阻塞!

服務啟動運行後會一直運行onStartCommand()方法。

2、用bindService啟動一個服務,該服務和activity是綁定在一起的:啟動時,先調用onCreate()------>onBind()--------->onServiceConnected(),啟動服務的組件消亡,服務也就消亡了。

3、AIDL服務調用方式

demo:http://download.csdn.net/detail/u014600432/8175529

1)服務端代碼:

首先定義一個介面描述語言的介面:

package com.example.service;interface DataService{double getData(String arg);}

然後定義服務元件代碼:

/** *Version: *author:YangQuanqing *Data: */package com.example.android_aidl_service;import com.example.service.DataService;import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os.IBinder;import android.os.RemoteException;/** * @author YangQuanqing yqq * */public class MyService extends Service {@Overridepublic IBinder onBind(Intent arg0) {<span style="color:#ff0000;">//返回binder由didl檔案產生</span>return binder;}//定義給用戶端調用的方法 (aidl檔案)Binder binder=new <span style="color:#ff0000;">DataService.Stub()</span> {@Overridepublic double getData(String arg) throws RemoteException {if(arg=="a"){return 1;}if(arg=="b"){return 2;}return 0;}};}

服務端的資訊清單檔:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.android_aidl_service"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="17" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.example.android_aidl_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             android:name="com.example.android_aidl_service.MyService"            >            <intent-filter>                <!-- 意圖過濾器要把aidl包名加類名 -->                <action android:name="com.example.service.DataService"/>            </intent-filter>        </service>    </application></manifest>

用戶端編碼:

把aidl檔案包拷貝到用戶端,用戶端代碼如下:

package com.example.android_aidl_client;import android.app.Activity;import android.content.ComponentName;import android.content.Intent;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.os.RemoteException;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;import com.example.service.DataService;public class MainActivity extends Activity {private Button btn1,btn2;//定義一個AIDL執行個體private DataService dataService;private TextView tv;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btn1=(Button)this.findViewById(R.id.button1);btn2=(Button)this.findViewById(R.id.button2);tv=(TextView)this.findViewById(R.id.textView1);//綁定服務btn1.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {Intent intent=new Intent(DataService.class.getName());//啟動服務bindService(intent, conn, BIND_AUTO_CREATE);}});//調用服務的方法btn2.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {try {int result=(int) dataService.getData("a");tv.setText(result+"");} catch (RemoteException e) {// TODO Auto-generated catch blocke.printStackTrace();}}});}//用戶端與服務互動private ServiceConnection conn=new ServiceConnection() {@Overridepublic void onServiceDisconnected(ComponentName name) {}@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {//傳入servicedataService=DataService.Stub.asInterface(service);}};@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}

這樣就可以完成處理序間通訊了。


4、用bindService啟動服務並訪問本地服務的方法。

訪問介面代碼:

package com.example.android_service_binder;import android.app.Activity;import android.content.ComponentName;import android.content.Context;import android.content.Intent;import android.content.ServiceConnection;import android.os.Bundle;import android.os.IBinder;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;import com.example.android_service_binder.MyService.LocalBinder;public class MainActivity extends Activity {//銷毀綁定@Overrideprotected void onStop() {super.onStop();if(flag){//解除綁定unbindService(serviceConnection);flag=false;}}//綁定Service@Overrideprotected void onStart() {// TODO Auto-generated method stubsuper.onStart();/*Intent intent=new Intent(MainActivity.this,MyService.class);//啟動servicebindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);*/}private Button btnBinder=null;private Button btnCall=null;private TextView tv=null;private MyService myService;//service執行個體private boolean flag=false;//預設不綁定@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btnBinder=(Button)this.findViewById(R.id.button1);btnCall=(Button)this.findViewById(R.id.button2);tv=(TextView)this.findViewById(R.id.textView1);btnBinder.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {Intent intent=new Intent(MainActivity.this,MyService.class);//啟動servicebindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);}});//調用service方法btnCall.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {//處於綁定狀態if(flag){int result=myService.getRandom();tv.setText("<<<<<"+result);}}});}private ServiceConnection serviceConnection= new ServiceConnection(){//串連@Overridepublic void onServiceConnected(ComponentName arg0, IBinder iBinder) {//獲得服務的The IBinder of the Service's communication channel, which you can now make calls on.LocalBinder binder=(LocalBinder) iBinder;//獲得服務myService=binder.getService();flag=true;}//不串連@Overridepublic void onServiceDisconnected(ComponentName arg0) {flag=false;}};@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}

服務元件代碼:

/** *Version: *author:YangQuanqing *Data: */package com.example.android_service_binder;import java.util.Random;import android.app.Service;import android.content.Intent;import android.os.Binder;import android.os.IBinder;/** * @author YangQuanqing yqq * */public class MyService extends Service {private final LocalBinder lb=new LocalBinder();private final Random num=new Random();@Overridepublic IBinder onBind(Intent arg0) {// 返回本地Binder的子類執行個體return  lb;}//定義一個本地Binder類繼承Binderpublic class LocalBinder extends Binder{//獲得Servie子類當前執行個體給用戶端public MyService getService(){return MyService.this;}}public int getRandom(){return num.nextInt(98);}}


通過該demo可以訪問本地服務裡面的方法。

demo:http://download.csdn.net/detail/u014600432/8175633

5、IntentService

本質是開啟一個線程來完成耗時操作。

IntentService生命週期:

onCreate()------->onStartCommand()--------->onHandleIntent()--------->onDestroy()

/** *Version: *author:YangQuanqing *Data: */package com.example.android_intentservice;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.util.EntityUtils;import android.app.IntentService;import android.content.Intent;import android.os.Environment;import android.widget.Toast;/** * @author YangQuanqing  不需要開啟線程(看源碼知道是自己封裝了開啟線程),不需要關閉服務,自己關閉,單線程下載資料 *  * 一定要記得執行個體化!!! */public class DownLoadService extends IntentService {@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();}public DownLoadService() {super("DownLoadService");}// 只需複寫如下方法// 在該方法中執行操作@Overrideprotected void onHandleIntent(Intent intent) {// 獲得提取網路資源的執行個體HttpClient httpClient = new DefaultHttpClient();// 佈建要求方式HttpPost httpPost = new HttpPost(intent.getStringExtra("url"));// 設定儲存路徑File file = new File(Environment.getExternalStorageDirectory(),"IntentService.gif");// 定義輸出資料流用於寫FileOutputStream fileOutputStream = null;byte[] data = null;// 網路資料try {// 執行請求獲得響應HttpResponse httpResponse = httpClient.execute(httpPost);// 判斷響應狀態代碼if (httpResponse.getStatusLine().getStatusCode() == 200) {// 獲得響應實體HttpEntity httpEntity = httpResponse.getEntity();// 獲得網路資料data = EntityUtils.toByteArray(httpEntity);// 判斷SD卡是否可用if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {// 寫入SD卡fileOutputStream=new FileOutputStream(file);fileOutputStream.write(data, 0, data.length);//Toast.makeText( DownLoadService.this,"下載完成", Toast.LENGTH_LONG).show();Toast.makeText( getApplicationContext(),"下載完成", Toast.LENGTH_LONG).show();}}} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {if (fileOutputStream != null) {try {fileOutputStream.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}}

調用服務介面:

package com.example.android_intentservice;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends Activity {private Button btn_intent=null;private String url="http://www.baidu.com/img/bdlogo.gif";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);btn_intent=(Button)this.findViewById(R.id.button1);btn_intent.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View arg0) {Intent intent=new Intent(MainActivity.this,DownLoadService.class);intent.putExtra("url", url);startService(intent);}});}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}

demo:http://download.csdn.net/detail/u014600432/8175673



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.