Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package su.gamepoint.opendomofon.pro;
- import android.content.Context;
- import android.content.DialogInterface;
- import android.content.Intent;
- import android.content.SharedPreferences;
- import android.content.pm.PackageManager;
- import android.graphics.Color;
- import android.hardware.Camera;
- import android.hardware.camera2.CameraAccessException;
- import android.hardware.camera2.CameraManager;
- import android.net.Uri;
- import android.os.Build;
- import android.os.Bundle;
- import android.preference.PreferenceManager;
- import android.support.annotation.NonNull;
- import android.support.v4.content.ContextCompat;
- import android.support.v7.app.AlertDialog;
- import android.support.v7.app.AppCompatActivity;
- import android.support.v7.widget.LinearLayoutManager;
- import android.support.v7.widget.RecyclerView;
- import android.support.v7.widget.Toolbar;
- import android.text.Editable;
- import android.text.TextWatcher;
- import android.text.format.DateFormat;
- import android.view.Menu;
- import android.view.MenuInflater;
- import android.view.MenuItem;
- import android.view.View;
- import android.widget.EditText;
- import android.widget.ImageView;
- import android.widget.ProgressBar;
- import android.widget.TextView;
- import android.widget.Toast;
- import com.bumptech.glide.Glide;
- import com.firebase.ui.database.FirebaseRecyclerAdapter;
- import com.google.android.gms.appindexing.Action;
- import com.google.android.gms.appindexing.AppIndex;
- import com.google.android.gms.auth.api.Auth;
- import com.google.android.gms.common.ConnectionResult;
- import com.google.android.gms.common.api.GoogleApiClient;
- import com.google.android.gms.tasks.OnFailureListener;
- import com.google.android.gms.tasks.OnSuccessListener;
- import com.google.firebase.auth.FirebaseAuth;
- import com.google.firebase.auth.FirebaseUser;
- import com.google.firebase.database.DatabaseReference;
- import com.google.firebase.database.FirebaseDatabase;
- import com.google.firebase.remoteconfig.FirebaseRemoteConfig;
- import com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings;
- import com.jude.swipbackhelper.SwipeBackHelper;
- import java.util.HashMap;
- import java.util.Map;
- import de.hdodenhof.circleimageview.CircleImageView;
- import hani.momanii.supernova_emoji_library.Actions.EmojIconActions;
- import hani.momanii.supernova_emoji_library.Helper.EmojiconEditText;
- import static su.gamepoint.opendomofon.pro.R.id.fonarik;
- public class ChatActivity extends AppCompatActivity
- implements GoogleApiClient.OnConnectionFailedListener {
- private int SETTINGS_ACTION = 1;
- boolean hasFlash = false; // флаг поддержки устройством камеры
- private Camera camera;
- private DatabaseReference mSimpleFirechatDatabaseReference;
- public FirebaseRecyclerAdapter<ChatMessage, FirechatMsgViewHolder>
- mFirebaseAdapter;
- private ImageView mSendButton;
- private RecyclerView mMessageRecyclerView;
- //private LinearLayoutManager mLinearLayoutManager;
- private ProgressBar mProgressBar;
- private EditText mMsgEditText;
- private SharedPreferences mSharedPreferences;
- public static final String DEFAULT_NAME = "PointApps";
- private String mUsername;
- private String mPhotoUrl;
- private GoogleApiClient mGoogleApiClient;
- private FirebaseAuth mFirebaseAuth;
- private FirebaseUser mFirechatUser;
- private FirebaseRemoteConfig mFirebaseRemoteConfig;
- //Фонарь
- private CameraManager mCameraManager;
- private String mCameraId;
- private Boolean isTorchOn;
- //Views UI
- private RecyclerView rvListMessage;
- private LinearLayoutManager mLinearLayoutManager;
- private ImageView btSendMessage,btEmoji;
- private EmojiconEditText edMessage;
- private View contentRoot;
- private EmojIconActions emojIcon;
- @Override
- public void onStart() {
- super.onStart();
- // ATTENTION: This was auto-generated to implement the App Indexing API.
- // See https://g.co/AppIndexing/AndroidStudio for more information.
- mGoogleApiClient.connect();
- Action viewAction = Action.newAction(
- Action.TYPE_VIEW, // TODO: choose an action type.
- "Main Page", // TODO: Define a title for the content shown.
- // TODO: If you have web page content that matches this app activity's content,
- // make sure this auto-generated web page URL is correct.
- // Otherwise, set the URL to null.
- Uri.parse("http://host/path"),
- // TODO: Make sure this auto-generated app URL is correct.
- Uri.parse("android-app://su.gamepoint.opendomofon.pro/http/host/path")
- );
- AppIndex.AppIndexApi.start(mGoogleApiClient, viewAction);
- }
- @Override
- public void onStop() {
- super.onStop();
- // ATTENTION: This was auto-generated to implement the App Indexing API.
- // See https://g.co/AppIndexing/AndroidStudio for more information.
- Action viewAction = Action.newAction(
- Action.TYPE_VIEW, // TODO: choose an action type.
- "Main Page", // TODO: Define a title for the content shown.
- // TODO: If you have web page content that matches this app activity's content,
- // make sure this auto-generated web page URL is correct.
- // Otherwise, set the URL to null.
- Uri.parse("http://host/path"),
- // TODO: Make sure this auto-generated app URL is correct.
- Uri.parse("android-app://su.gamepoint.opendomofon.pro/http/host/path")
- );
- AppIndex.AppIndexApi.end(mGoogleApiClient, viewAction);
- mGoogleApiClient.disconnect();
- }
- public static class FirechatMsgViewHolder extends RecyclerView.ViewHolder {
- public TextView msgTextView;
- public TextView userTextView;
- public CircleImageView userImageView;
- public TextView timeTextView;
- public FirechatMsgViewHolder(View v) {
- super(v);
- msgTextView = (TextView) itemView.findViewById(R.id.msgTextView);
- userTextView = (TextView) itemView.findViewById(R.id.userTextView);
- userImageView = (CircleImageView) itemView.findViewById(R.id.userImageView);
- timeTextView = (TextView) itemView.findViewById(R.id.timeTextView);
- }
- }
- @Override
- public void onCreate(Bundle savedInstanceState) {
- SharedPreferences pref3 = PreferenceManager
- .getDefaultSharedPreferences(this);
- String themeName3 = pref3.getString("theme3", "Стандартная");
- if (themeName3.equals("Стандартная")) {
- setTheme(R.style.AppThemeDrawer);
- } else if (themeName3.equals("Тёмная")) {
- setTheme(R.style.Theme2);
- } else if (themeName3.equals("Синяя")) {
- setTheme(R.style.ThemeBlue);
- } else if (themeName3.equals("Тёмно-синяя")) {
- setTheme(R.style.ThemeBlueBlack);
- } else if (themeName3.equals("Красная")) {
- setTheme(R.style.ThemeRed);
- } else if (themeName3.equals("Тёмно-красная")) {
- setTheme(R.style.ThemeRedBlack);
- }
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_chat);
- isTorchOn = false;// фонарь
- SwipeBackHelper.onCreate(this);
- SharedPreferences pref11 = PreferenceManager
- .getDefaultSharedPreferences(this);
- String themeName11 = pref11.getString("theme11", "Включить");
- if (themeName11.equals("Включить")) {
- SwipeBackHelper.getCurrentPage(this)//get current instance
- .setSwipeBackEnable(true)
- .setScrimColor(Color.WHITE);//on-off
- } else if (themeName11.equals("Выключить")) {
- SwipeBackHelper.getCurrentPage(this)//get current instance
- .setSwipeBackEnable(true)//on-off
- .setScrimColor(Color.WHITE)//on-off
- .setSwipeEdge(0);
- }
- mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
- mUsername = DEFAULT_NAME;
- Boolean isFlashAvailable = getApplicationContext().getPackageManager()
- .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
- if (!isFlashAvailable) {
- AlertDialog alert = new AlertDialog.Builder(ChatActivity.this)
- .create();
- alert.setTitle("Ошибка!");
- alert.setMessage("Ваше устройство не поддерживает встроенный фонарик!");
- alert.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- // closing the application
- finish();
- System.exit(0);
- }
- });
- alert.show();
- return;
- }
- mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
- try {
- mCameraId = mCameraManager.getCameraIdList()[0];
- } catch (CameraAccessException e) {
- e.printStackTrace();
- }
- //Подсказка на меню
- TextView textView = (TextView) findViewById(R.id.msgTextView);
- btEmoji = (ImageView)findViewById(R.id.buttonEmoji);
- btEmoji = (ImageView)findViewById(R.id.buttonEmoji);
- edMessage = (EmojiconEditText)findViewById(R.id.msgEditText);
- contentRoot = findViewById(R.id.contentRoot);
- EmojIconActions emojIcon=new EmojIconActions(this,contentRoot,edMessage,btEmoji);
- emojIcon.ShowEmojIcon();
- // Initialize ProgressBar and RecyclerView.
- mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
- mMessageRecyclerView = (RecyclerView) findViewById(R.id.messageRecyclerView);
- mLinearLayoutManager = new LinearLayoutManager(this);
- mLinearLayoutManager.setStackFromEnd(true);
- mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
- // инклюдим тулбар
- Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
- setSupportActionBar(toolbar);
- getSupportActionBar().setDisplayHomeAsUpEnabled(true);
- //mProgressBar.setVisibility(ProgressBar.INVISIBLE);
- mMsgEditText = (EditText) findViewById(R.id.msgEditText);
- //mMessageEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(mSharedPreferences
- // .getInt(CodelabPreferences.FRIENDLY_MSG_LENGTH, DEFAULT_MSG_LENGTH_LIMIT))});
- mMsgEditText.addTextChangedListener(new TextWatcher() {
- @Override
- public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
- }
- @Override
- public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
- if (charSequence.toString().trim().length() > 0) {
- mSendButton.setEnabled(true);
- } else {
- mSendButton.setEnabled(false);
- }
- }
- @Override
- public void afterTextChanged(Editable editable) {
- }
- });
- mSendButton = (ImageView) findViewById(R.id.sendButton);
- mSendButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- ChatMessage friendlyMessage = new
- ChatMessage(mMsgEditText.getText().toString(),
- mUsername,
- mPhotoUrl);
- mSimpleFirechatDatabaseReference.child("messages")
- .push().setValue(friendlyMessage);
- mMsgEditText.setText("");
- }
- });
- mSimpleFirechatDatabaseReference = FirebaseDatabase.getInstance().getReference();
- mFirebaseAdapter = new FirebaseRecyclerAdapter<ChatMessage,
- FirechatMsgViewHolder>(
- ChatMessage.class,
- R.layout.chat_message,
- FirechatMsgViewHolder.class,
- mSimpleFirechatDatabaseReference.child("messages")) {
- @Override
- public void populateViewHolder(FirechatMsgViewHolder viewHolder,
- ChatMessage friendlyMessage, int position) {
- mProgressBar.setVisibility(ProgressBar.INVISIBLE);
- viewHolder.msgTextView.setText(friendlyMessage.getText());
- viewHolder.userTextView.setText(friendlyMessage.getName());
- viewHolder.timeTextView.setText(DateFormat.format("dd-MM-yyyy ( в HH:mm:ss)", friendlyMessage.getTimeMessage()));
- if (friendlyMessage.getPhotoUrl() == null) {
- viewHolder.userImageView
- .setImageDrawable(ContextCompat
- .getDrawable(ChatActivity.this,
- R.drawable.ic_account_circle_black_36dp));
- } else {
- Glide.with(ChatActivity.this)
- .load(friendlyMessage.getPhotoUrl())
- .into(viewHolder.userImageView);
- }
- }
- };
- mFirebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
- @Override
- public void onItemRangeInserted(int positionStart, int itemCount) {
- super.onItemRangeInserted(positionStart, itemCount);
- int friendlyMessageCount = mFirebaseAdapter.getItemCount();
- int lastVisiblePosition =
- mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
- // If the recycler view is initially being loaded or the
- // user is at the bottom of the list, scroll to the bottom
- // of the list to show the newly added message.
- if (lastVisiblePosition == -1 ||
- (positionStart >= (friendlyMessageCount - 1) &&
- lastVisiblePosition == (positionStart - 1))) {
- mMessageRecyclerView.scrollToPosition(positionStart);
- }
- }
- });
- mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
- mMessageRecyclerView.setAdapter(mFirebaseAdapter);
- // ATTENTION: This "addApi(AppIndex.API)"was auto-generated to implement the App Indexing API.
- // See https://g.co/AppIndexing/AndroidStudio for more information.
- mGoogleApiClient = new GoogleApiClient.Builder(this)
- .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
- .addApi(Auth.GOOGLE_SIGN_IN_API)
- .addApi(AppIndex.API).build();
- mFirebaseAuth = FirebaseAuth.getInstance();
- mFirechatUser = mFirebaseAuth.getCurrentUser();
- if (mFirechatUser == null) {
- startActivity(new Intent(this, AuthorizationActivity.class));
- finish();
- return;
- } else {
- mUsername = mFirechatUser.getDisplayName();
- if (mFirechatUser.getPhotoUrl() != null) {
- mPhotoUrl = mFirechatUser.getPhotoUrl().toString();
- }
- }
- mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
- FirebaseRemoteConfigSettings firebaseRemoteConfigSettings =
- new FirebaseRemoteConfigSettings.Builder()
- .setDeveloperModeEnabled(true)
- .build();
- Map<String, Object> defaultConfigMap = new HashMap<>();
- defaultConfigMap.put("button_name", "");
- mFirebaseRemoteConfig.setConfigSettings(firebaseRemoteConfigSettings);
- mFirebaseRemoteConfig.setDefaults(defaultConfigMap);
- fetchConfig();
- }
- public void fetchConfig() {
- long cacheExpiration = 3600; // 1 hour in seconds
- // If developer mode is enabled reduce cacheExpiration to 0 so that
- // each fetch goes to the server. This should not be used in release
- // builds.
- if (mFirebaseRemoteConfig.getInfo().getConfigSettings()
- .isDeveloperModeEnabled()) {
- cacheExpiration = 0;
- }
- mFirebaseRemoteConfig.fetch(cacheExpiration)
- .addOnSuccessListener(new OnSuccessListener<Void>() {
- @Override
- public void onSuccess(Void aVoid) {
- // Make the fetched config available via
- // FirebaseRemoteConfig get<type> calls.
- mFirebaseRemoteConfig.activateFetched();
- //mSendButton.setText(mFirebaseRemoteConfig.getString("button_name"));
- }
- })
- .addOnFailureListener(new OnFailureListener() {
- @Override
- public void onFailure(@NonNull Exception e) {
- //mSendButton.setText(mFirebaseRemoteConfig.getString("button_name"));
- }
- });
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- MenuInflater inflater = getMenuInflater();
- inflater.inflate(R.menu.chat_menu, menu);
- return true;
- }
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- switch (item.getItemId()) {
- case fonarik:
- fonarMenu(); // вкл выкл фонарика
- return true;
- case R.id.sign_out_menu:
- // mFirebaseAuth.signOut();
- // Auth.GoogleSignInApi.signOut(mGoogleApiClient);
- // mUsername = DEFAULT_NAME;
- // startActivity(new Intent(this, MainActivity.class));
- exitMenuDialog(); //диалог выхода из приложения
- return true;
- // for debug devs
- // case R.id.reconfig: // очистка кэша, только для девелоперов
- //fetchConfig();
- //return true;
- case R.id.spamreport:
- spamMenuDialog(); //диалог выбора отправки спам репорта
- return true;
- default:
- return super.onOptionsItemSelected(item);
- }
- }
- public void fonarMenu() { // обработчик нажатия
- try {
- if (isTorchOn) {
- turnOffFlashLight();
- isTorchOn = false;
- } else {
- turnOnFlashLight();
- isTorchOn = true;
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- private void spamMenuDialog() {
- final SharedPreferences prefs2=PreferenceManager.getDefaultSharedPreferences(this);//this==context
- if(!prefs2.contains("MessageSpam")) {
- AlertDialog.Builder alert = new AlertDialog.Builder(this);
- alert.setTitle("Пожаловаться");
- alert.setMessage(R.string.chat_report);
- alert.setPositiveButton("Нет", new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int whichButton) {
- }
- });
- alert.setNeutralButton("В ВКонтакте", new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int whichButton) {
- Intent intent = new
- Intent(Intent.ACTION_VIEW, Uri.parse("http://vk.com/pointapps"));
- startActivity(intent);
- }
- });
- alert.setNegativeButton("На EMAIL", new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int whichButton) {
- Intent intent = new Intent(Intent.ACTION_SEND);
- intent.setType("text/plain");
- intent.putExtra(Intent.EXTRA_EMAIL, "wevosu@gmail.com");
- intent.putExtra(Intent.EXTRA_SUBJECT, "Сообщение о нарушении/спаме в чате OpenDomofon PRO");
- intent.putExtra(Intent.EXTRA_TEXT, "");
- startActivity(Intent.createChooser(intent,"Выберите почтовый клиент для отправки email-сообщения"));
- }
- });
- alert.show();
- }
- }
- private void exitMenuDialog() {
- final SharedPreferences prefs2=PreferenceManager.getDefaultSharedPreferences(this);//this==context
- if(!prefs2.contains("ExitChat")) {
- AlertDialog.Builder alert = new AlertDialog.Builder(this);
- alert.setTitle("Выход из аккаунта");
- alert.setMessage("Вы действительно хотите выйти из аккаунта?");
- alert.setPositiveButton("Да", new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int whichButton) {
- mFirebaseAuth.signOut();
- Auth.GoogleSignInApi.signOut(mGoogleApiClient);
- mUsername = DEFAULT_NAME;
- Intent intent = new Intent(ChatActivity.this, MainActivity.class);
- startActivity(intent);
- }
- });
- alert.setNegativeButton("Нет", new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int whichButton) {
- }
- });
- alert.show();
- }
- }
- @Override
- public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
- Toast.makeText(this, "Google Play Services ошибка.", Toast.LENGTH_SHORT).show();
- }
- @Override
- public void onPostCreate(Bundle savedInstanceState) {
- super.onPostCreate(savedInstanceState);
- SwipeBackHelper.onPostCreate(this);
- }
- @Override
- public void onDestroy() {
- super.onDestroy();
- SwipeBackHelper.onDestroy(this);
- }
- public void turnOnFlashLight() {
- try {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
- mCameraManager.setTorchMode(mCameraId, true);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public void turnOffFlashLight() {
- try {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
- mCameraManager.setTorchMode(mCameraId, false);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement