简体   繁体   中英

onCreate being called twice causing app to exit prematurely

I went through the other SO posts but didn't find anything relevant to my problem.

I am trying to create an app that will get the user's step count from the last reboot. Here is my main Activity:

package com.assignment.bwowassignment;

import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;

import java.util.Arrays;

public class MainActivity extends AppCompatActivity implements MainActivityContract.View {

    MainActivityPresenter presenter;

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);

        Log.d("mihir", "hello");
        presenter = new MainActivityPresenter(this);
        presenter.requestActivityPermission(this);
    }

    @Override
    public void onGetStepsSuccess(float[] values) {
        Log.d("mihir", Arrays.toString(values));
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == presenter.ACTIVITY_REQUEST_CODE)
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                presenter.registerListener(this);
            else {
                Log.d("mihir", "kill me");
                finish();
            }
    }

    @Override
    protected void onPause() {
        super.onPause();
        presenter.sensorManager.unregisterListener(presenter);
    }
}

MainActivityPresenter.java

package com.assignment.bwowassignment;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.util.Log;

import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.util.logging.Logger;

public class MainActivityPresenter implements MainActivityContract.Presenter, SensorEventListener {

    MainActivityContract.View view;
    SensorManager sensorManager;
    Sensor sensor;

    public MainActivityPresenter(MainActivityContract.View view) {
        this.view = view;
        sensorManager = (SensorManager) ((Context) view).getSystemService(Context.SENSOR_SERVICE);
        sensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
    }

    @Override
    public void registerListener(Context context) {
        sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    public void requestActivityPermission(Context context) {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACTIVITY_RECOGNITION) == PackageManager.PERMISSION_GRANTED)
            registerListener(context);
        else if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.ACTIVITY_RECOGNITION))
            new AlertDialog.Builder(context)
                    .setTitle("Permission required")
                    .setMessage("This permission is required to fetch the sensor data from your phone, denying it will cause the app to exit")
                    .setPositiveButton("Give permission", (dialog, which) -> ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.ACTIVITY_RECOGNITION}, ACTIVITY_REQUEST_CODE))
                    .setNegativeButton("Deny", (dialog, which) -> ((Activity) context).finish())
                    .show();
        else
            ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.ACTIVITY_RECOGNITION}, ACTIVITY_REQUEST_CODE);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        view.onGetStepsSuccess(event.values);
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }
}

MainActivityContract.java

package com.assignment.bwowassignment;

import android.content.Context;

public interface MainActivityContract {

    interface View {
        void onGetStepsSuccess(float[] values);
    }

    interface Presenter {
        int ACTIVITY_REQUEST_CODE = 1;

        void registerListener(Context context);
        void requestActivityPermission(Context context);
    }
}

As you can see there are two Logs with my name in the tag, what is happening here is the "hello" log is getting logged twice. I am guessing it's the first onCreate which is responsible for my app finishing before starting since I get this warning in the logcat:

W/Activity: Can request only one set of permissions at a time

I am only requesting one permission but due to the onCreate being called twice the first permission gets automatically denied which causes the app to finish() before it already started, I have been scratching my head over this since yesterday, any help is appreciated!

I figured it out!

The culprit was this line: AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);

So apparently, this causes a configuration change, causing the onCreate method to be called twice, to get over this, call it BEFORE the call to super in onCreate like this:

AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM