Android java restart application

Как программно «перезапустить» приложение для Android?

Во-первых, я знаю, что на самом деле нельзя убивать/перезапускать приложение на Android. В моем случае я хочу factory — reset мое приложение в конкретном случае, когда сервер отправляет клиенту определенную информацию. Пользователь может быть зарегистрирован на сервере только с ОДНОМ экземпляром приложения (т.е. несколько устройств не разрешены). Если другой экземпляр получает этот «logged-in» -lock, все остальные экземпляры этого пользователя должны удалить свои данные (factory — reset), чтобы поддерживать согласованность. Можно принудительно получить блокировку, поскольку пользователь может удалить приложение и переустановить его, что приведет к другому идентификатору экземпляра, и пользователь больше не сможет освободить блокировку. Поэтому можно принудительно получить блокировку. Из-за этой силовой возможности нам нужно всегда проверять конкретный пример, что он имеет блокировку. Это делается на (почти) каждом запросе на сервер. Сервер может послать «неверный-lock-id». Если это обнаружено, клиентское приложение должно удалить все. Это был прецедент. Нет для вопроса реализации: У меня есть Activity A, который запускает Login Activity L или главное приложение Activity B в зависимости от поля sharedPrefs. После запуска L или B он закрывается, так что работает только L или B. Таким образом, в том случае, если пользователь уже зарегистрирован в B, выполняется сейчас. B запускает C. C вызывает startService для IntentService D. Это приводит к этому стеку: (A) > B > C > D Из метода onHandleIntent D событие отправляется на ResultReceiver R. R теперь обрабатывает это событие, предоставляя пользователю диалог, в котором он может выбрать factory — reset приложение (удалить базу данных, sharedPrefs и т.д.). После factory — reset я хочу перезапустить приложение (чтобы закрыть все действия) и снова запустить A, который затем запускает login Activity L и заканчивается: (A) > L Метод Dialog onClick выглядит следующим образом:

@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); >
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 все еще работают. Если я нажму кнопку «Назад» в login 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?

Читайте также:  Javascript при клике открыть

Источник

How to restart an Activity in Android?

This example demonstrates how do I restart an Activity in android.

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

Step 3 − Add the following code to src/MainActivity.java

import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.util.Random; public class MainActivity extends AppCompatActivity < TextView textView; Button button; Random random = new Random(); @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textView); button = findViewById(R.id.button); textView.setText("Random Number: " + random.nextInt(100)); button.setOnClickListener(new View.OnClickListener() < @Override public void onClick(View v) < Intent intent = getIntent(); finish(); startActivity(intent); >>); > >

Step 4 − Add the following code to androidManifest.xml

Let’s try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project’s activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −

Click here to download the project code.

Источник

How to Make Android App with Restart Button — Android Studio 2.2.2 Tutorial

Restart Android App with a button. It’s very easy! Some times we had to switch off and then turn our applications on again, this can be easily done through the method that we’re about to discuss on.

Manually doing this? Download the full source code and add this to your project files.

 package com.sabithpkcmnr.sampleapp; 

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity <
Button bt_restart;
@Override
protected void onCreate(Bundle savedInstanceState) <
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

bt_restart=(Button)findViewById(R.id.restart);
bt_restart.setOnClickListener(new View.OnClickListener() <
@Override
public void onClick(View v) <
Intent restartIntent = getBaseContext().getPackageManager()
.getLaunchIntentForPackage(getBaseContext().getPackageName());
restartIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(restartIntent);
>
>);

>
>

   
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="@android:color/white"
tools:context="com.sabithpkcmnr.sampleapp.MainActivity">

android:text="Restart This App"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/restart"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />



Finally, run your app there you may find your app restart when you press the restart button.

Hope that was helpful!
Thanks!

How to Make Android App with Restart Button - Android Studio 2.2.2 Tutorial

How to Make Android App with Restart Button — Android Studio 2.2.2 Tutorial Reviewed by Unknown on 03:38 Rating: 5

Источник

How to auto restart an Android Application after a Crash or a Force Close Error ?

The biggest nightmare of Android developers is the Crash or Force Close Error that can occur when a user uses one of their applications. Indeed, it’s always a bad message sent to the user and the major risk is that the user uninstalls the application. Unfortunately, you can’t always catch properly all errors and sometimes you can’t avoid a Crash or a Force Close Error. In these specific cases, a good approach is to configure auto restart for your Android Application. With this approach, you have better chances to keep users on your application.

android-png-0

Note that you can also enjoy this tutorial in video on Youtube :

To start, you need to create a custom Application class implementation to get an instance of your context continuously :

package com.ssaurel.appcrash; import android.app.Application; import android.content.Context; public class MyApplication extends Application < public static MyApplication instance; @Override public void onCreate() < super.onCreate(); instance = this; >@Override public Context getApplicationContext() < return super.getApplicationContext(); >public static MyApplication getInstance() < return instance; >>

Don’t forget to add this Application implementation on your Android Manifest :

To try the auto restart feature, we need to define a button in the layout of the Main Activity. When we will click on the button, we’re going to crash the application. The layout will have the following form :

Now, we enter in the core of our auto restart feature. You need to create a custom implementation of the UncaughtExceptionHandler interface. What is the purpose of this interface ? It’s an interface for handlers invoked when a Thread abruptly terminates due to an uncaught exception.
Our custom implementation will have the following form :

package com.ssaurel.appcrash; import android.app.Activity; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; public class MyExceptionHandler implements Thread.UncaughtExceptionHandler < private Activity activity; public MyExceptionHandler(Activity a) < activity = a; >@Override public void uncaughtException(Thread thread, Throwable ex) < Intent intent = new Intent(activity, MainActivity.class); intent.putExtra("crash", true); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(MyApplication.getInstance().getBaseContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT); AlarmManager mgr = (AlarmManager) MyApplication.getInstance().getBaseContext().getSystemService(Context.ALARM_SERVICE); mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, pendingIntent); activity.finish(); System.exit(2); >>

When an uncaught exception occurs, the uncaughtException method will be called. We’re going to create an Intent to restart our application at the defined moment via an Alarm. Then, we finish the current activity and we exit the application. Note that we put a boolean parameter to indicate that the application is restarted.

Last step is to install the UncaughtExceptionHandler during the start of the application by calling the static setDefaultUncaughtExceptionHandler method of the Thread class :

package com.ssaurel.appcrash; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Toast; public class MainActivity extends AppCompatActivity < @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler(this)); if (getIntent().getBooleanExtra("crash", false)) < Toast.makeText(this, "App restarted after crash", Toast.LENGTH_SHORT).show(); >> public void crashMe(View v) < throw new NullPointerException(); >>

Note that we launch a NullPointerException in the crashMe method to force the crash of the application and test the auto restart feature. Other thing to note is the crash boolean parameter test when the activity is launched. Like said previously, it lets us to know when the application is restarted after a crash or when the application is launched for the first time.

Now, you can launch the application and you should see the following screen after a click on the crashMe button :

Источник

Оцените статью