Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start an activity after certain time period?

Tags:

android

timer

i need to start an activity from the current activity after a certain time period. I coded like below.

public class FirstActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_first);


    new Timer().schedule(new TimerTask(){
        public void run() { 
            startActivity(new Intent(FirstActivity.this, SecondActivity.class));
        }
    }, 2000); 
}

But its not working..it keeps on crashing.. Is my method correct? my manifest file is as below

`

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="15" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".FirstActivity"
        android:label="@string/title_activity_first" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".SecondActivity"
        android:label="@string/title_activity_second" >
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.first.FirstActivity" />
    </activity>
</application>

like image 897
Ram Avatar asked Nov 05 '12 11:11

Ram


People also ask

Which method is used to start an activity?

onCreate() On activity creation, the activity enters the Created state. In the onCreate() method, you perform basic application startup logic that should happen only once for the entire life of the activity.

How do I start the same activity again on android?

If you just want to reload the activity, for whatever reason, you can use this. recreate(); where this is the Activity. This is never a good practice. Instead you should startActivity() for the same activity and call finish() in the current one.


2 Answers

You can use the Handler class postDelayed() method to perform this:

Handler mHandler = new Handler();
mHandler.postDelayed(new Runnable() {

    @Override
    public void run() {
        //start your activity here  
    }

}, 1000L);

Where 1000L is the time in milliseconds after which the code within the Runnable class will be called.

Try to use this .

like image 171
Dinesh Sharma Avatar answered Oct 13 '22 20:10

Dinesh Sharma


Thanks all... its working now.. the problem is with the second activity not with the timer. when i comment out "getActionBar().setDisplayHomeAsUpEnabled(true);" these lines in the second activity, it started working . these lines wont give any error at compile time but, during runtime it will be an issue.Thanks.

like image 41
Ram Avatar answered Oct 13 '22 20:10

Ram