Android 앱을 프로그래밍적으로 "다시 시작"하려면 어떻게 해야 합니까?
첫째, 안드로이드에서 애플리케이션을 실제로 죽이거나 다시 시작해서는 안 된다는 것을 알고 있습니다.저의 사용 사례에서는 서버가 특정 정보를 클라이언트에게 전송하는 특정한 경우에 애플리케이션을 공장 재설정하려고 합니다.
사용자는 애플리케이션 인스턴스 하나가 있는 서버에서만 로그인할 수 있습니다(즉, 여러 장치는 허용되지 않음).다른 인스턴스에서 "로그인" 잠금이 발생하면 일관성을 유지하기 위해 해당 사용자의 다른 모든 인스턴스는 데이터를 삭제(공장에서 재설정)해야 합니다.
사용자가 앱을 삭제하고 다시 설치할 경우 다른 인스턴스 ID가 발생하여 더 이상 잠금을 해제할 수 없기 때문에 강제로 잠금을 해제할 수 있습니다.따라서 강제로 잠금 장치를 얻는 것이 가능합니다.
그 힘의 가능성 때문에, 우리는 항상 그것이 자물쇠를 가지고 있다는 구체적인 사례를 확인할 필요가 있습니다.이 작업은 서버에 요청할 때마다 (거의) 수행됩니다.서버가 "wrong-lock-id"를 보낼 수 있습니다.탐지되면 클라이언트 응용프로그램은 모든 내용을 삭제해야 합니다.
그것이 사용 사례였습니다.
는 는이 있습니다.Activity
로그인을 시작하는 AActivity
또는 앱의 메인Activity
공유 값에 따라 를 미리 설정합니다. L 를 시작한 후 L B만 실행되도록 를 닫습니다.L 또는 B를 시작한 후 L 또는 B만 실행되도록 자체를 닫습니다.따라서 사용자가 로그인한 경우에는 이미 B가 실행되고 있습니다.
B는 C를 시작합니다.는 C를콜스startService
를 위해IntentService
이 :D가 됩니다. 그러면 다음과 같은 스택이 생성됩니다.
(A) > B > C > D
이벤트는 D의 onHandleIntent 메서드에서 ResultReceiver R로 전송됩니다.
R은 사용자에게 응용프로그램을 공장에서 재설정하도록 선택할 수 있는 대화상자를 제공하여 해당 이벤트를 처리합니다(데이터베이스 삭제, sharedPrefs 등).
공장 재설정 후 애플리케이션을 다시 시작하고(모든 활동을 종료하려면) A만 다시 시작하고 로그인을 시작합니다.Activity
랜드 자체 마감:
(A) > L
클릭 시 Dialog's on Click 메서드는 다음과 같습니다.
@Override
public void onClick(DialogInterface dialog, int which) {
// Will call onCancelListener
MyApplication.factoryReset(); // (Deletes the database, clears sharedPrefs, etc.)
Intent i = new Intent(MyApp.getContext(), A.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MyApp.getContext().startActivity(i);
}
그리고 그것은.MyApp
클래스:
public class MyApp extends Application {
private static Context context;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
public static Context getContext() {
return context;
}
public static void factoryReset() {
// ...
}
}
문제는 만약 제가 그를 사용한다면.FLAG_ACTIVITY_NEW_TASK
활동 B와 C는 여전히 실행 중입니다.로그인에서 뒤로 버튼을 누르면Activity
C가 보이는데 홈 화면으로 다시 돌아가고 싶습니다.
설정하지 않으면FLAG_ACTIVITY_NEW_TASK
오류가 발생합니다.
07-07 12:27:12.272: ERROR/AndroidRuntime(9512): android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
활동'을 사용할 수 없습니다.Context
, 그 이유는ServiceIntent
D는 또한 에 의해 시작되는 백그라운드 작업에서 호출될 수 있습니다.AlarmManager
.
그렇다면 활동 스택이 (A) > L이 되는 것을 어떻게 해결할 수 있을까요?
나중에 시작 활동을 시작하도록 설정한 후 응용 프로그램을 닫을 수 있습니다.
Intent mStartActivity = new Intent(context, StartActivity.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(context, mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);
간단히 다음과 같은 전화를 걸 수:
public static void triggerRebirth(Context context, Intent nextIntent) {
Intent intent = new Intent(context, YourClass.class);
intent.addFlags(FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(KEY_RESTART_INTENT, nextIntent);
context.startActivity(intent);
if (context instanceof Activity) {
((Activity) context).finish();
}
Runtime.getRuntime().exit(0);
}
대안으로:
여기 @Oleg Koshkin 답변의 약간 개선된 버전이 있습니다.
현재 프로세스의 킬을 포함하여 활동을 다시 시작하려면 코드에 따라 시도합니다.도우미 클래스 또는 필요한 곳에 배치합니다.
public static void doRestart(Context c) {
try {
//check if the context is given
if (c != null) {
//fetch the packagemanager so we can get the default launch activity
// (you can replace this intent with any other activity if you want
PackageManager pm = c.getPackageManager();
//check if we got the PackageManager
if (pm != null) {
//create the intent with the default start activity for your application
Intent mStartActivity = pm.getLaunchIntentForPackage(
c.getPackageName()
);
if (mStartActivity != null) {
mStartActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//create a pending intent so the application is restarted after System.exit(0) was called.
// We use an AlarmManager to call this intent in 100ms
int mPendingIntentId = 223344;
PendingIntent mPendingIntent = PendingIntent
.getActivity(c, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) c.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
//kill the application
System.exit(0);
} else {
Log.e(TAG, "Was not able to restart application, mStartActivity null");
}
} else {
Log.e(TAG, "Was not able to restart application, PM null");
}
} else {
Log.e(TAG, "Was not able to restart application, Context null");
}
} catch (Exception ex) {
Log.e(TAG, "Was not able to restart application");
}
}
이렇게 하면 jni 클래스와 모든 정적 인스턴스도 다시 초기화됩니다.
Ilya_Gazman 답변을 새로운 API를 사용하기 위해 약간 수정하였습니다(IntentCompat는 API 26부터 사용하지 않음).Runtime.getRuntime().exit(0)이 System.exit(0)보다 나은 것 같습니다.
public static void triggerRebirth(Context context) {
PackageManager packageManager = context.getPackageManager();
Intent intent = packageManager.getLaunchIntentForPackage(context.getPackageName());
ComponentName componentName = intent.getComponent();
Intent mainIntent = Intent.makeRestartActivityTask(componentName);
context.startActivity(mainIntent);
Runtime.getRuntime().exit(0);
}
Jake Warton은 최근에 그의 프로세스를 출판하였습니다.피닉스 도서관, 믿을 수 있는 방법으로 이것을 합니다.기본적으로 전화만 걸면 됩니다.
ProcessPhoenix.triggerRebirth(context);
라이브러리가 호출 작업을 자동으로 종료하고 응용 프로그램 프로세스를 종료한 후 기본 응용 프로그램 작업을 다시 시작합니다.
IntentCompat.makeMainSelector 활동 - 2020년 11월 11일 마지막 테스트
런처 활동으로 앱이 복원되고 이전 프로세스가 삭제됩니다.
Api 15부터 작동합니다.
public static void restart(Context context){
Intent mainIntent = IntentCompat.makeMainSelectorActivity(Intent.ACTION_MAIN, Intent.CATEGORY_LAUNCHER);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.getApplicationContext().startActivity(mainIntent);
System.exit(0);
}
제 솔루션은 프로세스/애플리케이션을 다시 시작하지 않습니다.앱이 홈 액티비티를 "재시작"(그리고 다른 모든 액티비티를 종료)하도록 할 뿐입니다.사용자가 보기에는 다시 시작하는 것처럼 보이지만 프로세스는 동일합니다.어떤 경우에는 사람들이 이 효과를 얻고 싶어한다고 생각하기 때문에 참고로 여기에 남겨 둡니다.
public void restart(){
Intent intent = new Intent(this, YourHomeActivity.class);
this.startActivity(intent);
this.finishAffinity();
}
"당신의 앱이 예기치 않게 닫혔습니다"를 트리거하지 않은 유일한 코드는 다음과 같습니다.외부 라이브러리를 필요로 하지 않는 비감각 코드이기도 합니다.그리고 타이머도 필요 없습니다.
public static void triggerRebirth(Context context, Class myClass) {
Intent intent = new Intent(context, myClass);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intent);
Runtime.getRuntime().exit(0);
}
이것이 API 29 이상에서 작동하는 것을 발견했습니다 - 앱이 실행되지 않을 때 사용자가 실행한 것처럼 앱을 죽이고 다시 시작하기 위한 목적입니다.
public void restartApplication(final @NonNull Activity activity) {
// Systems at 29/Q and later don't allow relaunch, but System.exit(0) on
// all supported systems will relaunch ... but by killing the process, then
// restarting the process with the back stack intact. We must make sure that
// the launch activity is the only thing in the back stack before exiting.
final PackageManager pm = activity.getPackageManager();
final Intent intent = pm.getLaunchIntentForPackage(activity.getPackageName());
activity.finishAffinity(); // Finishes all activities.
activity.startActivity(intent); // Start the launch activity
System.exit(0); // System finishes and automatically relaunches us.
}
이는 앱의 런처 활동에 다음과 같은 기능이 있을 때 수행되었습니다.
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
DEFAULT 카테고리가 필요하다는 댓글을 본 적은 있지만, 그런 경우는 발견하지 못했습니다.제 앱의 Application 개체가 다시 생성되는 것을 확인했기 때문에 프로세스가 실제로 종료되고 다시 시작된 것으로 생각합니다.
사용하는 유일한 목적은 사용자가 Firebase Crashlytics에 대한 충돌 보고를 활성화 또는 비활성화한 후 앱을 다시 시작하는 것입니다.그들의 문서에 따르면, 그 변경 사항이 적용되려면 앱을 다시 시작(프로세스를 삭제하고 다시 생성)해야 합니다.
정말 좋은 속임수가 있습니다.내 문제는 정말 오래된 C++ jni 라이브러리에서 리소스가 유출되었다는 것입니다.어느 순간 작동이 멈췄습니다.사용자가 앱을 종료하고 다시 실행하려고 했지만 작업을 완료하는 것은 프로세스를 완료(또는 삭제)하는 것과 같지 않기 때문에 아무 결과도 없었습니다.(그런데 사용자는 실행 중인 응용프로그램 목록으로 이동하여 해당 응용프로그램을 중지할 수 있습니다. 이렇게 하면 효과는 있지만, 사용자는 응용프로그램을 종료하는 방법을 모릅니다.)
이 기능의 효과를 관찰하려면 다음을 추가합니다.static
당신의 활동에 변수를 주고 각각 그것을 증가시킵니다. 예를 들어 버튼을 누르세요.응용프로그램 활동을 종료한 후 응용프로그램을 다시 호출하면 이 정적 변수는 해당 값을 유지합니다.(애플리케이션이 실제로 종료된 경우에는 변수에 초기값이 할당됩니다.)
(그리고 버그를 고치고 싶지 않은 이유에 대해 언급해야 합니다.그 도서관은 수십 년 전에 쓰여졌고 그 이후로 자료들이 유출되었습니다.경영진은 항상 효과가 있었다고 믿고 있습니다.해결책 대신 해결책을 제공하는 데 드는 비용...제 생각에는, 당신이 이해할 수 있을 것 같습니다.)
이제 jni 공유(일명 다이나믹, .so) 라이브러리를 초기 상태로 재설정하려면 어떻게 해야 합니까?새로운 프로세스로 애플리케이션을 다시 시작하기로 선택했습니다.
System.exit()은 현재 활동을 종료하고 Android는 한 가지 활동을 덜 하면서 응용프로그램을 다시 만듭니다.
암호는 다음과 같습니다.
/** This activity shows nothing; instead, it restarts the android process */
public class MagicAppRestart extends Activity {
// Do not forget to add it to AndroidManifest.xml
// <activity android:name="your.package.name.MagicAppRestart"/>
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.exit(0);
}
public static void doRestart(Activity anyActivity) {
anyActivity.startActivity(new Intent(anyActivity.getApplicationContext(), MagicAppRestart.class));
}
}
호출 작업은 코드를 실행할 뿐입니다.MagicAppRestart.doRestart(this);
, 호출 활동의onPause()
실행된 후 프로세스가 다시 생성됩니다.AndroidManifest.xml에서 이 활동에 대해 언급하는 것을 잊지 마십시오.
이 방법의 장점은 지연이 없다는 것입니다.
업데이트: Android 2.x에서는 작동했지만 Android 4에서는 뭔가 바뀌었습니다.
네, 앱 리팩터링을 했고 자동으로 A를 끝내지는 못할 것 같습니다.나는 항상 이것을 실행하고 그것을 끝까지 마칩니다.onActivityResult
이벤트. 이런 식으로 나는 사용할 수 있습니다.FLAG_ACTIVITY_CLEAR_TOP
+FLAG_ACTIVITY_NEW_TASK
원하는 것을 얻을 수 있는 플래그:
public class A extends Activity {
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
finish();
}
protected void onResume() {
super.onResume();
// ...
if (loggedIn) {
startActivityForResult(new Intent(this, MainActivity.class), 0);
} else {
startActivityForResult(new Intent(this, LoginActivity.class), 0);
}
}
}
그리고.ResultReceiver
@Override
public void onClick(DialogInterface dialog, int which) {
MyApp.factoryReset();
Intent i = new Intent(MyApp.getContext(), A.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MyApp.getContext().startActivity(i);
}
어쨌든 고맙습니다!
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
앱을 완전히 다시 시작하는 가장 좋은 방법은 앱을 다시 시작하는 것이지, 단순히 다음과 같은 활동으로 이동하는 것은 아닙니다.FLAG_ACTIVITY_CLEAR_TOP
그리고.FLAG_ACTIVITY_NEW_TASK
. 그래서 나의 해결책은 당신의 앱에서 또는 다른 앱에서 하는 것이고, 유일한 조건은 앱 패키지 이름을 아는 것입니다(예: 'com.example.myProject').
public static void forceRunApp(Context context, String packageApp){
Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(packageApp);
launchIntent.setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(launchIntent);
}
appB에서 appA를 다시 시작하거나 appA를 시작하는 예:
forceRunApp(mContext, "com.example.myProject.appA");
앱이 실행 중인지 확인할 수 있습니다.
public static boolean isAppRunning(Context context, String packageApp){
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();
for (int i = 0; i < procInfos.size(); i++) {
if (procInfos.get(i).processName.equals(packageApp)) {
return true;
}
}
return false;
}
참고: 이 대답이 주제에서 좀 벗어난다는 것은 알지만, 누군가에게는 정말 도움이 될 수 있습니다.
지금도 일하고 있습니다.
public void resetApplication() {
Intent resetApplicationIntent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
if (resetApplicationIntent != null) {
resetApplicationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
}
context.startActivity(resetApplicationIntent);
((Activity) context).overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
애플리케이션을 다시 시작하는 가장 좋은 방법은 다음을 사용하는 것입니다.finishAffinity();
부터,finishAffinity();
젤리빈 버전에서만 사용할 수 있기 때문에 사용할 수 있습니다.ActivityCompat.finishAffinity(YourCurrentActivity.this);
하위 버전의 경우.
그럼 사용.Intent
첫번째 활동을 시작하는 코드는 다음과 같습니다.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
finishAffinity();
Intent intent = new Intent(getApplicationContext(), YourFirstActivity.class);
startActivity(intent);
} else {
ActivityCompat.finishAffinity(YourCurrentActivity.this);
Intent intent = new Intent(getApplicationContext(), YourFirstActivity.class);
startActivity(intent);
}
도움이 되길 바랍니다.
사용해보기FLAG_ACTIVITY_CLEAR_TASK
이 답변의 Kotlin 버전:
val intent = Intent(this, YourActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
startActivity(intent)
Runtime.getRuntime().exit(0)
사용가능startInstrumentation
의 방법Activity
. 구현이 비어 있어야 합니다.Instrumentation
그리고 명백한 것입니다.그런 다음 이 메서드를 호출하여 앱을 다시 시작할 수 있습니다.다음과 같은 경우:
try {
InstrumentationInfo info = getPackageManager().queryInstrumentation(getPackageName(), 0).get(0);
ComponentName component = new ComponentName(this, Class.forName(info.name));
startInstrumentation(component, null, null);
} catch (Throwable e) {
new RuntimeException("Failed restart with Instrumentation", e);
}
Instrumentation 클래스 이름을 동적으로 얻지만 하드코드화할 수 있습니다.다음과 같은 것들이 있습니다.
try {
startInstrumentation(new ComponentName(this, RebootInstrumentation.class), null, null);
} catch (Throwable e) {
new RuntimeException("Failed restart with Instrumentation", e);
}
불러startInstrumentation
앱을 다시 로드합니다.이 방법에 대한 설명을 읽습니다.하지만 킬 앱처럼 행동한다면 안전하지 않을 수 있습니다.
현재 작업 중인 애플리케이션은 사용자에게 표시할 프래그먼트를 선택할 수 있는 기회를 제공해야 합니다(프래그먼트는 런타임에 동적으로 변경됩니다).저에게 가장 좋은 해결책은 애플리케이션을 완전히 다시 시작하는 것이었습니다.
그래서 저는 많은 해결책을 시도했지만, 그 중 어떤 것도 저에게 효과가 없었습니다. 하지만 이것은:
final Intent mStartActivity = new Intent(SettingsActivity.this, Splash.class);
final int mPendingIntentId = 123456;
final PendingIntent mPendingIntent = PendingIntent.getActivity(SettingsActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
final AlarmManager mgr = (AlarmManager) SettingsActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
this.finishAffinity(); //notice here
Runtime.getRuntime().exit(0); //notice here
그것이 다른 사람에게 도움이 되기를 바랍니다!
용도:
navigateUpTo(new Intent(this, MainActivity.class));
API 레벨 16(4.1)부터 작동한다고 생각합니다.
FLAG_ACTIVE_CLEAR_로 초기화면을 직접 시작합니다.TASK 및 FLAG_ACTIVE_NEW_TASK.
fun triggerRestart(context: Activity) {
val intent = Intent(context, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
if (context is Activity) {
(context as Activity).finish()
}
Runtime.getRuntime().exit(0)
}
이쪽으로 갑니다.
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(
getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
이 코드는 안드로이드 8-13 테스트를 통과했습니다.
public void restartApp() {
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName() );
startActivity(Intent.makeRestartActivityTask(i.getComponent()));
Runtime.getRuntime().exit(0);
}
종료를 지연시키기 위해 핸들러를 추가해야 했습니다.
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 200, mPendingIntent);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
Runtime.getRuntime().exit(0);
}
}, 100);
시도해 보십시오.
Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
프로세스 피닉스 라이브러리와 함께.다시 시작하려는 활동의 이름은 "A"입니다.
자바맛
// Java
public void restart(){
ProcessPhoenix.triggerRebirth(context);
}
코틀린맛
// kotlin
fun restart() {
ProcessPhoenix.triggerRebirth(context)
}
지연 재시작 적용
startDelay시작 지연(밀리초)
public static void reStartApp(Context context, long startDelay) {
//Obtain the startup Intent of the application with the package name of the application
Intent intent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
PendingIntent restartIntent = PendingIntent.getActivity(context.getApplicationContext(), -1, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (mgr != null) {
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + startDelay, restartIntent);
}
}
val i = baseContext.packageManager.getLaunchIntentForPackage(baseContext.packageName)
i!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
startActivity(i)
finish()
Mikepenz의 Alternative Answer는 제 경우에 약간의 변화가 필요했습니다.https://stackoverflow.com/a/22345538/12021422 내가 수정할 수 있는 Mikepenz의 답변에 대한 Major Credits.
여기 저에게 도움이 된 플러그 앤 플레이 정적 기능이 있습니다.
응용프로그램 컨텍스트만 통과하면 이 기능이 재시작을 처리합니다.
public static void doRestart(Context c) {
try {
// check if the context is given
if (c != null) {
// fetch the package manager so we can get the default launch activity
// (you can replace this intent with any other activity if you want
PackageManager pm = c.getPackageManager();
// check if we got the PackageManager
if (pm != null) {
// create the intent with the default start activity for your application
Intent mStartActivity = pm.getLaunchIntentForPackage(c.getPackageName());
if (mStartActivity != null) {
mStartActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
c.getApplicationContext().startActivity(mStartActivity);
// kill the application
System.exit(0);
}
}
}
} catch (Exception e) {
e.printStackTrace();
Log.e("restart", "Could not Restart");
}
}
주 활동 호출 다시 시작활동 방법:
public static void restartActivity(Activity mActivity) {
Intent mIntent = mActivity.getIntent();
mActivity.finish();
mActivity.startActivity(mIntent);
}
언급URL : https://stackoverflow.com/questions/6609414/how-do-i-programmatically-restart-an-android-app
'sourcecode' 카테고리의 다른 글
Postgre와 동치Oracle 9i의 SQL array() / array_to_string() 함수 (0) | 2023.10.30 |
---|---|
'SELECT'를 사용하여 함수 호출 (0) | 2023.10.25 |
자바스크립트에서 동적 요소에 이벤트 첨부 (0) | 2023.10.25 |
바인딩 값이 변경될 때 AngularJS 트리거 ng-animate (0) | 2023.10.25 |
PowerShell 스크립트에서 C# .cs 파일 실행 (0) | 2023.10.25 |