筆記如下
-
服務(wù)介紹:下面試官方的說法
3.png
-
服務(wù)有兩種形式:
1.開啟服務(wù)
2.綁定服務(wù)
3.png
編寫服務(wù)的步驟:
1.繼承一個service 類 , 那么就寫了 一個服務(wù)
2.到 清單文件中進(jìn)行配置
3.啟動服務(wù), 關(guān)閉服務(wù)
- 開啟服務(wù)
配置文件中
<service android:name="com.chen.myapplication02.TestService">
Intent intent = new Intent();
intent.setClass(this,TestService.class);
//開啟服務(wù)
startService(intent);
//關(guān)閉服務(wù)
stopService(intent);
public class TestService extends Service {
//實現(xiàn)抽象方法
}
在開啟服務(wù)中是調(diào)用服務(wù)中的方法的
- 綁定服務(wù)
配置文件中
<service android:name="com.chen.myapplication02.TestService">
activity中
//綁定服務(wù)
public void bindService(View v){
Intent intent = new Intent();
intent.setClass(this,TestService.class);
//綁定服務(wù)
//conn:通訊的頻道
//BIND_AUTO_CREATE :綁定的時候就去創(chuàng)建服務(wù)
//intent:找到了需要綁定的服務(wù)
//new MyConnection():返回一個在目標(biāo)服務(wù)中自定義方法的類(代理人)
bindService(intent,conn,BIND_AUTO_CREATE);
}
//IService是一個接口,里面聲明了在服務(wù)中自定義的私有方法
IService agent ;
private class MyConnection implements ServiceConnection{
//當(dāng)成功的綁定了服務(wù),用于返回代理人
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//獲得了返回的代理人
agent = (IService) service;
System.out.println("綁定成功.....");
}
//當(dāng)服務(wù)接觸綁定的時候,會調(diào)用的方法
@Override
public void onServiceDisconnected(ComponentName name) {
//防止內(nèi)存溢出
agent = null;
System.out.println("綁定失敗.....");
}
}
//調(diào)用服務(wù)中的自定義的方法
public void call(View v){
agent.callMethodServive("伯伯",250);
}
Service中
public class TestService extends Service {
//代理人
//這里繼承了Binder是IBinder的實現(xiàn)類
private class MyAgent extends Binder implements IService {
public void callMethodServive(String name , int money){
methodInService(name,money);
}
}
//當(dāng)綁定了服務(wù)的時候,就會調(diào)用onBind方法,返回代理人
@Override
public IBinder onBind(Intent intent) {
System.out.println("onbind執(zhí)行了....服務(wù)被綁定了.....");
return new MyAgent();
}
public void methodInService(String name , int money){
Toast.makeText(this, "ok了.....", Toast.LENGTH_SHORT).show();
System.out.println("服務(wù)中的方法被調(diào)用到了.....");
}
}
IService 中
public interface IService {
public void callMethodServive(String name , int money);
}
在綁定服務(wù)中就可以調(diào)用自己在服務(wù)中自定義的方法了