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

时间:2016-05-23 22:55:28

标签: java android android-activity android-context activity-finish

这是我的代码:

这是HomeActivity.java:

public class HomeActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

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

这是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);
        }

    }
}

我试图称之为“完成();”在这里面: public void checkLogin(){if(!this.isLoggedIn()){所以我可以关闭/完成(); HomeActivity.java类。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

创建您的类作为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;
    }
}

在包含此自定义类的模块中,转到最表体,并将应用名称定义为:

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

然后,从您的其他班级,将应用程序上下文调用为:

Zillion.getContext()