我需要知道一种通用的方式来区分来自启动程序的活动调用和来自我的应用程序内的另一个活动的调用,或活动上的BACK堆栈区分活动从主屏幕或从另一个活动启动从应用程序
有人吗?现在这是窃听我相当长一段时间,我需要把它放到休息...
在此先感谢 JQCorreia
我需要知道一种通用的方式来区分来自启动程序的活动调用和来自我的应用程序内的另一个活动的调用,或活动上的BACK堆栈区分活动从主屏幕或从另一个活动启动从应用程序
有人吗?现在这是窃听我相当长一段时间,我需要把它放到休息...
在此先感谢 JQCorreia
在你活动的OnCreate,叫getIntent()
。如果活动是从启动器(主屏幕)启动的,getAction()
的值将是android.intent.action.MAIN
,并且getCategories()
将返回一个包含android.intent.category.LAUNCHER类别的集合。 如果活动从别处开始,则这些值可能是null
。
除了@ advantej的回答,您可以将每个开始通话扩展到该活动,并为起始意向添加一个附加内容(例如intent.putExtra("caller", this.getClass().getSimpleName()
);
在活动的onCreate
方法中,您可以检查@advantej的建议。
如果启动程序不是主屏幕图标,则您可以进一步检查intent.hasExtra("caller")
是否返回true,如果是,那么它是什么。
2例中的onRestart();称为,1.当活动来自后台,2.当用户通过后退按钮到达活动,然后样本解决方案: 使用onBackPressed()函数来设置一个标志..所以你知道onRestart叫做后退按钮的依据。 。) 在onRestart(检查标志,并重置和....
基于advantej's answer,这里是一个完整的例子也隐藏UP按钮,如果活动是从一个启动器图标启动:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sell);
/**
* If this activity was started from launcher icon, then don't show the Up button in the action bar.
*/
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
Intent intent = getIntent();
Set<String> intentCategories = intent.getCategories();
boolean wasActivityStartedFromLauncherIcon = Intent.ACTION_MAIN.equals(intent.getAction()) && intentCategories != null && intentCategories.contains(Intent.CATEGORY_LAUNCHER);
boolean showUpButton = !wasActivityStartedFromLauncherIcon;
actionBar.setDisplayHomeAsUpEnabled(showUpButton);
}
}
这里有便利的方法,所以你不需要自己写:
protected boolean isStartedByLauncher() {
if (getIntent() == null) {
return false;
}
boolean isActionMain = Intent.ACTION_MAIN.equals(getIntent().getAction());
Set<String> categories = getIntent().getCategories();
boolean isCategoryLauncher = categories != null && categories.contains(Intent.CATEGORY_LAUNCHER);
return isActionMain && isCategoryLauncher;
}
如果你有这个函数需要一个Intent而不是调用getIntent,它就成为一个可移植的util方法:) – 2017-12-23 00:51:17
你可以从意向标志找出它。
第1步:
Intent intent = getIntent();
int flag = intent.getFlag();
第2步:
if flag = Intent.FLAG_ACTIVITY_NEW_TASK
launch from other app or activities
else
launch from home page
我不知道,但你想看看'getIntent()',看看你看到一些差异?我想你应该会在行动中看到一些不同...... – WarrenFaith 2011-04-12 15:40:41