setResult第一次没有返回调用onActivityResult

时间:2016-10-17 09:46:37

标签: java android android-activity realm

我在onActivityResult上遇到了一些问题。我有2个活动,LoginActivity和MainActivity。 MainActivity是发布活动。 OnCreate,它会检查是否有登录用户,如果没有,它会使用startActivityForResult()启动LoginActivity。当用户成功登录时,在LoginActivity上调用setResult()和后续的finish()方法。这会触发MainActivity上的onActivityResult。一切正常。

但是,我在MainActivity中有注销按钮。如果单击,它将删除当前用户的会话,并再次调用startActivityForResult并启动LoginActivity。相同的流程,只有在LoginActivity上调用setResult()和finish()之后才会显示MainActivity(应用程序移动到后台)并且不调用onActivityResult()。只有当我手动将应用程序带到前台时才会调用onActivityResult()。是什么给了什么?

为什么我第一次登录而不是第二次登录时会调用onActivityResult?

清单摘要:     

        <activity
            android:name=".activities.MainActivity"
            android:label="@string/title_activity_main">
            <intent-filter android:label="@string/app_name">
                <category android:name="android.intent.category.LAUNCHER" />
                <action android:name="android.intent.action.MAIN" />
            </intent-filter>
        </activity>

LoginActivity代码段:

/**
     * Saves the logged in session in the db and creates a UserModel if it's a new user logging in
     * @param intent
     */
    private void saveSession(Intent intent) {

        Session session = intent.getParcelableExtra(Session.SESSION);
        User user = session.getUser();

        realm.beginTransaction();

        //Check if user exists in db
        UserModel userModel = realm.where(UserModel.class).equalTo(PATIENT_ID, session.getUser().getPatientId()).findFirst();

        if(userModel == null) {
            userModel = new UserModel();
            userModel.setLanguage(user.getLanguage());
            userModel.setLastLogin(user.getLastLogin());
            userModel.setPatientId(user.getPatientId());
            userModel.setPermissions(new RealmList<RealmString>());
            for(int i = 0;user.getPermissions().size()>i;i++) {
                RealmString realmString = new RealmString();
                realmString.setValue(user.getPermissions().get(i));
                userModel.getPermissions().add(realmString);
            }
            userModel.setRegistered(user.getRegistered());
            userModel.setRole(user.getRole());
            userModel.setUserName(user.getUserName());
        }
        UserSessionModel userSession = new UserSessionModel();
        userSession.setUser(userModel);
        userSession.setCookie(session.getCookie());
        userSession.setJwt(session.getJwt());
        realm.copyToRealmOrUpdate(userSession);

        realm.commitTransaction();


        mJwt = session.getJwt();


        finish();
    }

    @Override
    public void finish() {
        Intent result = new Intent();
        result.putExtra(LoginActivity.JWT, mJwt);
        setResult(Activity.RESULT_OK, result);
        super.finish();
    }

MainActivity:

/**
     * Show all the accounts registered on the device.
     * If there are no accounts, start LoginActivity to create one.
     */
    private void getAccount() {

        //Get all accounts
        final RealmResults<UserModel> availableAccounts = realm.where(UserModel.class).findAll();
        if(availableAccounts.size() == 0) {
            //Open login activity if there are no accounts
            Intent intent = new Intent(this, LoginActivity.class);
            this.startActivityForResult(intent, AUTHENTICATE);
        } else if (availableAccounts.size() > 0) {
            availableAccounts.sort("lastLogin", Sort.DESCENDING);
            UserModel account = availableAccounts.get(0);
            getSession(account);
        }
    }

/**
     * Get an authentication token
     */
    private void getSession(UserModel account) {
        UserSessionModel result = realm.where(UserSessionModel.class)
                .equalTo("user.patientId", account.getPatientId())
                .findFirst();

        if(result != null) {
            init(result);
        } else {
            //Authenticate existing account
            Intent intent = new Intent(this, LoginActivity.class);
            intent.putExtra(LoginActivity.PATIENT_ID, account.getPatientId());
            this.startActivityForResult(intent, AUTHENTICATE);
        }
    }

在MainActivity中注销

/**
     * Logout and return to login view
     */
    private void logout() {
        showProgress(true);
        mLogoutTask = new UserLogoutTask(mSession.getCookie());
        if(mSession !=null) {
            realm.beginTransaction();
            mSession.deleteFromRealm();
            realm.commitTransaction();
        }
        mLogoutTask.execute();
        mSession = null;
        getAccount();
    }

MainActivity中的OnActivityResult

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case AUTHENTICATE:
                if(resultCode == RESULT_OK){
                    Bundle bundle = data.getExtras();
                    String jwt = bundle.getString(LoginActivity.JWT);
                    UserSessionModel session = realm.where(UserSessionModel.class).equalTo("jwt", jwt).findFirst();
                    init(session);
                }
                break;
        }
    }

初始化方法

private void init(final UserSessionModel session) {

        mSession = session;

        View headerView = navigationView.getHeaderView(0);
        lblUsername = ButterKnife.findById(headerView, R.id.header_username);
        // Set username in menu header
        lblUsername.setText(getString(R.string.welcome, mSession.getUser().getUserName()));

        Crashlytics.setUserIdentifier(mSession.getUser().getPatientId());

        //Need to do this for the following code because Realm only allows access to object in the same threads
        final String patientId = mSession.getUser().getPatientId();

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MRESIST_LOCATION_PERMISSION_CHANGED);
        } else {
            startGPSService();
        }

        //Start sensor service
        Thread t = new Thread(){
            public void run(){
                sensorServiceIntent = new Intent(getApplicationContext(), SensorService.class);
                sensorServiceIntent.putExtra("patientId", patientId);
                getApplicationContext().startService(sensorServiceIntent);
            }
        };
        t.start();
    }

0 个答案:

没有答案