在Serializable类中获取Activity的上下文



我有一个实现'Serializable'的类,但我无法在其中获得我的主要活动的上下文。下面是这个类的代码:

public class Game implements Serializable{
private String name;
private ColorTheme theme;
private int distance = 0;
private int score = 0;
boolean boom = false;
protected Context context;
public Game(MainActivity context){
    this.context = context.getApplicationContext();
}

在此之后,我认为我得到了上下文,然后我想要的是,当得分大于1时,应用程序应该关闭。

score = (i+1);
if (score >1)
{
}

我想在这个条件下关闭我的游戏,但它没有给我任何选项来完成上下文。请告诉我哪里错了。我认为上下文在这个Serializable类中没有成功实现。帮助需要

供参考

在Game类中关闭应用程序不是一个好方法,最好在Activity本身中完成。一个好的解决方案是在Game类中创建一个方法,如下所示:

public boolean shouldCloseApplication(){
  return this.score > 1;
}

和在活动中,使用以下内容:

if(game.shouldCloseApplication()){
  //close the application as mentioned below
  this.finishAffinity();
}

说,如果你想关闭应用程序,你只需要调用

this.finishAffinity();

参考这篇文章

因此,不传递" MainActivity ",直接使用" Context "与

一起传递。
Game game = new Game(MainActivity.this);

和接收

public Game(Context context){
  this.context = context;
}

一起使用
if(score > 1)
{
  context.finishAffinity();
}

不建议,但可以使用

如果不行,使用

context.getActivity().finish();
System.exit(0);

希望能有所帮助

try this

public Game(MainActivity context){
this.context = context;
}

score = (i+1);
if (score >1){
PackageManager pm = context.getPackageManager();
                        Intent i = new Intent("android.intent.action.MAIN");
                        i.addCategory("android.intent.category.HOME");
                        List<ResolveInfo> lst = pm.queryIntentActivities(i, 0);
                        if (lst != null) {
                            for (ResolveInfo resolveInfo : lst) {
                                try {
                                    ApplicationInfo ai = pm.getApplicationInfo(
                                                    resolveInfo.activityInfo.packageName,0);
                                    if ((ai.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                                        Intent goHome = new Intent();
                                        goHome.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                        goHome.setClassName(
                                                resolveInfo.activityInfo.packageName,
                                                resolveInfo.activityInfo.name);
                                        context.startActivity(goHome);
                                        int pid = android.os.Process.myPid();
                                        android.os.Process.killProcess(pid);
                                        break;
                                    }
                                } catch (NameNotFoundException e) {
                                    logMessage(LOG_TYPE_ERROR, "AppConstant-exitFromApp-kill", e.getMessage());
                                }
                            }
                        }
}

最新更新