Android - Auto starting an activity after some duration

152 views Asked by At

I am new to Android.

I am having Accelerometer sensor data in one activity. I stopped the SensorManager after a shake has been detected. Now I need to restart the activity automatically after 5 seconds, the SensorManager has stopped. Is it possible?

or is it possible to start the current activity from the same?

Can somebody help me with this?

Thanks in Advance :)

4

There are 4 answers

1
A.Arjun On BEST ANSWER

Use this code when SensorManager has stopped. It will restart the Activity after 5 sec when SensorManager has stopped.

new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {

                    Intent intent = getIntent();
                    finish();
                    startActivity(intent);
                }
            }, 5000);
0
Maya Mohite On

Thread is used to provide delay. Add the below code when your sensor stopped detected.

 new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

              //Start Activity here
            }
        },5000);
1
ρяσѕρєя K On

I need to restart the activity automatically after 5 seconds, the sensorManager has stopped. Is it possible?

Yes it is possible using AlarmManager

When stopping SensorManager provide PendingIntent of Activity to AlarmManager with required delay to start Activity:

Intent intent = new Intent(context,MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context,0, intent, 
                              Intent.FLAG_ACTIVITY_NEW_TASK);
AlarmManager manager =(AlarmManager) getSystemService(Context.ALARM_SERVICE);  
manager.set(AlarmManager.RTC,System.currentTimeMillis() + 6000, pendingIntent);  
0
Linh On

When you stop Sensor, you can start Activity after 5s by use Handler like

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
  @Override
  public void run() {
      startActivity(...);
  }
}, 5000);