我正在寻找有关我的应用程序打开位置的统计信息。我开始看这个例子:
利用Activity中的方法getReferrer()
。现在我在调试我的应用程序并从Google搜索应用程序打开结果时看到的是,此方法始终为我提供结果的http链接,但它从未向我提供用户使用的应用程序是Google搜索的信息。我知道这些信息会传递给应用程序,因为如果我检查Activity,我可以看到mReferrer
属性包含调用者应用程序的包名,正是我所寻找的!但是,无法访问所述属性,并且唯一使用它的地方是方法getReferrer()
。现在看一下这个方法,这就是Activity里面的内容:
/**
* Return information about who launched this activity. If the launching Intent
* contains an {@link android.content.Intent#EXTRA_REFERRER Intent.EXTRA_REFERRER},
* that will be returned as-is; otherwise, if known, an
* {@link Intent#URI_ANDROID_APP_SCHEME android-app:} referrer URI containing the
* package name that started the Intent will be returned. This may return null if no
* referrer can be identified -- it is neither explicitly specified, nor is it known which
* application package was involved.
*
* <p>If called while inside the handling of {@link #onNewIntent}, this function will
* return the referrer that submitted that new intent to the activity. Otherwise, it
* always returns the referrer of the original Intent.</p>
*
* <p>Note that this is <em>not</em> a security feature -- you can not trust the
* referrer information, applications can spoof it.</p>
*/
@Nullable
public Uri getReferrer() {
Intent intent = getIntent();
try {
Uri referrer = intent.getParcelableExtra(Intent.EXTRA_REFERRER);
if (referrer != null) {
return referrer;
}
String referrerName = intent.getStringExtra(Intent.EXTRA_REFERRER_NAME);
if (referrerName != null) {
return Uri.parse(referrerName);
}
} catch (BadParcelableException e) {
Log.w(TAG, "Cannot read referrer from intent;"
+ " intent extras contain unknown custom Parcelable objects");
}
if (mReferrer != null) {
return new Uri.Builder().scheme("android-app").authority(mReferrer).build();
}
return null;
}
如您所见,Intent.EXTRA_REFERRER
的优先级始终存在,因此永远不会使用mReferrer的最后一部分。
有没有办法可以检索来电者包名?
答案 0 :(得分:1)
嗯,刚想办法自己做。在这里分享,以防任何人进行相同的操作。实质上,看看getReferrer()
如何工作,这将得到包名:
// Backup referrer info and remove it temporarily.
Uri extraReferrerBackup = getIntent().getParcelableExtra(Intent.EXTRA_REFERRER);
String extraReferrerNameBackup = getIntent().getStringExtra(Intent.EXTRA_REFERRER_NAME);
getIntent().removeExtra(Intent.EXTRA_REFERRER);
getIntent().removeExtra(Intent.EXTRA_REFERRER_NAME);
// Get the app referrer.
Uri referrer = getReferrer();
// Restore previous http referrer info.
getIntent().putExtra(Intent.EXTRA_REFERRER, extraReferrerBackup);
getIntent().putExtra(Intent.EXTRA_REFERRER_NAME, extraReferrerNameBackup);