简体   繁体   English

如何从非活动和finish();获取应用程序上下文?

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

here is my code: 这是我的代码:

this is the HomeActivity.java: 这是HomeActivity.java:

public class HomeActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

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

This is the SessionManagement.java: 这是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();" 我正试图称其为“ finish();”。 inside this: public void checkLogin(){ if(!this.isLoggedIn()){ so i can close/finish(); 在此里面: public void checkLogin(){if(!this.isLoggedIn()){这样我就可以关闭/完成(); the HomeActivity.java class. HomeActivity.java类。

how can i do that? 我怎样才能做到这一点?

Create your class as extends of Application, in my case, my class is: 创建类作为Application的扩展,在我的情况下,我的类是:

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: 在包含此自定义类的模块中,转到manifiedt,并将应用程序名称定义为:

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

Then, from your other class, call the app context as: 然后,从您的另一个类中,调用应用程序上下文为:

Zillion.getContext()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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