Search code examples
androidaudioandroid-mediaplayeractivity-manager

If home button is pressed without playing the audio, then the app crashes


If I press the home button without playing the audio. The app crashes, but it works perfectly when I play the audio and press the home button. Here's my code:

@Override
protected void onPause()
{
    Context context = getApplicationContext();
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
    if (!taskInfo.isEmpty()) {
        ComponentName topActivity = taskInfo.get(0).topActivity;
        if (!topActivity.getPackageName().equals(context.getPackageName())) {
            play.pause();
            but19.setBackgroundResource(R.drawable.play);
        }
    }
    super.onPause();
}
@Override
public void onBackPressed(){
    if(play!=null && (play.isPlaying())){
        if(play.isPlaying())
            play.stop();
        play.release();
    }
    super.onBackPressed();
}

Solution

  • Its crashing becasue play is null when you pause it crash so add chcek before calling pasue state.

    Change play.pause(); to

    if( play!=null && play.isPlaying()){ play.pause(); }

    Complete Code:

    @Override
    protected void onPause()
    {
        Context context = getApplicationContext();
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        if (!taskInfo.isEmpty()) {
            ComponentName topActivity = taskInfo.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
              if( play!=null && play.isPlaying()){
                  play.pause();
                 }
                but19.setBackgroundResource(R.drawable.play);
            }
        }
        super.onPause();
    }