안드로이드 액티비티
상속을 이용한 베이스() 만들기.
안드로이드 스튜디오 프로젝트 생성.
퍼미션 관련 권한 자동화 시킬려니 동작이 안됨.
/////
/////java
/////
/**
* 추상화 클래스 상속전용.
*/
abstract class BaseActivity extends AppCompatActivity {
abstract protected int setContentViewLayout();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(setContentViewLayout());
Log.e("bear", "BaseActivity start");
//무언가 하나를 불러내면 딱 하고 끝나서
// 여러 가지 신경안써도 되는 것....어떻게 해야하지????
// onRequestPermissionsResult 이것을 baseActivity에서 처리하고 싶다는 건데.
}
/**
* 프래그먼트 add
* backStackCheck 기본적으로 true
* .addToBackStack(tag)
*/
protected void addFragment(int id, Fragment fragment) {
addFragment(id, fragment, null, true);
}
protected void addFragment(int id, Fragment fragment, boolean backStackCheck) {
addFragment(id, fragment, null, backStackCheck);
}
protected void addFragment(int id, Fragment fragment, String tag) {
addFragment(id, fragment, tag, true);
}
protected void addFragment(int id, Fragment fragment, String tag, boolean backStackCheck) {
//프래그먼트 등록 후 back 누르면 이전 activity 또는 fragment로 이동한다.
if (backStackCheck) {
getSupportFragmentManager()
.beginTransaction()
.add(id, fragment, tag)
// 백스텍에 이름이 없거나 널이면 프래그먼트클래스 이름을 등록
// 아니면 백스텍 이름을 등록 삼항연산자 앞에가 true : false
.addToBackStack(tag)
.commit();
} else {
getSupportFragmentManager()
.beginTransaction()
.add(id, fragment, tag)
.commit();
}
}
protected void replaceFragment(int id, Fragment fragment) {
replaceFragment(id, fragment, null, true);
}
protected void replaceFragment(int id, Fragment fragment, boolean backStackCheck) {
replaceFragment(id, fragment, null, backStackCheck);
}
protected void replaceFragment(int id, Fragment fragment, String tag) {
replaceFragment(id, fragment, tag, true);
}
//
protected void replaceFragment(int id, Fragment fragment, String tag, boolean backStackCheck) {
if (backStackCheck) {
getSupportFragmentManager()
.beginTransaction()
.replace(id, fragment, tag)
// 백스텍에 이름이 없거나 널이면 프래그먼트클래스 이름을 등록
// 아니면 백스텍 이름을 등록 삼항연산자 앞에가 true : false
.addToBackStack(tag)
.commit();
} else {
getSupportFragmentManager()
.beginTransaction()
.replace(id, fragment, tag)
.commit();
}
}
@Override
public void onBackPressed() {
Log.w("bear", "fragment Size : " + getSupportFragmentManager().getBackStackEntryCount());
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
Log.w("bear", "000");
super.onBackPressed();
} else {
Log.w("bear", "1111");
super.onBackPressed();
}
}
/**
* 액티비티 전환
*/
protected void changeActivity(Context context, Class<?> activity, boolean activityFinish) {
Intent intent = new Intent(context, activity);
startActivity(intent);
if (activityFinish) {
finish();
}
}
/**
* 퍼미션 검사 리스너.
*/
protected interface PermissionCheckListener {
/***/
void permissionCheckFinish();
}
/**
* 리스너 등록.
*/
protected PermissionCheckListener permissionCheckListener;
/**
* 온 크레딧 바로 아래 생성 되어야 한다
*/
public void setPermissionCheckListener(PermissionCheckListener permissionCheckListener) {
this.permissionCheckListener = permissionCheckListener;
}
private final int PERMISSION_REQUEST = 1000;
/**
* 이게 BaseActivity 에 들어갈 필요가 있는가?????
* 스트링 배열로 퍼미션 체크.
* 필요할때만 if 문으로 처리.
* true 일 경우 퍼미션 팝업.
*/
public boolean permissionCheck(String[] strings) {
boolean check = false;
// //안드로이드 마시멜로 이후 퍼미션 체크.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
for (int i = 0; i < strings.length; i++) {
if (ContextCompat.checkSelfPermission(this, strings[i]) == PackageManager.PERMISSION_DENIED) {
ActivityCompat.requestPermissions(this, strings, PERMISSION_REQUEST);
check = true;
break;
}
}
}
return check;
}
/**
* 거부를 했을때 처리
* 다시보지 않기 체크 후 거부를 하면 설정에서 권한을 허용하도록 요청.
* 허용하지 않을 경우 앱 사용 을 못함..
* 처리를 잘못하면 무한 반복할 경우가 생김.
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_REQUEST) {
// //안드로이드 마시멜로 이후 퍼미션 체크.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] == 0) {
if (grantResults.length == (i + 1)) {
// 인터페이스 콜백으로 리턴됨.
permissionCheckListener.permissionCheckFinish();
}
} else {
// 거부한 이력이 있으면 true를 반환한다.
if (shouldShowRequestPermissionRationale(permissions[i])) {
ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUEST);
break;
} else {
new AlertDialog.Builder(this)
.setTitle("다시보지않기 클릭.")
.setMessage(permissions[i] + " 권한이 거부되었습니다 설정에서 직접 권한을 허용 해주세요.")
.setNeutralButton("설정", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivity(intent);
Toast.makeText(getApplicationContext(), "권한 설정 후 다시 실행 해주세요.", Toast.LENGTH_SHORT).show();
finish();
}
})
.setPositiveButton("확인", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "권한 설정을 하셔야 앱을 사용할 수 있습니다.", Toast.LENGTH_SHORT).show();
finish();
}
})
.setCancelable(false)
.create().show();
}// shouldShowRequestPermissionRationale /else
} // 권한 거절
} // for end
}//Build.VERSION.SDK_INT end
}//requestCode end
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public class MainActivity extends BaseActivity {
@Override
protected int setContentViewLayout() {
return R.layout.activity_main;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setPermissionCheckListener(new PermissionCheckListener() {
@Override
public void permissionCheckFinish() {
Log.w("bear", "MainActivity 여기서 시작해야 한다.");
addFragment(R.id.layoutContainer, BlankFragment.newInstance());
addFragment(R.id.layoutContainer, BlankFragment.newInstance("bear"));
replaceFragment(R.id.layoutContainer, BlankFragment.newInstance("bear", "bear22 "));
}
});
if (permissionCheck(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE})) {
Log.e("bear", "퍼미션 체크를 시도.");
return;
}
permissionCheckListener.permissionCheckFinish();
}
}
public class MainActivity extends BaseActivity {
@Override
protected int setContentViewLayout() {
return R.layout.activity_main;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setPermissionCheckListener(new PermissionCheckListener() {
@Override
public void permissionCheckFinish() {
Log.w("bear", "MainActivity 여기서 시작해야 한다.");
addFragment(R.id.layoutContainer, BlankFragment.newInstance());
addFragment(R.id.layoutContainer, BlankFragment.newInstance("bear"));
replaceFragment(R.id.layoutContainer, BlankFragment.newInstance("bear", "bear22 "));
}
});
if (permissionCheck(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE})) {
Log.e("bear", "퍼미션 체크를 시도.");
return;
}
permissionCheckListener.permissionCheckFinish();
}
}
public class MainActivity extends BaseActivity {
@Override
protected int setContentViewLayout() {
return R.layout.activity_main;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setPermissionCheckListener(new PermissionCheckListener() {
@Override
public void permissionCheckFinish() {
Log.w("bear", "MainActivity 여기서 시작해야 한다.");
addFragment(R.id.layoutContainer, BlankFragment.newInstance());
addFragment(R.id.layoutContainer, BlankFragment.newInstance("bear"));
replaceFragment(R.id.layoutContainer, BlankFragment.newInstance("bear", "bear22 "));
}
});
if (permissionCheck(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE})) {
Log.e("bear", "퍼미션 체크를 시도.");
return;
}
permissionCheckListener.permissionCheckFinish();
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
abstract class BaseFragment extends Fragment {
abstract protected int setContentViewLayout();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
Log.e("bear", "BaseFragment start");
return inflater.inflate(setContentViewLayout(), container, false);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* 기본 프래그먼트 작업.
*/
public class BlankFragment extends BaseFragment {
@Override
protected int setContentViewLayout() {
// onCreateView 오버라이딩 할 필요없다.
return R.layout.fragment_blank;
}
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
public BlankFragment() {
// Required empty public constructor
}
public static BlankFragment newInstance() {
return new BlankFragment();
}
public static BlankFragment newInstance(String param1) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
fragment.setArguments(args);
return fragment;
}
public static BlankFragment newInstance(String param1, String param2) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
if (getArguments().getString(ARG_PARAM1) != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
}
if (getArguments().getString(ARG_PARAM2) != null) {
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (mParam1 != null) {
Log.d("bear", "blankFragment mParam1 : " + mParam1);
}
if (mParam2 != null) {
Log.d("bear", "blankFragment mParam2 : " + mParam2);
}
TextView fragment_Textview = view.findViewById(R.id.fragment_Textview);
fragment_Textview.setText(" m : " + mParam1 + " , m " + mParam2);
}
}