Android開發——通過廣播啟動另一個應用的Activity


需求:現在有應用A和應用B,我需要在A應用中啟動B應用中的某個Activity

實現:A應用中的Activity發送廣播,關鍵代碼如下:

       String broadcastIntent = "com.example.android.notepad.NotesList";//自己自定義
       Intent intent = new Intent(broadcastIntent);
       this.sendBroadcast(intent);

B應用中需要一個BroadcastReceiver來接收廣播,取名TestReceiver繼承BroadcastReceiver重寫onReceive方法啟動一個activity,關鍵代碼如下:   

if(intent.getAction().equals("com.example.android.notepad.NotesList")){
        Intent noteList = new Intent(context,NotesList.class);
        noteList.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(noteList);
}

到這代碼就完成了,當然在AndroidManifest.xml中要對TestReceiver進行注冊,代碼如下:

     <receiver android:name="TestReceiver">
             <intent-filter>
                  <action android:name="com.example.android.notepad.NotesList"/>
            </intent-filter>
    </receiver>

這樣就完成了通過廣播啟動另一個應用Activity。

注意問題:Context中有一個startActivity方法,Activity繼承自Context,重載了startActivity方法。如果使用 Activity的startActivity方法,不會有任何限制,而如果使用Context的startActivity方法的話,就需要開啟一個新的task,解決辦法是,加一個flag,也就是這句noteList.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);的作用。如果不添加這句,就會報android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity,Caused by: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM