4

我想要檢測用戶選擇了什麼應用程序後,我會向他顯示一個createChooser()對話框。所以,我創建了我BroadcastReceiver子是這樣的:執行createChooser(上下文,意圖,IntentSender)後,不會調用BroadcastReceiver

import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.util.Log; 

public class ShareBroadcastReceiver extends BroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     Log.d("INFORMATION", "Received intent after selection: "+intent.getExtras().toString()); 
    } 
} 

而且我已經加入我接收到我的Android 清單文件:

<application> 
... 
... 
... 
    <receiver android:name=".helpers.ShareBroadcastReceiver" android:exported="true"/> 
</application> 

這裏是調用createChooser代碼對話框:

Intent sendIntent = new Intent(android.content.Intent.ACTION_SEND); 
sendIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
sendIntent.setType("image/png"); 

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) { 
    Log.d("INFORMATION", "The current android version allow us to know what app is chosen by the user."); 

    Intent receiverIntent = new Intent(this,ShareBroadcastReceiver.class); 
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, receiverIntent, PendingIntent.FLAG_CANCEL_CURRENT); 
    sendIntent = Intent.createChooser(sendIntent,"Share via...", pendingIntent.getIntentSender()); 
} 
startActivity(sendIntent); 

即使這是明確的PendingIntent,因爲我直接使用ShareBroadcastReceiver類名,沒有任何intent-filter,我的廣播接收器在用戶點擊選擇器對話框後沒有正確回調,我做錯了什麼?

回答

3

代碼中的所有內容都是正常的。你只需要改變一個行onReceive方法在ShareBroadcastReceiver趕上你的意圖的「EXTRA_CHOSEN_COMPONENT」鍵:

Log.d("INFORMATION", "Received intent after selection: "+intent.getExtras().get(Intent.EXTRA_CHOSEN_COMPONENT));

在你的日誌,你會看到這樣的事情(在我的情況下,我選擇了谷歌保持):

ComponentInfo{com.google.android.keep/com.google.android.keep.activities.ShareReceiverActivity} 
相關問題