Android:离线时我的应用程序不断崩溃

Posted

技术标签:

【中文标题】Android:离线时我的应用程序不断崩溃【英文标题】:Android: My App keep crashing when offline 【发布时间】:2021-10-23 23:09:10 【问题描述】:

我今天刚刚在我的应用中实现了横幅插页式广告,我的应用是一款游戏,它应该是在线游戏,但我注意到如果用户离线,游戏就会打开,我对此没有任何问题,但问题是每当任何有插页式广告的活动或地点,如果没有互联网连接,应用程序将崩溃 那么如何解决这个问题呢?

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_anagram);

    questionCounter = findViewById(R.id.questionCounter);


    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

    tv_info = findViewById(R.id.tv_info);
    tv_word = findViewById(R.id.tv_word);
    et_guess = findViewById(R.id.et_guess);
    b_check = findViewById(R.id.b_check);
    guessItTimer = findViewById(R.id.guessItTimer);
    scaling = AnimationUtils.loadAnimation(this,R.anim.scale);


    //ads
    MobileAds.initialize(this, new OnInitializationCompleteListener() 
        @Override
        public void onInitializationComplete(@NonNull InitializationStatus initializationStatus) 

        
    );

    AdRequest adRequest1 = new AdRequest.Builder().build();
    // Attempt loading ad for interstitial
    InterstitialAd.load(this,"MyAd--ID", adRequest1,
            new InterstitialAdLoadCallback() 
                @Override
                public void onAdLoaded(@NonNull InterstitialAd interstitialAd) 
                    // The mInterstitialAd reference will be null until
                    // an ad is loaded.
                    mInterstitialAd = interstitialAd;
                    Log.i("TAG", "onAdLoaded");
                

                @Override
                public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) 
                    // Handle the error
                    Log.i("TAG", loadAdError.getMessage());
                    mInterstitialAd = null;
                
            );

    r = new Random();

    newGame();
    checkAnswer();



private String shuffleWord(String word)
    List<String> letters = Arrays.asList(word.split(""));
    Collections.shuffle(letters);
    String shuffled = "";
    for(String letter: letters)
        shuffled += letter;
    
    return shuffled;


private void newGame()
    //get random word from dictionary
    currentWord = dictionary[r.nextInt(dictionary.length)];

    // show the shuffled word
    tv_word.setText(shuffleWord(currentWord));
    et_guess.setText("");
    b_check.setEnabled(true);
    //so tv_info color change and not to cancel the other request
    if (tv_info.getText().toString() == "Fantastic!")
        tv_info.setVisibility(View.VISIBLE);
     else
        tv_info.setVisibility(View.INVISIBLE);
    


//CountdownTimer
public void resetTimer() 
    timer = new CountDownTimer(35150, 1000) 
        @Override
        public void onTick(long l) 
            int timerColor = Integer.parseInt(guessItTimer.getText().toString());
            guessItTimer.setText(String.valueOf(l / 1000));
            //Animation for timer and color
            if (timerColor < 11 && timerColor >= 1) 
                guessItTimer.setTextColor(Color.parseColor("#E10F0F"));
                guessItTimer.startAnimation(scaling);//----------------->
            

        

        @Override
        public void onFinish() 
            Toast.makeText(AnagramActivity.this, "Time is over", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(AnagramActivity.this, anagramAgainActivity.class));
            finish();
        
    .start();


public void onBackPressed() 
    super.onBackPressed();
    timer.cancel();
    mInterstitialAd.show(AnagramActivity.this);
    this.finish();


public void checkAnswer() 
    b_check.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View view) 
            if(et_guess.getText().toString().equalsIgnoreCase(currentWord))
                tv_info.setVisibility(View.VISIBLE);
                tv_info.setTextColor(Color.GREEN);
                tv_info.setText("Fantastic!");
                b_check.setEnabled(false);

                // set count of numb of question answered
                index = index +1;
                String ar = String.valueOf(index);
                questionCounter.setText(ar);

                newGame();

             else 
                tv_info.setVisibility(View.VISIBLE);
                tv_info.setTextColor(Color.RED);
                tv_info.setText("Try Again!");
            
        
    );
    resetTimer();

【问题讨论】:

可能是一段代码或某种堆栈跟踪? 刚刚添加了示例活动的代码 请同时发布崩溃日志。 【参考方案1】:

您在onBackPressed() 方法中调用mInterstitialAd.show(AnagramActivity.this);。应用离线时,mInterstitialAd 为空,导致崩溃。添加条件以仅在广告加载时显示广告(mInterstitialAd 不为空)。

public void onBackPressed() 
    super.onBackPressed();
    timer.cancel();
    if(mInterstitialAd !=null)
    mInterstitialAd.show(AnagramActivity.this);
    this.finish();

【讨论】:

成功了,谢谢

以上是关于Android:离线时我的应用程序不断崩溃的主要内容,如果未能解决你的问题,请参考以下文章

即使在离线时如何缓存网页以在我的 android 应用程序中使用

Android Webview离线时加载缓存

当用户离线时,Firebase 身份验证会话会持续多长时间?

执行代码时我的 Android 崩溃

当用户在Android中使用XMPP离线时向用户发送通知

当接收器离线时,socket.io 发出不工作