应用程序突然重启

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了应用程序突然重启相关的知识,希望对你有一定的参考价值。

我用四个活动制作了简单的图片匹配游戏,完成后可以再次玩。问题是大多数情况下游戏会停止并返回到上一个

错误:

2020-01-29 15:05:51.001 11438-11438 /? E / androidRuntime:致命例外:主要流程:com.mk_kadish.playandlearn,PID:11438android.view.WindowManager $ BadTokenException:无法添加窗口-令牌android.os.BinderProxy@4f4586f无效;您的活动正在进行吗?在android.view.ViewRootImpl.setView(ViewRootImpl.java:798)在android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:356)在android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)在android.app.Dialog.show(Dialog.java:329)在androidx.appcompat.app.AlertDialog $ Builder.show(AlertDialog.java:1007)在com.mk_kadish.playandlearn.game1.game1_HomeActivity $ 4.onFinish(game1_HomeActivity.java:284)在android.os.CountDownTimer $ 1.handleMessage(CountDownTimer.java:127)在android.os.Handler.dispatchMessage(Handler.java:106)在android.os.Looper.loop(Looper.java:193)在android.app.ActivityThread.main(ActivityThread.java:6669)在java.lang.reflect.Method.invoke(本机方法)在com.android.internal.os.RuntimeInit $ MethodAndArgsCaller.run(RuntimeInit.java:493)在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

其中一个文件的代码和另一个文件的代码重复相同:

public class game1_HomeActivity extends AppCompatActivity {

    private AllSharedPrefernces allSharedPrefernces;
    View view1;
    int position1;
    private int height;
    private int width;
    private static final long START_TIME_IN_MILLIS = 120000;
    private TextView mTextViewCountDown;
    private  TextView textViewPairs;
    private Button mButtonStartPause;
    private Button mButtonReset;
    private CountDownTimer mCountDownTimer;
    private Long pointsCounter;
    private boolean mTimerRunning;
    private long mTimeLeftInMillis = START_TIME_IN_MILLIS;
    ArrayList<Game1KeyValue> allpairs;
    boolean isMatch=false;
    ImageAdapter imageAdapter2;
    ImageView curView = null;
    private int countPair = 0;
    TextView tv6;
    TextView myPoints;
    TextView temPoints;
    public int[] drawable;
    int[] pos;
    int maxnum=2;
    int currentPos = -1;
    MediaPlayer mediaPlayerno_ar;
    MediaPlayer mediaPlayer_no;
    MediaPlayer mediaPlayeryes;
    MediaPlayer mediaPlayeryes_ar;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        allSharedPrefernces = new AllSharedPrefernces(this);
        setContentView(R.layout.activity_game1__home);

        drawable=new int[]
                {
                        R.drawable.yes_ar,
                        R.drawable.no_ar,
                        R.drawable.no,
                        R.drawable.yes,
                };

        pos=TawleedRandom.walledArray(4);
        allpairs = new ArrayList<>();
        allpairs.add(new Game1KeyValue(R.drawable.yes,R.drawable.yes_ar));
        allpairs.add(new Game1KeyValue(R.drawable.no ,R.drawable.no_ar));
        temPoints=findViewById(R.id.l1g1_tempoints);

        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        height = displayMetrics.heightPixels;
        width = displayMetrics.widthPixels;
        tv6 = findViewById(R.id.g2_tv4_pairsCount);
        myPoints=findViewById(R.id.g2_tv6_Ponits);
        pointsCounter=getPoints();
        myPoints.setText(pointsCounter+"");
        pointsCounter=0L;
        tv6.setText(""+drawable.length /2);
        mTextViewCountDown = findViewById(R.id.g1_tv2_text_view_countdown);
        textViewPairs=findViewById(R.id.g1_tv2_pairsCount);
        mButtonStartPause = findViewById(R.id.button_start_pause);
        mButtonReset = findViewById(R.id.button_reset);
        mButtonStartPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mTimerRunning) {
                    pauseTimer();
                } else {
                    startTimer();
                }
            }
        });

        mButtonReset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playAgain(v);
            }
        });
        updateCountDownText();

        final ImageAdapter imageAdapter = new ImageAdapter(this,height,width,drawable.length);
        GridView gridView = findViewById(R.id.gridView);
        gridView.setNumColumns(2);
        gridView.setEnabled(false);
        RelativeLayout.LayoutParams parameter =  (RelativeLayout.LayoutParams) gridView.getLayoutParams();
        parameter.setMargins(width * 2 /7, parameter.topMargin, parameter.rightMargin, parameter.bottomMargin); // left, top, right, bottom
        gridView.setLayoutParams(parameter);
        gridView.setAdapter(imageAdapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (currentPos < 0) {
                    currentPos = position;
                    curView = (ImageView) view;
                    runSuitableMusika(drawable[pos[position]]);
                    ((ImageView) view).setImageResource(drawable[pos[position]]);
                    view1 = view;
                    position1 = position;
                } else
                    {
                    if (currentPos == position)
                    {
                        ((ImageView) view).setImageResource(R.drawable.questionbg);
                    }
                    else
                        {
                            runSuitableMusika(drawable[pos[position]]);
                        for (Game1KeyValue d : allpairs) {
                            if ((d.key == drawable[pos[currentPos]]) || (d.value == drawable[pos[currentPos]])) {
                                if (d.key == drawable[pos[currentPos]]) {
                                    if (d.value == drawable[pos[position]]) {
                                        isMatch = true;
                                        d.setUsed(1);
                                    }
                                    break;
                                } else {
                                    if (d.value == drawable[pos[currentPos]]) {
                                        if (d.key == drawable[pos[position]]) {
                                            isMatch = true;
                                        }
                                        break;
                                    }
                                }
                            }
                        }

                        ((ImageView) view).setImageResource(drawable[pos[position]]);
                        view1 = view;

                        if (!isMatch) {
                            Handler handler = new Handler();
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    curView.setImageResource(R.drawable.questionbg);
                                    ((ImageView) view1).setImageResource(R.drawable.questionbg);
                                }
                            }, 600);
                        }
                        else if (isMatch) {
                            isMatch = false;
                            ((ImageView) view).setImageResource(drawable[pos[position]]);
                            runSuitableMusika(drawable[pos[position]]);
                            countPair++;
                            pointsCounter=pointsCounter+1L;
                            temPoints.setText(pointsCounter+"");
                            textViewPairs.setText(countPair + "");
                            if(countPair != maxnum)
                            {
                                int curNum=drawable.length;
                                int[] newArray = new int[curNum-2];
                                int[] pos1=TawleedRandom.walledArray(curNum-2);
                                int k=0;
                                for(int i=0;i<curNum;i++)
                                {
                                    if(i==position || i==currentPos)
                                    {

                                    }
                                    else
                                    {
                                        newArray[pos1[k]] = drawable[pos[i]];
                                        k++;
                                    }
                                }
                                drawable=newArray;
                                pos=pos1;

                                Handler handler = new Handler();
                                handler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        removeFromGrid();
                                    }
                                }, 1000);
                            }
                            else
                            if (countPair == maxnum) {


                                try
                                {
                                    Thread.sleep(500);
                                }
                                catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                passToNext(view);
                            }
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    currentPos = -1;
                }
            }
        });
    }

    private void removeFromGrid()
    {
        GridView gridView = findViewById(R.id.gridView);
        gridView.setAdapter(null);
        imageAdapter2=new ImageAdapter(this,height,width,drawable.length);
        gridView.setNumColumns(2);
        gridView.setAdapter(imageAdapter2);
        currentPos = -1;
    }

    private void startTimer() {
        mCountDownTimer = new CountDownTimer(mTimeLeftInMillis, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mTimeLeftInMillis = millisUntilFinished;
                updateCountDownText();
            }

            @Override
            public void onFinish() {
                GridView gridView0 = findViewById(R.id.gridView);
                gridView0.setVisibility(View.INVISIBLE);
                Button btn2=findViewById(R.id.button_start_pause);
                btn2.setVisibility(View.INVISIBLE);

                AlertDialog.Builder builder = new AlertDialog.Builder(game1_HomeActivity.this);
                builder.setCancelable(true);
                builder.setTitle("            انتهت اللعبة                        ");
                builder.setMessage("حظ أوفر المرة القادمة");
                builder.setNegativeButton("الخروج من اللعبة", new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                       backToFirstMethod();
                    }
                });

                builder.setPositiveButton("العب مرة أخرى", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Intent intent = getIntent();
                        finish();
                        startActivity(intent);
                    }
                });
                builder.show();
            }
        }.start();
        mTimerRunning = true;
        mButtonStartPause.setText("إيقاف مؤقت");
        mButtonReset.setVisibility(View.INVISIBLE);
        GridView gridView = findViewById(R.id.gridView);
        gridView.setNumColumns(2);
        gridView.setEnabled(true);
    }

    private void pauseTimer() {
        mCountDownTimer.cancel();
        mTimerRunning = false;
        mButtonStartPause.setText("استئناف");
        mButtonReset.setVisibility(View.VISIBLE);
        GridView gridView = findViewById(R.id.gridView);
        gridView.setNumColumns(2);
        gridView.setEnabled(false);
    }

    private void updateCountDownText() {
        int minutes = (int) (mTimeLeftInMillis / 1000) / 60;
        int seconds = (int) (mTimeLeftInMillis / 1000) % 60;
        String timeLeftFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
        mTextViewCountDown.setText(timeLeftFormatted);
    }

    public void passToNext(View view)
    {
        allSharedPrefernces.writeTimer1(mTimeLeftInMillis);
        allSharedPrefernces.saveDbPoints(getPoints());
        allSharedPrefernces.storeTempPoints(2L);

        startActivity(new Intent(this,game1_secondActivity.class));
        finish();
    }

    public void playAgain(View view)
    {
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

    public void backToFirstMethod()
    {
        startActivity(new Intent(this, indexActivity.class));
        finish();
    }

    public Long getPoints()
    {
        SchoolDbHelper schoolDbHelper=new SchoolDbHelper(this);
        SQLiteDatabase mydatabase=schoolDbHelper.getReadableDatabase();
        Long c= schoolDbHelper.getCurrentPoints(11,mydatabase);
        return c;
    }
答案

您的例外情况表明您正在呼叫被破坏的活动,反之亦然。确保销毁该活动后没有活动或对话框被调用。有关更多信息,请检查以下链接

Bad window token, you cannot show a dialog before an Activity is created or after it's hidden

以上是关于应用程序突然重启的主要内容,如果未能解决你的问题,请参考以下文章

如何防止应用重启后自动创建子片段?

应用程序突然重启

应用程序突然重启

提效小技巧——记录那些不常用的代码片段

在 CoordinatorLayout Android 中的 ViewPager 片段中使用 NestedScrollView 突然滚动

用模拟器玩游戏怎么电脑突然蓝屏重启