JBay Solutions Development Blog on Java, Android, Play2 and others
RSS RSS RSS RSS

Starting new Activity in Android

From an Activity

To start a new Activity from another Activity:

Intent intent = new Intent(this, OtherActivity.class);
startActivity(intent);

From a Service

Intent intent = new Intent(this, OtherActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);


From somewhere else

To start an Activity from another class that does not extend Context or does not extend a class that allows access to a Context, a context must be retrieved in some way.

Either by passing it to the method being called:

public void startNewActivity(Context context) {
    Intent intent = new Intent(this, OtherActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
}

Or by using the Application Context, if the class that extends Application (if there is one) makes it available directy of by using an helper class.

Example of Aplication and AppState Helper Class

Following a set of classes to help with making the Application Context available to all classes of the project.

The Application class for the project:

package com.example.mytestapp;

import android.app.Application;
public class MyTestApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        MyTestAppState.setApplicationContext(this);
    }
}

The AppState class for the project:

package com.example.mytestapp;

import android.content.Context;
import android.util.Log;

public class MyTestAppState {

    private static final String TAG = "MyTestAppState";
    private static Context sContext;

    private static MyTestAppState INSTANCE;

    public static MyTestAppState getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new MyTestAppState();
        }
        return INSTANCE;
    }

    private MyTestAppState() {
        if (sContext == null) {
            throw new IllegalStateException("MyTestAppState inited before app context set");
        }
        Log.v(TAG, "MyTestAppState inited");
    }

    public Context getContext() {
        return sContext;
    }

    public static void setApplicationContext(Context context) {
        if (sContext != null) {
        Log.w(TAG, "setApplicationContext called twice! old=" + sContext + " new=" + context);
        }
        sContext = context.getApplicationContext();
    }
}

Using the Application Context

Intent intent = new Intent(this, OtherActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MyTestAppState.getInstance().getContext().startActivity(intent);

What is Intent.FLAGACTIVITYNEW_TASK

According to the Android Development API documents, when this Flag is set, the new ACtivity will become the start of a new task on the History Stack.




comments powered by Disqus