Advertisement
Guest User

Untitled

a guest
Oct 1st, 2017
496
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 25.13 KB | None | 0 0
  1. package su.gamepoint.opendomofon.pro;
  2.  
  3. import android.content.Context;
  4. import android.content.DialogInterface;
  5. import android.content.Intent;
  6. import android.content.SharedPreferences;
  7. import android.content.pm.PackageManager;
  8. import android.graphics.Color;
  9. import android.hardware.Camera;
  10. import android.hardware.camera2.CameraAccessException;
  11. import android.hardware.camera2.CameraManager;
  12. import android.net.Uri;
  13. import android.os.Build;
  14. import android.os.Bundle;
  15. import android.preference.PreferenceManager;
  16. import android.support.annotation.NonNull;
  17. import android.support.v4.content.ContextCompat;
  18. import android.support.v7.app.AlertDialog;
  19. import android.support.v7.app.AppCompatActivity;
  20. import android.support.v7.widget.LinearLayoutManager;
  21. import android.support.v7.widget.RecyclerView;
  22. import android.support.v7.widget.Toolbar;
  23. import android.text.Editable;
  24. import android.text.TextWatcher;
  25. import android.text.format.DateFormat;
  26. import android.view.Menu;
  27. import android.view.MenuInflater;
  28. import android.view.MenuItem;
  29. import android.view.View;
  30. import android.widget.EditText;
  31. import android.widget.ImageView;
  32. import android.widget.ProgressBar;
  33. import android.widget.TextView;
  34. import android.widget.Toast;
  35.  
  36. import com.bumptech.glide.Glide;
  37. import com.firebase.ui.database.FirebaseRecyclerAdapter;
  38. import com.google.android.gms.appindexing.Action;
  39. import com.google.android.gms.appindexing.AppIndex;
  40. import com.google.android.gms.auth.api.Auth;
  41. import com.google.android.gms.common.ConnectionResult;
  42. import com.google.android.gms.common.api.GoogleApiClient;
  43. import com.google.android.gms.tasks.OnFailureListener;
  44. import com.google.android.gms.tasks.OnSuccessListener;
  45. import com.google.firebase.auth.FirebaseAuth;
  46. import com.google.firebase.auth.FirebaseUser;
  47. import com.google.firebase.database.DatabaseReference;
  48. import com.google.firebase.database.FirebaseDatabase;
  49. import com.google.firebase.remoteconfig.FirebaseRemoteConfig;
  50. import com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings;
  51. import com.jude.swipbackhelper.SwipeBackHelper;
  52.  
  53. import java.util.HashMap;
  54. import java.util.Map;
  55.  
  56. import de.hdodenhof.circleimageview.CircleImageView;
  57. import hani.momanii.supernova_emoji_library.Actions.EmojIconActions;
  58. import hani.momanii.supernova_emoji_library.Helper.EmojiconEditText;
  59.  
  60. import static su.gamepoint.opendomofon.pro.R.id.fonarik;
  61.  
  62.  
  63. public class ChatActivity extends AppCompatActivity
  64. implements GoogleApiClient.OnConnectionFailedListener {
  65.  
  66. private int SETTINGS_ACTION = 1;
  67. boolean hasFlash = false; // флаг поддержки устройством камеры
  68. private Camera camera;
  69. private DatabaseReference mSimpleFirechatDatabaseReference;
  70. public FirebaseRecyclerAdapter<ChatMessage, FirechatMsgViewHolder>
  71. mFirebaseAdapter;
  72. private ImageView mSendButton;
  73. private RecyclerView mMessageRecyclerView;
  74. //private LinearLayoutManager mLinearLayoutManager;
  75. private ProgressBar mProgressBar;
  76. private EditText mMsgEditText;
  77. private SharedPreferences mSharedPreferences;
  78. public static final String DEFAULT_NAME = "PointApps";
  79. private String mUsername;
  80. private String mPhotoUrl;
  81. private GoogleApiClient mGoogleApiClient;
  82. private FirebaseAuth mFirebaseAuth;
  83. private FirebaseUser mFirechatUser;
  84.  
  85. private FirebaseRemoteConfig mFirebaseRemoteConfig;
  86.  
  87. //Фонарь
  88. private CameraManager mCameraManager;
  89. private String mCameraId;
  90. private Boolean isTorchOn;
  91.  
  92.  
  93. //Views UI
  94. private RecyclerView rvListMessage;
  95. private LinearLayoutManager mLinearLayoutManager;
  96. private ImageView btSendMessage,btEmoji;
  97. private EmojiconEditText edMessage;
  98. private View contentRoot;
  99. private EmojIconActions emojIcon;
  100. @Override
  101. public void onStart() {
  102. super.onStart();
  103.  
  104. // ATTENTION: This was auto-generated to implement the App Indexing API.
  105. // See https://g.co/AppIndexing/AndroidStudio for more information.
  106. mGoogleApiClient.connect();
  107. Action viewAction = Action.newAction(
  108. Action.TYPE_VIEW, // TODO: choose an action type.
  109. "Main Page", // TODO: Define a title for the content shown.
  110. // TODO: If you have web page content that matches this app activity's content,
  111. // make sure this auto-generated web page URL is correct.
  112. // Otherwise, set the URL to null.
  113. Uri.parse("http://host/path"),
  114. // TODO: Make sure this auto-generated app URL is correct.
  115. Uri.parse("android-app://su.gamepoint.opendomofon.pro/http/host/path")
  116. );
  117. AppIndex.AppIndexApi.start(mGoogleApiClient, viewAction);
  118. }
  119.  
  120. @Override
  121. public void onStop() {
  122. super.onStop();
  123.  
  124. // ATTENTION: This was auto-generated to implement the App Indexing API.
  125. // See https://g.co/AppIndexing/AndroidStudio for more information.
  126. Action viewAction = Action.newAction(
  127. Action.TYPE_VIEW, // TODO: choose an action type.
  128. "Main Page", // TODO: Define a title for the content shown.
  129. // TODO: If you have web page content that matches this app activity's content,
  130. // make sure this auto-generated web page URL is correct.
  131. // Otherwise, set the URL to null.
  132. Uri.parse("http://host/path"),
  133. // TODO: Make sure this auto-generated app URL is correct.
  134. Uri.parse("android-app://su.gamepoint.opendomofon.pro/http/host/path")
  135. );
  136. AppIndex.AppIndexApi.end(mGoogleApiClient, viewAction);
  137. mGoogleApiClient.disconnect();
  138. }
  139.  
  140. public static class FirechatMsgViewHolder extends RecyclerView.ViewHolder {
  141. public TextView msgTextView;
  142. public TextView userTextView;
  143. public CircleImageView userImageView;
  144. public TextView timeTextView;
  145.  
  146. public FirechatMsgViewHolder(View v) {
  147. super(v);
  148. msgTextView = (TextView) itemView.findViewById(R.id.msgTextView);
  149. userTextView = (TextView) itemView.findViewById(R.id.userTextView);
  150. userImageView = (CircleImageView) itemView.findViewById(R.id.userImageView);
  151. timeTextView = (TextView) itemView.findViewById(R.id.timeTextView);
  152. }
  153. }
  154.  
  155. @Override
  156. public void onCreate(Bundle savedInstanceState) {
  157. SharedPreferences pref3 = PreferenceManager
  158. .getDefaultSharedPreferences(this);
  159. String themeName3 = pref3.getString("theme3", "Стандартная");
  160. if (themeName3.equals("Стандартная")) {
  161. setTheme(R.style.AppThemeDrawer);
  162.  
  163. } else if (themeName3.equals("Тёмная")) {
  164.  
  165. setTheme(R.style.Theme2);
  166. } else if (themeName3.equals("Синяя")) {
  167.  
  168. setTheme(R.style.ThemeBlue);
  169. } else if (themeName3.equals("Тёмно-синяя")) {
  170.  
  171. setTheme(R.style.ThemeBlueBlack);
  172. } else if (themeName3.equals("Красная")) {
  173.  
  174. setTheme(R.style.ThemeRed);
  175. } else if (themeName3.equals("Тёмно-красная")) {
  176.  
  177. setTheme(R.style.ThemeRedBlack);
  178. }
  179. super.onCreate(savedInstanceState);
  180. setContentView(R.layout.activity_chat);
  181.  
  182. isTorchOn = false;// фонарь
  183.  
  184. SwipeBackHelper.onCreate(this);
  185. SharedPreferences pref11 = PreferenceManager
  186. .getDefaultSharedPreferences(this);
  187. String themeName11 = pref11.getString("theme11", "Включить");
  188. if (themeName11.equals("Включить")) {
  189. SwipeBackHelper.getCurrentPage(this)//get current instance
  190. .setSwipeBackEnable(true)
  191. .setScrimColor(Color.WHITE);//on-off
  192.  
  193.  
  194.  
  195.  
  196. } else if (themeName11.equals("Выключить")) {
  197. SwipeBackHelper.getCurrentPage(this)//get current instance
  198. .setSwipeBackEnable(true)//on-off
  199. .setScrimColor(Color.WHITE)//on-off
  200. .setSwipeEdge(0);
  201. }
  202.  
  203. mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
  204. mUsername = DEFAULT_NAME;
  205.  
  206. Boolean isFlashAvailable = getApplicationContext().getPackageManager()
  207. .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
  208.  
  209. if (!isFlashAvailable) {
  210.  
  211. AlertDialog alert = new AlertDialog.Builder(ChatActivity.this)
  212. .create();
  213. alert.setTitle("Ошибка!");
  214. alert.setMessage("Ваше устройство не поддерживает встроенный фонарик!");
  215. alert.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
  216. public void onClick(DialogInterface dialog, int which) {
  217. // closing the application
  218. finish();
  219. System.exit(0);
  220. }
  221. });
  222. alert.show();
  223. return;
  224. }
  225.  
  226. mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
  227. try {
  228. mCameraId = mCameraManager.getCameraIdList()[0];
  229. } catch (CameraAccessException e) {
  230. e.printStackTrace();
  231. }
  232. //Подсказка на меню
  233.  
  234.  
  235.  
  236.  
  237.  
  238.  
  239. TextView textView = (TextView) findViewById(R.id.msgTextView);
  240.  
  241. btEmoji = (ImageView)findViewById(R.id.buttonEmoji);
  242. btEmoji = (ImageView)findViewById(R.id.buttonEmoji);
  243. edMessage = (EmojiconEditText)findViewById(R.id.msgEditText);
  244. contentRoot = findViewById(R.id.contentRoot);
  245. EmojIconActions emojIcon=new EmojIconActions(this,contentRoot,edMessage,btEmoji);
  246. emojIcon.ShowEmojIcon();
  247.  
  248.  
  249. // Initialize ProgressBar and RecyclerView.
  250. mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
  251. mMessageRecyclerView = (RecyclerView) findViewById(R.id.messageRecyclerView);
  252. mLinearLayoutManager = new LinearLayoutManager(this);
  253. mLinearLayoutManager.setStackFromEnd(true);
  254. mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
  255. // инклюдим тулбар
  256. Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
  257. setSupportActionBar(toolbar);
  258. getSupportActionBar().setDisplayHomeAsUpEnabled(true);
  259.  
  260. //mProgressBar.setVisibility(ProgressBar.INVISIBLE);
  261.  
  262. mMsgEditText = (EditText) findViewById(R.id.msgEditText);
  263. //mMessageEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(mSharedPreferences
  264. // .getInt(CodelabPreferences.FRIENDLY_MSG_LENGTH, DEFAULT_MSG_LENGTH_LIMIT))});
  265.  
  266. mMsgEditText.addTextChangedListener(new TextWatcher() {
  267. @Override
  268. public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
  269. }
  270.  
  271. @Override
  272. public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
  273. if (charSequence.toString().trim().length() > 0) {
  274. mSendButton.setEnabled(true);
  275. } else {
  276. mSendButton.setEnabled(false);
  277. }
  278. }
  279.  
  280. @Override
  281. public void afterTextChanged(Editable editable) {
  282. }
  283. });
  284.  
  285. mSendButton = (ImageView) findViewById(R.id.sendButton);
  286. mSendButton.setOnClickListener(new View.OnClickListener() {
  287. @Override
  288. public void onClick(View view) {
  289. ChatMessage friendlyMessage = new
  290. ChatMessage(mMsgEditText.getText().toString(),
  291. mUsername,
  292. mPhotoUrl);
  293. mSimpleFirechatDatabaseReference.child("messages")
  294. .push().setValue(friendlyMessage);
  295. mMsgEditText.setText("");
  296. }
  297. });
  298. mSimpleFirechatDatabaseReference = FirebaseDatabase.getInstance().getReference();
  299. mFirebaseAdapter = new FirebaseRecyclerAdapter<ChatMessage,
  300. FirechatMsgViewHolder>(
  301. ChatMessage.class,
  302. R.layout.chat_message,
  303. FirechatMsgViewHolder.class,
  304. mSimpleFirechatDatabaseReference.child("messages")) {
  305.  
  306. @Override
  307. public void populateViewHolder(FirechatMsgViewHolder viewHolder,
  308. ChatMessage friendlyMessage, int position) {
  309. mProgressBar.setVisibility(ProgressBar.INVISIBLE);
  310. viewHolder.msgTextView.setText(friendlyMessage.getText());
  311. viewHolder.userTextView.setText(friendlyMessage.getName());
  312. viewHolder.timeTextView.setText(DateFormat.format("dd-MM-yyyy ( в HH:mm:ss)", friendlyMessage.getTimeMessage()));
  313. if (friendlyMessage.getPhotoUrl() == null) {
  314. viewHolder.userImageView
  315. .setImageDrawable(ContextCompat
  316. .getDrawable(ChatActivity.this,
  317. R.drawable.ic_account_circle_black_36dp));
  318. } else {
  319. Glide.with(ChatActivity.this)
  320. .load(friendlyMessage.getPhotoUrl())
  321. .into(viewHolder.userImageView);
  322. }
  323. }
  324. };
  325.  
  326. mFirebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
  327. @Override
  328. public void onItemRangeInserted(int positionStart, int itemCount) {
  329. super.onItemRangeInserted(positionStart, itemCount);
  330. int friendlyMessageCount = mFirebaseAdapter.getItemCount();
  331. int lastVisiblePosition =
  332. mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
  333. // If the recycler view is initially being loaded or the
  334. // user is at the bottom of the list, scroll to the bottom
  335. // of the list to show the newly added message.
  336. if (lastVisiblePosition == -1 ||
  337. (positionStart >= (friendlyMessageCount - 1) &&
  338. lastVisiblePosition == (positionStart - 1))) {
  339. mMessageRecyclerView.scrollToPosition(positionStart);
  340. }
  341. }
  342. });
  343.  
  344. mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
  345. mMessageRecyclerView.setAdapter(mFirebaseAdapter);
  346.  
  347. // ATTENTION: This "addApi(AppIndex.API)"was auto-generated to implement the App Indexing API.
  348. // See https://g.co/AppIndexing/AndroidStudio for more information.
  349. mGoogleApiClient = new GoogleApiClient.Builder(this)
  350. .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
  351. .addApi(Auth.GOOGLE_SIGN_IN_API)
  352. .addApi(AppIndex.API).build();
  353. mFirebaseAuth = FirebaseAuth.getInstance();
  354. mFirechatUser = mFirebaseAuth.getCurrentUser();
  355. if (mFirechatUser == null) {
  356. startActivity(new Intent(this, AuthorizationActivity.class));
  357. finish();
  358. return;
  359. } else {
  360. mUsername = mFirechatUser.getDisplayName();
  361. if (mFirechatUser.getPhotoUrl() != null) {
  362. mPhotoUrl = mFirechatUser.getPhotoUrl().toString();
  363. }
  364. }
  365.  
  366. mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
  367.  
  368. FirebaseRemoteConfigSettings firebaseRemoteConfigSettings =
  369. new FirebaseRemoteConfigSettings.Builder()
  370. .setDeveloperModeEnabled(true)
  371. .build();
  372.  
  373. Map<String, Object> defaultConfigMap = new HashMap<>();
  374. defaultConfigMap.put("button_name", "");
  375.  
  376. mFirebaseRemoteConfig.setConfigSettings(firebaseRemoteConfigSettings);
  377. mFirebaseRemoteConfig.setDefaults(defaultConfigMap);
  378.  
  379. fetchConfig();
  380. }
  381.  
  382.  
  383.  
  384. public void fetchConfig() {
  385. long cacheExpiration = 3600; // 1 hour in seconds
  386. // If developer mode is enabled reduce cacheExpiration to 0 so that
  387. // each fetch goes to the server. This should not be used in release
  388. // builds.
  389. if (mFirebaseRemoteConfig.getInfo().getConfigSettings()
  390. .isDeveloperModeEnabled()) {
  391. cacheExpiration = 0;
  392. }
  393. mFirebaseRemoteConfig.fetch(cacheExpiration)
  394. .addOnSuccessListener(new OnSuccessListener<Void>() {
  395. @Override
  396. public void onSuccess(Void aVoid) {
  397. // Make the fetched config available via
  398. // FirebaseRemoteConfig get<type> calls.
  399. mFirebaseRemoteConfig.activateFetched();
  400. //mSendButton.setText(mFirebaseRemoteConfig.getString("button_name"));
  401. }
  402. })
  403. .addOnFailureListener(new OnFailureListener() {
  404. @Override
  405. public void onFailure(@NonNull Exception e) {
  406. //mSendButton.setText(mFirebaseRemoteConfig.getString("button_name"));
  407. }
  408. });
  409. }
  410.  
  411.  
  412. @Override
  413. public boolean onCreateOptionsMenu(Menu menu) {
  414. MenuInflater inflater = getMenuInflater();
  415. inflater.inflate(R.menu.chat_menu, menu);
  416. return true;
  417. }
  418.  
  419. @Override
  420. public boolean onOptionsItemSelected(MenuItem item) {
  421. switch (item.getItemId()) {
  422. case fonarik:
  423. fonarMenu(); // вкл выкл фонарика
  424. return true;
  425. case R.id.sign_out_menu:
  426. // mFirebaseAuth.signOut();
  427. // Auth.GoogleSignInApi.signOut(mGoogleApiClient);
  428. // mUsername = DEFAULT_NAME;
  429. // startActivity(new Intent(this, MainActivity.class));
  430.  
  431. exitMenuDialog(); //диалог выхода из приложения
  432. return true;
  433. // for debug devs
  434. // case R.id.reconfig: // очистка кэша, только для девелоперов
  435. //fetchConfig();
  436. //return true;
  437. case R.id.spamreport:
  438. spamMenuDialog(); //диалог выбора отправки спам репорта
  439. return true;
  440. default:
  441. return super.onOptionsItemSelected(item);
  442. }
  443. }
  444. public void fonarMenu() { // обработчик нажатия
  445. try {
  446. if (isTorchOn) {
  447. turnOffFlashLight();
  448. isTorchOn = false;
  449. } else {
  450. turnOnFlashLight();
  451. isTorchOn = true;
  452. }
  453. } catch (Exception e) {
  454. e.printStackTrace();
  455. }
  456. }
  457. private void spamMenuDialog() {
  458. final SharedPreferences prefs2=PreferenceManager.getDefaultSharedPreferences(this);//this==context
  459. if(!prefs2.contains("MessageSpam")) {
  460. AlertDialog.Builder alert = new AlertDialog.Builder(this);
  461. alert.setTitle("Пожаловаться");
  462.  
  463. alert.setMessage(R.string.chat_report);
  464.  
  465. alert.setPositiveButton("Нет", new DialogInterface.OnClickListener() {
  466. public void onClick(DialogInterface dialog, int whichButton) {
  467.  
  468. }
  469. });
  470. alert.setNeutralButton("В ВКонтакте", new DialogInterface.OnClickListener() {
  471. public void onClick(DialogInterface dialog, int whichButton) {
  472. Intent intent = new
  473. Intent(Intent.ACTION_VIEW, Uri.parse("http://vk.com/pointapps"));
  474. startActivity(intent);
  475. }
  476. });
  477. alert.setNegativeButton("На EMAIL", new DialogInterface.OnClickListener() {
  478. public void onClick(DialogInterface dialog, int whichButton) {
  479. Intent intent = new Intent(Intent.ACTION_SEND);
  480. intent.setType("text/plain");
  481. intent.putExtra(Intent.EXTRA_EMAIL, "wevosu@gmail.com");
  482. intent.putExtra(Intent.EXTRA_SUBJECT, "Сообщение о нарушении/спаме в чате OpenDomofon PRO");
  483. intent.putExtra(Intent.EXTRA_TEXT, "");
  484.  
  485. startActivity(Intent.createChooser(intent,"Выберите почтовый клиент для отправки email-сообщения"));
  486. }
  487. });
  488.  
  489. alert.show();
  490. }
  491. }
  492. private void exitMenuDialog() {
  493. final SharedPreferences prefs2=PreferenceManager.getDefaultSharedPreferences(this);//this==context
  494. if(!prefs2.contains("ExitChat")) {
  495. AlertDialog.Builder alert = new AlertDialog.Builder(this);
  496. alert.setTitle("Выход из аккаунта");
  497.  
  498. alert.setMessage("Вы действительно хотите выйти из аккаунта?");
  499.  
  500. alert.setPositiveButton("Да", new DialogInterface.OnClickListener() {
  501. public void onClick(DialogInterface dialog, int whichButton) {
  502. mFirebaseAuth.signOut();
  503. Auth.GoogleSignInApi.signOut(mGoogleApiClient);
  504. mUsername = DEFAULT_NAME;
  505. Intent intent = new Intent(ChatActivity.this, MainActivity.class);
  506. startActivity(intent);
  507. }
  508. });
  509. alert.setNegativeButton("Нет", new DialogInterface.OnClickListener() {
  510. public void onClick(DialogInterface dialog, int whichButton) {
  511.  
  512. }
  513. });
  514.  
  515. alert.show();
  516. }
  517. }
  518. @Override
  519. public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
  520. Toast.makeText(this, "Google Play Services ошибка.", Toast.LENGTH_SHORT).show();
  521. }
  522.  
  523. @Override
  524. public void onPostCreate(Bundle savedInstanceState) {
  525. super.onPostCreate(savedInstanceState);
  526. SwipeBackHelper.onPostCreate(this);
  527. }
  528.  
  529. @Override
  530. public void onDestroy() {
  531. super.onDestroy();
  532. SwipeBackHelper.onDestroy(this);
  533. }
  534.  
  535.  
  536. public void turnOnFlashLight() {
  537.  
  538. try {
  539. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  540. mCameraManager.setTorchMode(mCameraId, true);
  541. }
  542. } catch (Exception e) {
  543. e.printStackTrace();
  544. }
  545. }
  546.  
  547.  
  548. public void turnOffFlashLight() {
  549.  
  550. try {
  551. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  552. mCameraManager.setTorchMode(mCameraId, false);
  553. }
  554.  
  555. } catch (Exception e) {
  556. e.printStackTrace();
  557. }
  558. }
  559. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement