oncreate被调用两次,导致应用程序过早退出

2w2cym1i  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(305)

我浏览了其他的so帖子,但没有发现任何与我的问题相关的东西。
我正在尝试创建一个应用程序,它将从上次重新启动中获取用户的步数。以下是我的主要活动:

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) {

    }
}

主活动合同.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);
    }
}

正如您所看到的,标签中有两个带有我名字的日志,这里发生的是“hello”日志记录了两次。我猜这是第一个oncreate,它负责我的应用程序在启动前完成,因为我在logcat中得到这个警告: W/Activity: Can request only one set of permissions at a time 我只请求一个权限,但由于oncreate被调用了两次,第一个权限被自动拒绝,从而导致应用程序 finish() 在它开始之前!从昨天起我就一直在为这个费劲,谢谢你的帮助!

8yoxcaq7

8yoxcaq71#

我想出来了!
罪魁祸首是这样的: AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO); 所以很明显,这会导致配置改变,导致 onCreate 方法调用两次,若要克服此问题,请在调用super in oncreate之前调用它,如下所示:

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

相关问题