占位式插件化框架—Service通信

如果沒(méi)有看過(guò)占位式插件化框架—Activity通信的請(qǐng)先看這篇文章届巩,因?yàn)檫@篇文章是在它的基礎(chǔ)上寫的阔馋。
思考:插件p.apk中PluginActivity怎么啟動(dòng)和關(guān)閉同是插件包中的TestService?

通過(guò)占位式插件化框架—Activity通信應(yīng)該可以想到怎么實(shí)現(xiàn):

  • 先寫一個(gè)標(biāo)準(zhǔn)服務(wù)的接口ServiceInterface
  • 在插件中寫一個(gè)服務(wù)的基類BaseService咬最,BaseService繼承Service和實(shí)現(xiàn)ServiceInterface鹅巍。創(chuàng)建TestService類,TestService類繼承BaseService请敦。
  • 在主apk中創(chuàng)建一個(gè)服務(wù)的代理類(ProxyService),用于調(diào)用插件服務(wù)的方法改衩。

\color{red}{在標(biāo)準(zhǔn)stander模塊中增加ServiceInterface接口}\

public interface ServiceInterface {
    /**
     * 把宿主(app)的環(huán)境  給  插件
     *
     * @param appService
     */
    void insertAppContext(Service appService);
    void onCreate();
    int onStartCommand(Intent intent, int flags, int startId);
    void onDestroy();
    boolean onUnbind(Intent intent);
    IBinder onBind(Intent intent);
}

\color{red}{在plugin\_package模塊中增加的類和方法}\

public class BaseService extends Service implements ServiceInterface {
    public Service appService;
    @Override
    public void insertAppContext(Service appService) {
        this.appService = appService;
    }
    @Override
    public void onCreate() {
    }
    @SuppressLint("WrongConstant")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return 0;
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onDestroy() {
    }
}
public class TestService extends BaseService {

    public static Boolean Run = true;
    @Override
    public void onCreate() {
        super.onCreate();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(appService, "啟動(dòng)插件TestService", Toast.LENGTH_LONG).show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (Run) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        Log.e("migill", "插件里面的服務(wù)TestService開(kāi)啟了一個(gè)線程 正在執(zhí)行中...");
                    }
                }
                Log.e("migill", "插件里面的服務(wù)TestService開(kāi)啟的線程執(zhí)行結(jié)束");
            }
        }).start();
        return super.onStartCommand(intent, flags, startId);
    }
    @Override
    public void onDestroy() {
        Toast.makeText(appService, "關(guān)閉插件TestService", Toast.LENGTH_LONG).show();
        Run = false;
        Log.e("migill", "插件里面的服務(wù)TestService執(zhí)行onDestroy()");
        super.onDestroy();
    }
}

TestService的onStartCommand()方法開(kāi)啟了一個(gè)線程岖常,在調(diào)用onDestroy()的時(shí)候線程的run()方法就會(huì)執(zhí)行結(jié)束。
接下來(lái)就是要增加啟動(dòng)和關(guān)閉服務(wù)的按鈕葫督,點(diǎn)擊后要調(diào)用宿主的啟動(dòng)和關(guān)閉服務(wù)的方法竭鞍。

public class BaseActivity extends Activity implements ActivityInterface {
    .......
    @Override
    public ComponentName startService(Intent service) {
        Intent intentNew = new Intent();
        Log.e("migill", "BaseActivity startService className:" + service.getComponent().getClassName());
        intentNew.putExtra("className", service.getComponent().getClassName());
        return appActivity.startService(intentNew);
    }

    @Override
    public boolean stopService(Intent name) {
        Intent intentNew = new Intent();
        Log.e("migill", "BaseActivity stopService className:" + name.getComponent().getClassName());
        intentNew.putExtra("className", name.getComponent().getClassName());
        return appActivity.stopService(intentNew);
    }
}

在BaseActivity中增加啟動(dòng)和關(guān)閉服務(wù)的方法板惑。startService()和stopService()兩個(gè)方法都是調(diào)用宿主中的方法。

public class PluginActivity extends BaseActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_plugin);//執(zhí)行的是BaseActivity中的setContentView方法
        Log.e("migill", "我是插件PluginActivity");
        .......
        findViewById(R.id.bt_start_service).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startService(new Intent(appActivity, TestService.class));
            }
        });

        findViewById(R.id.bt_stop_service).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopService(new Intent(appActivity, TestService.class));
            }
        });
    }
}

點(diǎn)擊啟動(dòng)服務(wù)的按鈕偎快,調(diào)用的是BaseActivity中的startService()洒放。
點(diǎn)擊停止服務(wù)的按鈕,調(diào)用的是BaseActivity中的stopService()滨砍。
編譯apk,重命名為p.apk,并放入 /storage/emulated/0/Android/data/com.migill.pluginproject/files/這個(gè)目錄下往湿。

