每次用户启动应用时,我都需要检测第一次调用活动:
...所以只有当应用程序被关闭(或被杀死)然后再次启动时,必须调用“做某事”。
答案 0 :(得分:16)
我通常在活动中使用static boolean
变量作为标志。然后,在onCreate()
内,测试变量;如果它是true
,那就做点什么并翻转旗帜。
public class MainActivity extends Activity {
private static boolean RUN_ONCE = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
runOnce();
}
private void runOnce() {
if (RUN_ONCE) {
RUN_ONCE = false;
// do something
}
}
...
}
答案 1 :(得分:0)
使用此代码
private static boolean isApplicationBroughtToBackground(final Activity activity) {
ActivityManager activityManager = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);
List tasks = null;
try {
tasks = activityManager.getRunningTasks(1);
} catch (SecurityException e) {
Log.e(TAG, "Missing required permission: \"android.permission.GET_TASKS\".", e);
return false;
}
if (tasks != null && !tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
try {
PackageInfo pi = activity.getPackageManager().getPackageInfo(activity.getPackageName(), PackageManager.GET_ACTIVITIES);
for (ActivityInfo activityInfo : pi.activities) {
if(topActivity.getClassName().equals(activityInfo.name)) {
return false;
}
}
} catch( PackageManager.NameNotFoundException e) {
Log.e(TAG, "Package name not found: " + activity.getPackageName());
return false; // Never happens.
}
}
return true;
}
答案 2 :(得分:0)
从其他活动调用时,会通过意图传递一个布尔额外值。并在开始时检查这个意图
@Override
protected void onStart() {
super.onStart();
boolean firstTime= getIntent().getBooleanExtra("firstTime", true);
if(firstTime)
{
//do something
}
else
{
//do something
}
答案 3 :(得分:-3)
使用sqlite
create table first (f INTEGER DEFAULT 0)
public int getFirst(){ codes... }
public void setFirst(){ codes... }
int x = db.getFirst();
if(x == 0){
db.setFirst(); //update f column to 1
DO SOMETHING
}