0

我正在导航 Activity 2,当我按下后退按钮时,它应该退出或完成应用程序而不显示主要活动。我正在使用 ViewPager(Activity2),backpress如果我只在ViewPager的第一页中导航,则代码正在运行,当我导航其他页面时,退出或完成应用程序的代码不起作用并显示 mainActivity。

主要活动

Intent myIntent = new Intent(MainActivity.this, Activity2.class);

活动2

@Override
public void onBackPressed() {
      super.onBackPressed();
    this.finish();
    android.os.Process.killProcess(android.os.Process.myPid());
    System.exit(0);
    getParent().finish();
    Activity a1 = (Activity)this.getBaseContext();

    if(this.getParent()!=null){
        Activity a = (Activity)this.getParent().getApplicationContext();
        a.finish();
    }

    Log.i("Backpressed", "pressed");

}
4

5 回答 5

2

这会奏效,

    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
于 2013-10-17T10:28:42.440 回答
0

你确定在“System.exit(0);”之后 被调用,其余的代码会被调用吗?我记得,不会。它应该可以按您的意愿工作。

无论如何,请不要使用任何这些方法。System.exit 在某些情况下可能对您来说就足够了,但实际上它会杀死应用程序的所有线程并被认为是一种肮脏的方法。

相反,从 Activity 1 调用 startActivityForResult 到 Activity 2 。然后,在活动 2 中调用完成并将结果设置为某个值,并在活动 1 中检查结果是否是退出应用程序,如果是,也在那里调用 finish()。

于 2013-10-17T10:18:35.187 回答
0

尝试android:noHistory="true"像这样将其添加到您的清单中

<activity
            android:noHistory="true"
            android:name="com.example.activities.MainPageActivity"
            android:configChanges="orientation|keyboardHidden|screenSize|screenLayout"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.NoTitleBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
于 2013-10-17T10:18:36.837 回答
0

添加finish();您的 MainActivity。
您还可以在 MainActivity 下的 Manifest 中添加以下行

        android:excludeFromRecents="true"
        android:finishOnTaskLaunch="true"
        android:noHistory="true"
于 2013-10-17T10:21:00.120 回答
0

如果您正在使用杀死进程..然后在背压上杀死所有进程..使用for循环获取所有进程的pid..并杀死它们..像这样

ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> list = am
            .getRunningAppProcesses();


    if (list != null) {
        for (int i = 0; i < list.size(); ++i) {
            String processid = list.get(i).processName;


            String packageName = mContext.getPackageName();
            if (processid.contains(packageName + ":homescreen")) {
                //here homescreen is the name you given in manifest for android:process

                Process.killProcess(list.get(i).pid);

            } 

并在每个活动的清单中添加 android:process=":anyname" 像这样

android:process=":homescreen"

于 2013-10-17T11:43:22.623 回答