development

Android-“뒤로”버튼을 재정 의하여 내 활동을 완료하지 못하도록하는 방법은 무엇입니까?

big-blog 2020. 5. 13. 20:42
반응형

Android-“뒤로”버튼을 재정 의하여 내 활동을 완료하지 못하도록하는 방법은 무엇입니까?


현재 알림이 표시되면 알림 표시 줄에도 알림이 표시되는 활동이 있습니다.

이것은 사용자가 집을 누르고 활동이 배경으로 밀릴 때 알림을 통해 활동으로 돌아갈 수 있도록하기위한 것입니다.

사용자가 뒤로 버튼을 누르면 문제가 발생하지만 내 활동이 손상되지만 사용자가 뒤로 밀 수는 있지만 알림을 통해 여전히 활동에 도달 할 수 있도록 알림은 유지됩니다. 그러나 USER가 이것을 시도하면 Null Pointers가 이전 활동을 다시 가져 오는 대신 새로운 활동을 시작하려고 시도합니다.

본질적으로 뒤로 버튼이 홈 버튼과 똑같이 작동하기를 원하며 여기에 내가 지금까지 시도한 방법이 있습니다.


        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event)  {
            if (Integer.parseInt(android.os.Build.VERSION.SDK) < 5
                    && keyCode == KeyEvent.KEYCODE_BACK
                    && event.getRepeatCount() == 0) {
                Log.d("CDA", "onKeyDown Called");
                onBackPressed();
            }

            return super.onKeyDown(keyCode, event);
        }

        public void onBackPressed() {
            Log.d("CDA", "onBackPressed Called");
            Intent setIntent = new Intent(Intent.ACTION_MAIN);
            setIntent.addCategory(Intent.CATEGORY_HOME);
            setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(setIntent); 

            return;
        }   

그러나 위의 코드는 여전히 내 활동을 파괴 할 수있는 것처럼 보입니다. 뒤로 버튼을 누를 때 활동이 파괴되는 것을 어떻게 막을 수 있습니까?


키 리스너를 제거하거나 true가지고 있으면 돌아옵니다 KEY_BACK.

뒤로 키를 잡으려면 다음이 필요합니다 ( super in 을 호출하지 마십시오 onBackPressed()).

또한 백그라운드에서 서비스를 실행하려는 경우 startForeground()알림을 계속 확인해야합니다. 그렇지 않으면 메모리를 확보해야하는 경우 Android에서 서비스를 종료합니다.

@Override
public void onBackPressed() {
   Log.d("CDA", "onBackPressed Called");
   Intent setIntent = new Intent(Intent.ACTION_MAIN);
   setIntent.addCategory(Intent.CATEGORY_HOME);
   setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
   startActivity(setIntent);
}

한 줄의 코드로만 구현하는 것이 더 쉬웠습니다.

@Override
public void onBackPressed() {
   moveTaskToBack(true);
}

나는 당신이 원하는 것은 뒤로 버튼을 재정의하는 것이 아니라 좋은 생각처럼 보이지 않습니다-안드로이드 OS는 그 동작을 정의하고 왜 변경합니까?) 활동 수명주기 를 사용하고 설정 / 데이터를 onSaveInstanceState (Bundle) 이벤트.

@Override
onSaveInstanceState(Bundle frozenState) {
    frozenState.putSerializable("object_key",
        someSerializableClassYouWantToPersist);
    // etc. until you have everything important stored in the bundle
}

그런 다음 onCreate (Bundle)사용 하여 지속 된 번들에서 모든 것을 꺼내고 상태를 다시 만듭니다.

@Override
onCreate(Bundle savedInstanceState) {
    if(savedInstanceState!=null){ //It could be null if starting the app.
        mCustomObject = savedInstanceState.getSerializable("object_key");
    }
    // etc. until you have reloaded everything you stored
}

위의 의사 코드를 고려하여 올바른 방향을 찾으십시오. Activity Lifecycle을 읽으면 원하는 것을 달성하는 가장 좋은 방법을 결정하는 데 도움이됩니다.


간단하게 ..

@Override
public void onBackPressed() {
    //super.onBackPressed();
}

//super.onBackPressed (); 주석 달기 트릭을 할 것입니다


이 시도:

@Override
public void onBackPressed() {
    finish();
}

Just in case you want to handle the behaviour of the back button (at the bottom of the phone) and the home button (the one to the left of the action bar), this custom activity I'm using in my project may help you.

import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;

/**
 * Activity where the home action bar button behaves like back by default
 */
public class BackActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setupHomeButton();
    }

    private void setupHomeButton() {
        final ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onMenuHomePressed();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    protected void onMenuHomePressed() {
        onBackPressed();
    }
}

Example of use in your activity:

public class SomeActivity extends BackActivity {

    // ....

    @Override
    public void onBackPressed()
    {
        // Example of logic
        if ( yourConditionToOverride ) {
            // ... do your logic ...
        } else {
            super.onBackPressed();
        }
    }    
}

@Override
public void onBackPressed() {
// Put your code here.
}

//I had to go back to the dashboard. Hence,

@Override
public void onBackPressed() {
    Intent intent = new Intent(this,Dashboard.class);
    startActivity(intent);
}
Just write this above or below the onCreate Method(within the class)

참고URL : https://stackoverflow.com/questions/3141996/android-how-to-override-the-back-button-so-it-doesnt-finish-my-activity

반응형