Skip to content

Instantly share code, notes, and snippets.

@rlarla245
Last active August 4, 2018 10:19
Show Gist options
  • Save rlarla245/f34bc74d3c4fd0131f3d6ff27c7ce34d to your computer and use it in GitHub Desktop.
Save rlarla245/f34bc74d3c4fd0131f3d6ff27c7ce34d to your computer and use it in GitHub Desktop.
Firebase 11 - Remote Config
11. Firebase – Remote Config(Change Value)
● 원격으로 앱의 배경색, 프로레스 작동 및 종료가 가능합니다.
1. 문서로 이동합니다. 원격 구성 탭으로 이동합니다.
- compile 코드를 붙여넣습니다.
- 작동 원리 부분의 mFirebaseRemoteConfig 코드를 가져옵니다. HomeActivity로 이동하여 remoteConfig() 메소드를 생성해 바디 부분으로 붙여넣습니다. 에러는 스스로 잡습니다.
해당 코드는 디버깅 테스트를 할 때 에러를 잡아주는 기능입니다.
- 문서 내 하단의 디폴트 설정 값을 입력하는 코드도 복사해 해당 메소드 하단에 붙여넣습니다.
해당 코드는 서버에 해당되는 값이 없을 때 참조하는 기능입니다.
2. 현재, xml 쪽에서 에러가 발생하므로 잡아주기 위해 해당 문서 코드의 MainActivity로 이동하여(github로 이동됨)
remote_config_defaults를 복사해 생성합니다. xml 디렉토리를 생성한 뒤 remote_config_defaults 파일을 만들어주면 됩니다.
- 원하는 기능으로 바꾸기 위해 키 값을 조금씩 변형시켜 줍니다.
첫 번째 키는 toolBarColor, value는 black으로 줍니다.
- 업로드 기능을 실행하는 메소드 내부에 remoteConfig 메소드를 실행시킵니다.
3. fetch 메소드 요청 코드를 문서에서 불러와 remoteConfig 메소드내에 붙입니다. fetch 메소드의 파라미터 값으로는 0을 넣습니다.
요청 시간의 의미를 지닙니다.
Toast 박스의 MainActivity를 HomeActivity로 변경시킵니다.
4. displayWelcomMessage 메소드에서 에러가 발생하므로 void 리턴 값으로 새로운 메소드를 생성해줍니다. 여기서 본인이 원하는 기능들을 입력하면 됩니다.
- 툴바 생각을 변화시키도록 했으므로 툴바를 전역 변수로 생성해서 사용할 수 있게 만듭니다. 코드는 다음과 같습니다.
String toolbarColor = mFirebaseRemoteConfig.getString(“toolBarColor”);
Boolean aBoolean = mFirebaseRemoteConfig.getBoolean(“welcome_message_caps”);
String message = mFirebaseRemoteConfig.getString(“welcome_message”);
toolbar.setBackgroundColor(Color.parseColor(toolbarColor));
if (aBoolean) {
AlertDialog.Buidler builder = new AlertDialog.Builder(this);
builder.setMessage(message)
.setPositiveButton(“확인”, new OnClickListner...) {
// 내부에 HomeActivity.this.finish();
});
builder.create().show();
}
5. 원격 조종을 통해 앱에 대한 접근을 막습니다. remote... xml 파일로 가서 불린 값을 false로 줍니다.
6. 콘솔에서 매개변수를 추가한 뒤 원하는 기능을 넣습니다.
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final int GALLERY_CODE = 10;
private TextView nameTextView, emailTextView;
protected ImageView uploadimageView;
protected EditText titleEditText, descriptionEditText;
protected Button uploadButton;
protected String imagePath;
private FirebaseDatabase database;
private FirebaseAuth auth;
protected FirebaseStorage storage;
protected FirebaseRemoteConfig mFirebaseRemoteConfig;
protected Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
uploadimageView = (ImageView) findViewById(R.id.homeactivity_imageview);
titleEditText = (EditText) findViewById(R.id.homeactivity_edittext_title);
descriptionEditText = (EditText) findViewById(R.id.homeactivity_edittext_description);
uploadButton = (Button) findViewById(R.id.homeactivity_button_uploadbutton);
auth = FirebaseAuth.getInstance();
storage = FirebaseStorage.getInstance();
database = FirebaseDatabase.getInstance();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View view = navigationView.getHeaderView(0);
nameTextView = (TextView) view.findViewById(R.id.homeactivity_navi_nametextview);
emailTextView = (TextView) view.findViewById(R.id.homeactivity_navi_emailtextview);
nameTextView.setText(auth.getCurrentUser().getDisplayName());
emailTextView.setText(auth.getCurrentUser().getEmail());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
// 버튼에 클릭 리스너를 달아줍니다.
uploadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
upload(imagePath);
}
});
remoteConfig();
}
public void remoteConfig() {
mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
.setDeveloperModeEnabled(BuildConfig.DEBUG)
.build();
mFirebaseRemoteConfig.setConfigSettings(configSettings);
mFirebaseRemoteConfig.setDefaults(R.xml.remote_config_defaults);
mFirebaseRemoteConfig.fetch(0)
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(HomeActivity.this, "Fetch Succeeded",
Toast.LENGTH_SHORT).show();
// After config data is successfully fetched, it must be activated before newly fetched
// values are returned.
mFirebaseRemoteConfig.activateFetched();
} else {
Toast.makeText(HomeActivity.this, "Fetch Failed",
Toast.LENGTH_SHORT).show();
}
displayWelcomeMessage();
}
});
}
public void displayWelcomeMessage() {
String toolbarColor = mFirebaseRemoteConfig.getString("toolbarColor");
String message = mFirebaseRemoteConfig.getString("welcome_message");
Boolean aBoolean = mFirebaseRemoteConfig.getBoolean("welcome_message_caps");
toolbar.setBackgroundColor(Color.parseColor(toolbarColor));
if (aBoolean) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message)
.setPositiveButton("확인", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
HomeActivity.this.finish();
}
});
builder.create().show();
}
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_board) {
Intent board_intent = new Intent(this, BoardActivity.class);
startActivity(board_intent);
} else if (id == R.id.nav_gallery) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(MediaStore.Images.Media.CONTENT_TYPE);
// 상수 입력이 필요합니다. 10으로 넣습니다.
startActivityForResult(intent, GALLERY_CODE);
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
} else if (id == R.id.navi_logout) {
auth.signOut();
LoginManager.getInstance().logOut();
finish();
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == GALLERY_CODE) {
// 글로벌 변수로 미리 선언해야 합니다. String이겠죠?
imagePath = getPath(data.getData());
// 해당 코드는 File file = new File(getPath(data.getData()));와 동일합니다.
File file = new File(imagePath);
// Uri 자체가 내부 저장소와 외부를 이어주는 기능이므로 내부 저장소 이미지를 앱으로 불러온다는 의미가 됩니다.
uploadimageView.setImageURI(Uri.fromFile(file));
}
}
private void upload(String uri) {
StorageReference storageRef
= storage.getReferenceFromUrl("gs://howlfirebasetest1-8cb99.appspot.com");
// getData()에서 uri로 변경합니다.
final Uri file = Uri.fromFile(new File(uri));
StorageReference riversRef =
storageRef.child("images/" + file.getLastPathSegment());
UploadTask uploadTask = riversRef.putFile(file);
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
Toast.makeText(HomeActivity.this, "업로드에 실패했습니다.", Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
@SuppressWarnings("VisibleForTests")
Uri downloadUrl = taskSnapshot.getDownloadUrl();
ImageDTO imageDTO = new ImageDTO();
imageDTO.imageUri = downloadUrl.toString();
imageDTO.imageName = file.getLastPathSegment();
imageDTO.title = titleEditText.getText().toString();
imageDTO.description = descriptionEditText.getText().toString();
imageDTO.uid = auth.getCurrentUser().getUid();
imageDTO.userId = auth.getCurrentUser().getEmail();
database.getReference().child("images").push().setValue(imageDTO);
Toast.makeText(HomeActivity.this, "업로드에 성공했습니다.", Toast.LENGTH_SHORT).show();
}
});
}
// 경로를 지정해주는 메소드입니다.
public String getPath(Uri uri) {
String[] proj = {MediaStore.Images.Media.DATA};
CursorLoader cursorLoader = new CursorLoader(this, uri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(index);
}
}
<?xml version="1.0" encoding="utf-8"?>
<!-- START xml_defaults -->
<defaultsMap>
<entry>
<key>toolbarColor</key>
<value>#000000</value>
</entry>
<entry>
<key>welcome_message_caps</key>
<value>false</value>
</entry>
<entry>
<key>welcome_message</key>
<value>Welcome to my awesome app!</value>
</entry>
</defaultsMap>
<!-- END xml_defaults -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment