简体   繁体   中英

how to get application context from non activity and finish();?

here is my code:

this is the HomeActivity.java:

public class HomeActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        session = new SessionManagement(getApplicationContext());
        session.checkLogin();

This is the SessionManagement.java:

public class SessionManagement {
    SharedPreferences pref;

    // Editor for Shared preferences
    SharedPreferences.Editor editor;

    // Context
    Context _context;

    public void checkLogin(){
        // Check login status
        if(!this.isLoggedIn()){

            // user is not logged in redirect him to Login Activity
            Intent i = new Intent(_context, LoginActivity.class);
            // Closing all the Activities
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            // Add new Flag to start new Activity
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            // Staring Login Activity
            _context.startActivity(i);
        }

    }
}

I am trying to call "finish();" inside this: public void checkLogin(){ if(!this.isLoggedIn()){ so i can close/finish(); the HomeActivity.java class.

how can i do that?

Create your class as extends of Application, in my case, my class is:

package zillion;

import android.app.Application;
import android.content.Context;

/**
 * Created by SCM on 2017-02-17.
 */

public class Zillion extends Application {

    private static Context mContext;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();
    }

    public static Context getContext() {
        return mContext;
    }
}

In the module that contains this custom class, go to the manifiest, and define the app name as:

<application
        android:name=".Zillion"
</application>

Then, from your other class, call the app context as:

Zillion.getContext()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM