应用程序突然重启

Posted

技术标签:

【中文标题】应用程序突然重启【英文标题】:Application restart suddenly 【发布时间】:2020-05-14 15:20:13 【问题描述】:

我做了简单的图片配对游戏,有四个活动,完成后你可以再次玩。 问题是大多数时候游戏停止并返回到上一个

错误:

2020-01-29 15:05:51.001 11438-11438/? E/android运行时:致命 例外:主要 进程:com.mk_kadish.playandlearn,PID:11438 android.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;
    

【问题讨论】:

【参考方案1】:

您的异常表明您正在调用已销毁的活动,反之亦然。 确保在销毁该活动后没有调用任何活动或对话框。 欲了解更多信息,请查看以下链接

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

【讨论】:

谢谢,但我无法准确识别问题位置。 应用停止并重新启动时应该会出现问题 android.app.Dialog.show(Dialog.java:329) at androidx.appcompat.app.AlertDialog$Builder.show(AlertDialog.java:1007) at com.mk_kadish.playandlearn.game1.game1_HomeActivity$4.onFinish(game1_HomeActivity.java:284 看看这个【参考方案2】:

您正在尝试为不再存在的上下文显示对话框。

尝试在 startTimer() 的 onFinish() 方法中使用它

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity().this);

同时检查活动是否可见,例如

if (getActivity().hasWindowFocus()) 
// create & show dialog here

【讨论】:

我删除了所有的 AlertDialogs 问题仍然存在

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

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

更改活动时程序突然结束

kindle为啥看着看着突然自己重启呢。

笔记本win10突然自动重启,反复反复重启?

shutdown

为啥电脑会突然断网,重启电脑就好了?