\color{red}{在宿主apk中加入代理服務(wù)類和需要添加的啟動(dòng)/關(guān)閉服務(wù)的方法}\

public class ProxyActivity extends Activity {
......
    @Override
    public ComponentName startService(Intent service) {
        String className = service.getStringExtra("className");
        Log.e("migill", "ProxyActivity startService className : " + className);
        Intent intent = new Intent(this, ProxyService.class);
        intent.putExtra("className", className);
        return super.startService(intent);
    }

    @Override
    public boolean stopService(Intent name) {
        String className = name.getStringExtra("className");
        Log.e("migill", "ProxyActivity stopService className : " + className);
        Intent intent = new Intent(this, ProxyService.class);
        intent.putExtra("className", className);
        return super.stopService(intent);
    }
}

這兩個(gè)方法都是開(kāi)啟和關(guān)閉代理的服務(wù)。

public class ProxyService extends Service {
    ServiceInterface serviceInterface;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("migill", "ProxyService onCreate()");
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String className = intent.getStringExtra("className");
        Log.e("migill", "ProxyService onStartCommand() className:" + className);

        try {
            Class mTestServiceClass = PluginManager.getInstance(this).getClassLoader().loadClass(className);
            Object mTestService = mTestServiceClass.newInstance();
            serviceInterface = (ServiceInterface) mTestService;
            //注入組件環(huán)境
            serviceInterface.insertAppContext(this);
            serviceInterface.onStartCommand(intent, flags, startId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.onStartCommand(intent, flags, startId);
    }
    @Override
    public void onDestroy() {
        Log.e("migill", "ProxyService onDestroy()");
        if (serviceInterface != null)
            serviceInterface.onDestroy();
        super.onDestroy();
    }
}

啟動(dòng)ProxyService服務(wù)的時(shí)候會(huì)走onStartCommand()生命周期方法惋戏,它就會(huì)根據(jù)全類名實(shí)例化對(duì)象领追,并調(diào)用serviceInterface.onStartCommand()。
關(guān)閉ProxyService服務(wù)的時(shí)候會(huì)走onDestroy()方法响逢,并調(diào)用serviceInterface.onDestroy()绒窑。


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市舔亭,隨后出現(xiàn)的幾起案子些膨,更是在濱河造成了極大的恐慌,老刑警劉巖钦铺,帶你破解...
    沈念sama閱讀 222,464評(píng)論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件订雾,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡矛洞,警方通過(guò)查閱死者的電腦和手機(jī)洼哎,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,033評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)沼本,“玉大人噩峦,你說(shuō)我怎么就攤上這事〕檎祝” “怎么了识补?”我有些...
    開(kāi)封第一講書(shū)人閱讀 169,078評(píng)論 0 362
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)辫红。 經(jīng)常有香客問(wèn)我凭涂,道長(zhǎng),這世上最難降的妖魔是什么厉熟? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 59,979評(píng)論 1 299
  • 正文 為了忘掉前任导盅,我火速辦了婚禮,結(jié)果婚禮上揍瑟,老公的妹妹穿的比我還像新娘白翻。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,001評(píng)論 6 398
  • 文/花漫 我一把揭開(kāi)白布滤馍。 她就那樣靜靜地躺著岛琼,像睡著了一般。 火紅的嫁衣襯著肌膚如雪巢株。 梳的紋絲不亂的頭發(fā)上槐瑞,一...
    開(kāi)封第一講書(shū)人閱讀 52,584評(píng)論 1 312
  • 那天,我揣著相機(jī)與錄音阁苞,去河邊找鬼困檩。 笑死,一個(gè)胖子當(dāng)著我的面吹牛那槽,可吹牛的內(nèi)容都是我干的悼沿。 我是一名探鬼主播,決...
    沈念sama閱讀 41,085評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼骚灸,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼糟趾!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起甚牲,我...
    開(kāi)封第一講書(shū)人閱讀 40,023評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤义郑,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后丈钙,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體非驮,經(jīng)...
    沈念sama閱讀 46,555評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,626評(píng)論 3 342
  • 正文 我和宋清朗相戀三年著恩,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了院尔。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,769評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡喉誊,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出纵顾,到底是詐尸還是另有隱情伍茄,我是刑警寧澤,帶...
    沈念sama閱讀 36,439評(píng)論 5 351
  • 正文 年R本政府宣布施逾,位于F島的核電站敷矫,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏汉额。R本人自食惡果不足惜曹仗,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,115評(píng)論 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望蠕搜。 院中可真熱鬧怎茫,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,601評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至祥山,卻和暖如春圃验,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背缝呕。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,702評(píng)論 1 274
  • 我被黑心中介騙來(lái)泰國(guó)打工澳窑, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人供常。 一個(gè)月前我還...
    沈念sama閱讀 49,191評(píng)論 3 378
  • 正文 我出身青樓照捡,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親话侧。 傳聞我的和親對(duì)象是個(gè)殘疾皇子栗精,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,781評(píng)論 2 361