一般情況下,一個(gè)應(yīng)用程序就是一個(gè)進(jìn)程恩敌,這個(gè)進(jìn)程名稱就是應(yīng)用程序包名端蛆。我們知道進(jìn)程是系統(tǒng)分配資源和調(diào)度的基本單位,所以每個(gè)進(jìn)程都有自己獨(dú)立的資源和內(nèi)存空間考赛,別的進(jìn)程是不能任意訪問(wèn)其他進(jìn)程的內(nèi)存和資源的惕澎。
有不少人疑惑,Android為什么要用多進(jìn)程颜骤?用多進(jìn)程的優(yōu)點(diǎn)唧喉?缺點(diǎn)拂到?
好處:
(1)分擔(dān)主進(jìn)程的內(nèi)存壓力仇让。
當(dāng)應(yīng)用越做越大,內(nèi)存越來(lái)越多应役,將一些獨(dú)立的組件放到不同的進(jìn)程梯找,它就不占用主進(jìn)程的內(nèi)存空間了。當(dāng)然還有其他好處益涧,有心人會(huì)發(fā)現(xiàn)
(2)使應(yīng)用常駐后臺(tái)锈锤,防止主進(jìn)程被殺守護(hù)進(jìn)程,守護(hù)進(jìn)程和主進(jìn)程之間相互監(jiān)視闲询,有一方被殺就重新啟動(dòng)它久免。
Android后臺(tái)進(jìn)程里有很多應(yīng)用是多個(gè)進(jìn)程的,因?yàn)樗鼈円qv后臺(tái)扭弧,特別是即時(shí)通訊或者社交應(yīng)用阎姥,不過(guò)現(xiàn)在多進(jìn)程已經(jīng)被用爛了。
典型用法是在啟動(dòng)一個(gè)不可見(jiàn)的輕量級(jí)私有進(jìn)程鸽捻,在后臺(tái)收發(fā)消息呼巴,或者做一些耗時(shí)的事情,或者開(kāi)機(jī)啟動(dòng)這個(gè)進(jìn)程御蒲,然后做監(jiān)聽(tīng)等衣赶。
壞處:
消耗用戶的電量。 多占用了系統(tǒng)的空間厚满,若所有應(yīng)用都這樣占用府瞄,系統(tǒng)內(nèi)存很容易占滿而導(dǎo)致卡頓。應(yīng)用程序架構(gòu)會(huì)變得復(fù)雜碘箍,因?yàn)橐幚矶噙M(jìn)程之間的通信遵馆。這里又是另外一個(gè)問(wèn)題了鲸郊。
多進(jìn)程的缺陷
進(jìn)程間的內(nèi)存空間是不可見(jiàn)的。開(kāi)啟多進(jìn)程后货邓,會(huì)引發(fā)以下問(wèn)題:
1)Application的多次重建秆撮。
2)靜態(tài)成員的失效。
3)文件共享問(wèn)題逻恐。
4)斷點(diǎn)調(diào)試問(wèn)題像吻。
在了解了多進(jìn)程的優(yōu)缺點(diǎn)之后,接下來(lái)介紹使用的方法复隆。
四大組件在AndroidManifest文件中注冊(cè)的時(shí)候拨匆,有個(gè)屬性android:process這里可以指定組件的所處的進(jìn)程。
默認(rèn)就是應(yīng)用的主進(jìn)程挽拂。指定為別的進(jìn)程之后惭每,系統(tǒng)在啟動(dòng)這個(gè)組件的時(shí)候,就先創(chuàng)建(如果還沒(méi)創(chuàng)建的話)這個(gè)進(jìn)程亏栈,然后再創(chuàng)建該組件台腥。打印出它的進(jìn)程名稱:重
載Application類的onCreate方法即可。
設(shè)置android:process屬性绒北,要注意:如果是android:process=”:comm”黎侈,以:開(kāi)頭的名字,表示這是一個(gè)應(yīng)用程序的私有進(jìn)程闷游,否則它是一個(gè)全局進(jìn)程峻汉。私有進(jìn)程的進(jìn)程名稱是
會(huì)在冒號(hào)前自動(dòng)加上包名,而全局進(jìn)程則不會(huì)脐往。一般我們都是有私有進(jìn)程休吠,很少使用全局進(jìn)程。
首先創(chuàng)建一個(gè)WheatherService:
public class WheatherService extends Service {
private RemoteCallbackList<IMyAidlCallBack> mRemoteCallbackList = new RemoteCallbackList<>();
@Nullable
@Override
public IBinder onBind(Intent intent) {
return new WheatherBinder();
}
private void getWheather() {
OkHttpUtils.get()
.url("http://www.apiopen.top:88/weatherApi?city=%E5%8E%A6%E9%97%A8")
.build()
.execute(new StringCallback() {
@Override
public void onError(Call call, Exception e, int id) {
log(e.toString());
final int count = mRemoteCallbackList.beginBroadcast();
if (count == 0) {
return;
}
try {
for (int i = 0; i < count; i++)
mRemoteCallbackList.getBroadcastItem(i).onError(e.toString());
} catch (RemoteException e1) {
log(e1.toString());
}
mRemoteCallbackList.finishBroadcast();
}
@Override
public void onResponse(String response, int id) {
log(response);
final int count = mRemoteCallbackList.beginBroadcast();
if (count == 0) {
return;
}
try {
for (int i = 0; i < count; i++)
mRemoteCallbackList.getBroadcastItem(i).onSuccess(JSON.parseObject(response, Wheather.class));
} catch (RemoteException e) {
e.printStackTrace();
}
mRemoteCallbackList.finishBroadcast();
}
});
}
private void log(String value) {
Log.e("TAG", value);
}
class WheatherBinder extends IRemoteService.Stub {
private IMyAidlCallBack iMyAidlCallBack;
@Override
public void getWheather() throws RemoteException {
log("getWheather-----------------");
WheatherService.this.getWheather();
}
@Override
public void registerListener(IMyAidlCallBack callBack) throws RemoteException {
this.iMyAidlCallBack = callBack;
log("registerListener");
if (mRemoteCallbackList == null) {
log("mRemoteCallbackList==null");
return;
}
mRemoteCallbackList.register(callBack);
}
@Override
public void unRegisterListener(IMyAidlCallBack callBack) throws RemoteException {
mRemoteCallbackList.unregister(callBack);
}
}
}
在AndroidManifest問(wèn)見(jiàn)中注冊(cè)這個(gè)service:
<service
android:name=".WheatherService"
android:process=":comm">
<intent-filter>
<action android:name="com.zlx.crossprocommut.IRemoteService" />
</intent-filter>
</service>
在我們的MainActivity中進(jìn)行服務(wù)的綁定:
public class MainActivity extends AppCompatActivity {
private TextView tv;
private IRemoteService iRemoteService;
private IMyAidlCallBack mCallBack = new IMyAidlCallBack.Stub() {
@Override
public void onSuccess(final Wheather wheather) throws RemoteException {
log("value: " + wheather.toString());
tv.post(new Runnable() {
@Override
public void run() {
Wheather.DataBean data = wheather.getData();
tv.setText("City:"+data.getCity() + "\n" + "Cityid: "+data.get+"溫度:"+data.getWendu()+".....................");
}
});
}
@Override
public void onError(String error) throws RemoteException {
log("value: " + error);
}
};
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, final IBinder iBinder) {
iRemoteService = WheatherService.WheatherBinder.asInterface(iBinder);
show("Service Connected业簿!");
log("Service Connected瘤礁!");
try {
iRemoteService.registerListener(mCallBack);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
show("Service Disconnected!");
log("Service Disconnected梅尤!");
iRemoteService = null;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = findViewById(R.id.id_tv);
}
@Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, WheatherService.class);
intent.setAction("com.zlx.crossprocommut.IRemoteService");
intent.setPackage("com.zlx.crossprocommut");
bindService(intent, connection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(connection);
}
public void getWheather(View view) {
try {
if (iRemoteService != null) {
iRemoteService.getWheather();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void log(String value) {
Log.e("TAG", value);
}
private void show(String value) {
Toast.makeText(MainActivity.this, value, Toast.LENGTH_SHORT).show();
}
}
有的人會(huì)問(wèn)柜思,這里為什么要用bindService,不用startService?其實(shí)這里是看具體情況的哈巷燥,如果用bindService:activity銷(xiāo)毀酝蜒,服務(wù)也就沒(méi)了,而用startService:activity銷(xiāo)毀矾湃,服務(wù)仍然還在亡脑!
最關(guān)鍵的要?jiǎng)?chuàng)建aidl文件:
IMyAidlCallBack.aidl:
import com.zlx.crossprocommut.Wheather;
interface IMyAidlCallBack {
void onSuccess(in Wheather wheather);
void onError(String error);
}
IRemoteService.aidl:
import com.zlx.crossprocommut.IMyAidlCallBack;
interface IRemoteService {
void getWheather();
void registerListener(IMyAidlCallBack callBack);
void unRegisterListener(IMyAidlCallBack callBack);
}
Wheather.aidl:
parcelable Wheather;
注意:Wheather是一個(gè)parcelable 序列化的數(shù)據(jù)對(duì)象