知乎专栏 |
package cn.netkiller.album; import android.os.Bundle; import android.view.View; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class HotelActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hotel); TextView hotelClose = (TextView) findViewById(R.id.hotelClose); hotelClose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } }
AndroidManifest.xml 中 activity 添加 android:launchMode="singleTask"
<activity android:name=".MainActivity" android:exported="true" android:launchMode="singleTask"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.HOME" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
MainActivity 中添加 onNewIntent(Intent intent)
@Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); if (intent != null) { boolean isExit = intent.getBooleanExtra("QUIT", false); if (isExit) { this.finish(); } } }
调用 quit 方法即可正常退出主程序
public void quit(View v) { Intent intent = new Intent(this, MainActivity.class); intent.putExtra("QUIT", true); startActivity(intent); }