첫 번째 활동에서 애플리케이션을 강제로 다시 시작
알 수없는 시작 애플리케이션이 제대로 종료되지 않아 홈 버튼과 앱 아이콘을 다시 표시 앱 내에서 다시 시작합니다. 첫 번째 활동에서 응용 프로그램을 강제로 다시 시작하고 싶습니다.
나는 이것이 onDestroy () 또는 onPause ()와 관련이 모르겠습니다하지만 무엇을 해야할지 결정합니다.
다음은 PackageManager를 사용하여 일반적인 방식으로 앱을 다시 시작하는 예입니다.
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
'답변'으로 솔루션은 작동하지만 나에게 중요한 문제가 있습니다. FLAG_ACTIVITY_CLEAR_TOP를 사용하면 이전 활동 스택이 onDestroy를 수신하기 전에 대상 활동이 onCreate가 호출됩니다. onDestroy에서 몇 가지 필요한 항목을 지우는 동안 작업해야했습니다.
이것은 나를 위해 일한 솔루션입니다.
public static void restart(Context context, int delay) {
if (delay == 0) {
delay = 1;
}
Log.e("", "restarting app");
Intent restartIntent = context.getPackageManager()
.getLaunchIntentForPackage(context.getPackageName() );
PendingIntent intent = PendingIntent.getActivity(
context, 0,
restartIntent, Intent.FLAG_ACTIVITY_CLEAR_TOP);
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
manager.set(AlarmManager.RTC, System.currentTimeMillis() + delay, intent);
System.exit(2);
}
아이디어는 조금 나중에 호출 될 AlarmManager를 통해 PendingIntent를 실행하여 오래된 활동 스택을 정리할 시간을 제공하는 것입니다.
항상 루트에서 시작하려는 루트 활동에서 android : clearTaskOnLaunch 를 true 로 설정하고 싶습니다 .
android:clearTaskOnLaunch="true"
android:launchMode="singleTask"
시작 클래스 (첫 번째 활동)의 매니페스트 파일 에서이 속성을 사용합니다.
FLAG_ACTIVITY_CLEAR_TOP가 필요한 작업을 수행합니까?
Intent i = new Intent(getBaseContext(), YourActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
FLAG_ACTIVITY_CLEAR_TOP
2.3.3을 지원해야 할 것입니다. 내 첫 번째 해결책은 다음과 달라집니다.
Intent intent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
intent.addFlags(Build.VERSION.SDK_INT >= 11 ? Intent.FLAG_ACTIVITY_CLEAR_TASK : Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);
이것은 거의 작동하지만 정답은 아닙니다.
기본 활동이 있으므로 모든 실행 활동을 닫는 킬 브로드 캐스트를 추가했습니다.
public abstract class BaseActivity extends AppCompatActivity {
private static final String ACTION_KILL = "BaseActivity.action.kill";
private static final IntentFilter FILTER_KILL;
static {
FILTER_KILL = new IntentFilter();
FILTER_KILL.addAction(ACTION_KILL);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerReceiver(killReceiver, FILTER_KILL);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(killReceiver);
}
private final BroadcastReceiver killReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
finish();
}
};
public void killApp(){
sendBroadcast(new Intent(ACTION_KILL));
}
}
내 모든 활동은이 수업에서 확장 확장
((BaseActivity)getActivity()).killApp();
startActivity(new Intent(getActivity(), StartActivity.class));
앱을 다시 시작합니다. genymotion v10, v16, v21 및 v22가 Nexus 5에서 테스트되었습니다.
편집 : 인 텐트를 보낼 때 파괴 된 경우 활동을 제거하지 않습니다. 나는 여전히 해결을 찾고 있습니다.
Marc의 대답은 내 주요 활동에 singleTop의 launchMode가있는 경우 제외하고는 훌륭하게 작동합니다. 이 인 텐트를 실행 한 다음 새 활동으로 이동하고 기기의 홈 버튼을 사용할 앱 아이콘에서 다시 시작하면 이전 활동이 백 스택에있는 기본의 새 인스턴스가 생성됩니다. .
이 질문 에 따르면 의도가 일치하지 않습니다. 를 보면 adb dumpsys activity
표준 Android 런처에서 패키지가 null 인 반면 Marc가 제안한대로 수행하면 의도 패키지가 내 패키지의 이름임을 알 수 있습니다. 이 차이로 인해 앱 아이콘을 다시 탭하고 기본 활동이 맨 위에 없을 때 일치하지 않고 새 인스턴스가 시작됩니다.
그러나 Kindle과 같은 다른 런처에서는 패키지 가 런처 인 텐트에 설정되어 있으므로 런처를 처리하는 일반적인 방법이 필요했습니다. 다음과 같은 정적 메서드를 추가했습니다.
static boolean mIsLaunchIntentPackageNull = true;
public static boolean isLaunchIntent(Intent i) {
if (Intent.ACTION_MAIN.equals(i.getAction()) && i.getCategories() != null
&& i.getCategories().contains(Intent.CATEGORY_LAUNCHER)) {
return true;
}
return false;
}
public static void handleLaunchIntent(Intent i) {
if (isLaunchIntent(i)) {
if (i.getPackage() != null) {
mIsLaunchIntentPackageNull = false;
}
else {
mIsLaunchIntentPackageNull = true;
}
}
}
다음과 같은 홈 사용합니다.
Intent intentHome = appContext.getPackageManager()
.getLaunchIntentForPackage( appContext.getPackageName());
intentHome.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// need to match launcher intent exactly to avoid duplicate activities in stack
if (mIsLaunchIntentPackageNull) {
intentHome.setPackage(null);
}
appContext.startActivity(intentHome);
그런 다음 매니페스트에 정의 된 주요 활동에 다음 줄을 추가했습니다.
public void onCreate(Bundle savedInstanceState) {
[class from above].handleLaunchIntent(getIntent());
이것은 킨들과 주요 활동에서 나를 위해 작동하며 주요 활동의 다른 인스턴스를 추가 할 수있는 앱을 내 전화 할 수 있습니다.
다음 코드는 나를 위해 작동하며 전체 앱을 완벽하게 다시 시작할 수 있습니다!
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);
애플리케이션 프로세스를 다시 시작하기 위해 Jake Wharton의 lib ProcessPhoenix 를 사용할 수 있습니다 .
이것은 나를 위해 일했습니다.
Intent mStartActivity = new Intent(ctx.getApplicationContext(), ActivityMain.class);
mStartActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mStartActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
mStartActivity.addFlags(0x8000); // equal to Intent.FLAG_ACTIVITY_CLEAR_TASK
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(ctx, mPendingIntentId, mStartActivity, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, mPendingIntent);
ActivityManager manager = (ActivityManager) ctx.getApplicationContext().getSystemService(ctx.getApplicationContext().ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> activityes = ((ActivityManager)manager).getRunningAppProcesses();
((Activity)ctx).moveTaskToBack(true);
manager.killBackgroundProcesses("com.yourpackagename");
System.exit(0);
열심히 생각하고 테스트 한 후 마침내 앱이 홈 버튼으로 남아있을 때 내 활동을 호출하여 다시 만드는 올바른 방법을 얻었습니다.
android:clearTaskOnLaunch
매니페스트에서
@Override
public void onRestart(){
onCreate();
}
그게 트릭입니다 ... (앱을 시작할 때마다 호출되는 onResume에 넣을 때보 다 낫습니다. 처음에도 두 번 표시됩니다)
참고 URL : https://stackoverflow.com/questions/2470870/force-application-to-restart-on-first-activity
'ProgramingTip' 카테고리의 다른 글
{% URL 사용 ??? (0) | 2020.11.06 |
---|---|
AngularJS에서 전화 및 신용 카드 번호 형식 지정 (0) | 2020.11.06 |
정확한 n 개의 요소가 집합의 모든 하위 집합을 어떻게 사용할 수 있습니까? (0) | 2020.11.06 |
긴 어깨의 10 자만 표시 하시겠습니까? (0) | 2020.11.06 |
Symfony2 기본 선택 필드 선택 설정 (0) | 2020.11.06 |