IT TIP

Android : '강제 종료'후 애플리케이션을 자동으로 다시 시작하는 방법은 무엇입니까?

itqueen 2020. 10. 29. 20:17
반응형

Android : '강제 종료'후 애플리케이션을 자동으로 다시 시작하는 방법은 무엇입니까?


Android 애플리케이션에서 예외를 올바르게 얻지 못하면 일반적으로 "강제 종료"오류가 발생합니다.

응용 프로그램이 강제 종료 된 경우 어떻게 자동으로 다시 시작할 수 있습니까?

이를 위해 사용되는 특정 권한이 있습니까?


이를 수행하려면 다음 두 가지를 수행해야합니다.

  1. 응용 프로그램 충돌의 표준 방식 인 "강제 종료"를 피하십시오.
  2. 어쨌든 충돌이 발생하면 다시 시작 메커니즘을 설정하십시오.

이를 수행하는 방법은 아래를 참조하십시오.

  1. 전화 Thread.setDefaultUncaughtExceptionHandler()케이스하는 모든 캐치되지 않는 예외 잡기 위해 uncaughtException()메소드가 호출됩니다. "강제 종료"가 나타나지 않고 응용 프로그램이 응답하지 않는 것은 좋지 않습니다. 응용 프로그램이 충돌했을 때 다시 시작하려면 다음을 수행해야합니다.

  2. 에서 onCreate방법, 당신의 주요 활동에 초기화 PendingIntent회원 :

    Intent intent = PendingIntent.getActivity(
        YourApplication.getInstance().getBaseContext(),
        0,
        new Intent(getIntent()),
        getIntent().getFlags());
    

그런 다음 uncaughtException()방법에 다음을 입력하십시오 .

AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 2000, intent);
System.exit(2);

을 (를) 호출해야합니다 System.exit(). 그렇지 않으면 작동하지 않습니다. 이렇게하면 2 초 후에 애플리케이션이 다시 시작됩니다.

결국 응용 프로그램이 충돌했다는 의도에 플래그를 설정할 수 있으며 onCreate()방법 에서 "죄송합니다. 응용 프로그램이 충돌했습니다. 다시는 안하겠습니다. :)"라는 대화 상자를 표시 할 수 있습니다.


요령은 애초에 강제 종료를하지 않는 것입니다.

메서드 를 사용 하면Thread.setDefaultUncaughtExceptionHandler() 응용 프로그램을 강제 종료하는 예외를 포착 할 수 있습니다.

봐 가지고 이 질문에 를 사용하는 예를 들어, UncaughtExceptionHandler응용 프로그램에 의해 제기 된 예외를 기록 할 수 있습니다.


크 리터 시즘이나 기타 오류 신고 서비스를 이용하시는 분들은 거의 맞습니다.

final UncaughtExceptionHandler defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
            public void uncaughtException(Thread thread, Throwable ex) {
              Intent launchIntent = new Intent(activity().getIntent());
              PendingIntent pending = PendingIntent.getActivity(CSApplication.getContext(), 0,
                    launchIntent, activity().getIntent().getFlags());
              getAlarmManager().set(AlarmManager.RTC, System.currentTimeMillis() + 2000, pending);
              defaultHandler.uncaughtException(thread, ex);
            }
});

public class ForceCloseExceptionHandalingActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setContentView(MyLayout());
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
                myHandaling(paramThread, paramThrowable);
            }
        });
    }

    private ViewGroup MyLayout(){
        LinearLayout mainLayout = new LinearLayout(this);
        mainLayout.setOrientation(LinearLayout.VERTICAL);  
        Button btnHello =new Button(this);
        btnHello.setText("Show all button");
        btnHello.setOnClickListener(new OnClickListener() {         
            @Override
            public void onClick(View v) {                   
                setContentView(MyLayout2());            
            }
        });             
        mainLayout.addView(btnHello);       
        return mainLayout;
    }

    private ViewGroup MyLayout2(){
        LinearLayout mainLayout = new LinearLayout(this);
        mainLayout.setOrientation(LinearLayout.VERTICAL);  
        Button btnHello =new Button(this);
        btnHello.setText("I am a EEROR uncaughtException");
        btnHello.setOnClickListener(new OnClickListener() {         
            @Override
            public void onClick(View v) {                   
                Log.e("Alert","btn  uncaughtException::");
                Toast.makeText(ForceCloseExceptionHandalingActivity.this, "Alert uncaughtException222",Toast.LENGTH_LONG).show();
                View buttone = null;
                setContentView(buttone);            
            }
        });     
        Button btnHello2 =new Button(this);
        btnHello2.setText("I am a EEROR Try n catch");
        btnHello2.setOnClickListener(new OnClickListener() {            
            @Override
            public void onClick(View v) {   

                try{
                    View buttone = null;
                    setContentView(buttone);
                }
                catch (Exception e) {
                    Log.e("Alert","Try n catch:::");
                    Toast.makeText(ForceCloseExceptionHandalingActivity.this, "Alert Try n catch",Toast.LENGTH_LONG).show();
                    setContentView(MyLayout());
                }

            }
        });     
        mainLayout.addView(btnHello);
        mainLayout.addView(btnHello2);
        return mainLayout;
    }
    public void myHandaling(Thread paramThread, Throwable paramThrowable){
        Log.e("Alert","Lets See if it Works !!!" +"paramThread:::" +paramThread +"paramThrowable:::" +paramThrowable);
        Toast.makeText(ForceCloseExceptionHandalingActivity.this, "Alert uncaughtException111",Toast.LENGTH_LONG).show();
        Intent in =new Intent(ForceCloseExceptionHandalingActivity.this,com.satya.ForceCloseExceptionHandaling.ForceCloseExceptionHandalingActivity.class);
        startActivity(in);
        finish();
        android.os.Process.killProcess(android.os.Process.myPid()); 
    }
    @Override
    protected void onDestroy() {
        Log.e("Alert","onDestroy:::");
        Toast.makeText(ForceCloseExceptionHandalingActivity.this, "Alert onDestroy",Toast.LENGTH_LONG).show();
        super.onDestroy();  
    }

패키지에이 클래스를 추가하기 만하면됩니다.

public class MyExceptionHandler implements
    java.lang.Thread.UncaughtExceptionHandler {
private final Context myContext;
private final Class<?> myActivityClass;

public MyExceptionHandler(Context context, Class<?> c) {
    myContext = context;
    myActivityClass = c;
}

public void uncaughtException(Thread thread, Throwable exception) {
    StringWriter stackTrace = new StringWriter();
    exception.printStackTrace(new PrintWriter(stackTrace));
    System.err.println(stackTrace);// You can use LogCat too
    Intent intent = new Intent(myContext, myActivityClass);
    String s = stackTrace.toString();
    //you can use this String to know what caused the exception and in which Activity
    intent.putExtra("uncaughtException", "Exception is: " + stackTrace.toString());
    intent.putExtra("stacktrace", s);
    myContext.startActivity(intent);
    //for restarting the Activity
    Process.killProcess(Process.myPid());
    System.exit(0);
}}

그런 다음 간단히 전화하십시오.

Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler(this,
            SplashScreenActivity.class));

참고 URL : https://stackoverflow.com/questions/2681499/android-how-to-auto-restart-application-after-its-been-force-closed

반응형