Idrizi.A
Idrizi.A

Reputation: 12010

Android - Close first activity

I have created an android application which has two activities, one of them is MainActivity and the other one is Article activity

In this application you can open unlimited number of activities. So it's like an article app, inside an article there are also other articles so you can follow unlimited number of articles. Every article opens a new Article activity.

Now what I want to do is this: When the 10th Article is opened I want to close the first Article activity (not MainActivity).

I have also read this question, but it works only if you have different activities (i.e. ActivityA, ActivityB, ActivityC...).

Is there any way I can do this?

Upvotes: 1

Views: 246

Answers (2)

Eugene R. Wang
Eugene R. Wang

Reputation: 151

this is a hack only to get it working but you may want to try fragment from your description;

  1. Create a new class called ActivityHandler.java

    public class ActivityHandler { 
    private static ActivityHandler uniqueInstance;
    private static List<Activity> mListActivity;
    private static int SIZE_LIMIT = 10;
    
    public static ActivityHandler getInstance() {
        if (uniqueInstance == null) {
            synchronized (ActivityHandler.class) {
                if (uniqueInstance == null) {
                    uniqueInstance = new ActivityHandler();
                }
            }
        }
        return uniqueInstance;
    }
    
    
    
    private Activityhandler() {
        if (mListActivity == null ) {
            mListActivity = new ArrayList();
        }
    }
    
    
    public static void add (Activity activity){
        mListActivity.add(activity);        
        if (mListActivity.size() > 10){
            Activity firstActivity = mListActivity.remove(0);
            firstActivity.finish();         
        }
    }   
    }
    

In your ArticleActivity's OnCreateMethod:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.article_activity);
    ActivityHandler.getInstance().add(this);


}

Upvotes: 0

Aakash
Aakash

Reputation: 5251

When opening 10th article, do this:

Intent intent = new Intent(this,Your_Article.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

or if you only want to close a particular activity, get the instance of that activity and close it using finish().

Upvotes: 1

Related Questions