Advertisement
Guest User

Untitled

a guest
Jul 1st, 2016
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 19.74 KB | None | 0 0
  1. package com.nearpeer.app;
  2.  
  3. /**
  4. *
  5. * Wifi-Direct based multi-user chat application
  6. *
  7. */
  8.  
  9. import java.util.Locale;
  10.  
  11. import android.annotation.SuppressLint;
  12. import android.app.ActionBar;
  13. import android.app.AlertDialog;
  14. import android.app.FragmentTransaction;
  15. import android.content.Context;
  16. import android.content.DialogInterface;
  17. import android.content.DialogInterface.OnCancelListener;
  18. import android.content.Intent;
  19. import android.content.SharedPreferences;
  20. import android.net.ConnectivityManager;
  21. import android.net.NetworkInfo;
  22. import android.net.wifi.WifiManager;
  23. import android.os.Bundle;
  24. import android.os.Handler;
  25. import android.os.Message;
  26. import android.provider.Settings.Secure;
  27. import android.support.v4.app.Fragment;
  28. import android.support.v4.app.FragmentActivity;
  29. import android.support.v4.app.FragmentManager;
  30. import android.support.v4.app.FragmentPagerAdapter;
  31. import android.support.v4.view.ViewPager;
  32. import android.view.Gravity;
  33. import android.view.LayoutInflater;
  34. import android.view.Menu;
  35. import android.view.MenuItem;
  36. import android.view.View;
  37. import android.view.View.OnClickListener;
  38. import android.widget.CheckBox;
  39. import android.widget.EditText;
  40. import android.widget.Toast;
  41.  
  42. import com.google.firebase.analytics.FirebaseAnalytics;
  43.  
  44. /**
  45. * The app's main entry point. Holds 2 fragments: {@link ChatSearchScreenFrag} and {@link ChatHistoryScreenFrag}.
  46. * The 1st fragment offers to scan for new chat groups and users. The 2nd offers to view chat history.
  47. */
  48. public class MainScreenActivity extends FragmentActivity implements ActionBar.TabListener
  49. {
  50. private AlertDialog mDialog=null;
  51. private OnClickListener AlertCheckBoxClickListener=null; //used to handle check-box click events for a dialog
  52.  
  53. SectionsPagerAdapter mSectionsPagerAdapter; //adapter for the tab view. Contains all the frags
  54. ViewPager mViewPager; //a layout widget in which each child view is a separate page (a separate tab) in the layout.
  55. //both fragment will initialize these references when they're created:
  56. public ChatHistoryScreenFrag mHistoryFrag = null;
  57. public ChatSearchScreenFrag mSearchFrag = null;
  58.  
  59. boolean isServiceStarted = false;
  60. boolean wasWifiDialogShown = false;
  61.  
  62. static int mDisplayedFragIndex = 0;
  63. public static long ChatRoomAccumulatingSerialNumber=0;
  64. public static String UniqueID=null;
  65. public static String UserName = ":>~"; //setting a default user name
  66. static boolean isToNotifyOnNewMsg = false; //defines if notifications should be shown on arrival of new messages
  67. static int RefreshPeriodInMs = 30000; //defines the peer refresh period
  68.  
  69. private boolean mIsRunForTheFirstTime=false;
  70.  
  71. @Override
  72. protected void onCreate(Bundle savedInstanceState)
  73. {
  74. super.onCreate(savedInstanceState);
  75. setContentView(R.layout.activity_main_screen);
  76.  
  77. //FirebaseAnalytics mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
  78.  
  79. /*Bundle bundle = new Bundle();
  80. bundle.putString(FirebaseAnalytics.Param.ITEM_ID, id);
  81. bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, name);
  82. bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "image");
  83. mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);*/
  84. try {
  85.  
  86. InitializeTabHandlerAndAdapter();
  87.  
  88. if (!isServiceStarted && ChatSearchScreenFrag.mService == null) {
  89. startService(new Intent(this, LocalService.class));
  90. isServiceStarted = true;
  91. }
  92.  
  93. getPrefs(); //get the shared prefs
  94.  
  95. //Happens only when the app is run for the very 1st time on a device
  96. if (MainScreenActivity.UniqueID == null) {
  97. UserName = new String(Secure.getString(getContentResolver(), Secure.ANDROID_ID)); //get a unique id
  98. UniqueID = new String(UserName);
  99. }//if
  100.  
  101. //Remove the title bar for out entire app
  102. getActionBar().setDisplayShowTitleEnabled(false);
  103. getActionBar().setDisplayShowHomeEnabled(false);
  104.  
  105. }catch (Exception e){
  106. Toast toast = Toast.makeText(getApplicationContext(), "Soory! Try after some time.",
  107. Toast.LENGTH_SHORT);
  108. toast.setGravity(Gravity.BOTTOM|Gravity.CENTER, 0, 10);
  109. toast.show();
  110. }
  111.  
  112. }//end of onCreate()
  113.  
  114. @Override
  115. protected void onResume()
  116. {
  117. super.onResume();
  118. //check if this activity was launched by the b-cast receiver after a wifi shutdown
  119.  
  120. try {
  121. boolean isToDisplayWifiDialog = getIntent()
  122. .getBooleanExtra(Constants.WIFI_BCAST_RCVR_WIFI_OFF_EVENT_INTENT_EXTRA_KEY, false);
  123.  
  124. if (isToDisplayWifiDialog && !wasWifiDialogShown) {
  125. new EnableWifiDirectDialog().show(getSupportFragmentManager(), "MyDialog"); //show a dialog
  126. wasWifiDialogShown = true;
  127. }
  128.  
  129. //if this app is run for the very 1st time, we want to launch the settings activity first.
  130. if (mIsRunForTheFirstTime) {
  131. //launch the preferences activity
  132. startActivity(new Intent(this, QuickPrefsActivity.class));
  133. mIsRunForTheFirstTime = false;
  134. }
  135. }catch (Exception e){
  136. Toast toast = Toast.makeText(getApplicationContext(), "Soory! Try after some time.",
  137. Toast.LENGTH_SHORT);
  138. toast.setGravity(Gravity.BOTTOM|Gravity.CENTER, 0, 10);
  139. toast.show();
  140. }
  141. }
  142.  
  143.  
  144. @Override
  145. protected void onPause()
  146. {
  147. super.onPause();
  148. savePrefs(); //save the preferences
  149. }//end of onPause()
  150.  
  151. private void InitializeTabHandlerAndAdapter()
  152. {
  153. // Set up the action bar (enable tab display).
  154. final ActionBar actionBar = getActionBar();
  155. actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
  156.  
  157. // Create the adapter that will return a fragment for each of the two
  158. // primary sections of the app.
  159. mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
  160.  
  161. // Set up the ViewPager with the sections adapter.
  162. mViewPager = (ViewPager) findViewById(R.id.pager);
  163. mViewPager.setAdapter(mSectionsPagerAdapter);
  164.  
  165. // When swiping between different sections, select the corresponding
  166. // tab. We can also use ActionBar.Tab#select() to do this if we have
  167. // a reference to the Tab.
  168. mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener()
  169. {
  170. @Override
  171. //if a tab was changed by a swipe gesture
  172. public void onPageSelected(int position) {
  173. actionBar.setSelectedNavigationItem(position); //update the tab bar to match the selected page
  174. mDisplayedFragIndex=position; //update the index of the currently displayed frag
  175. if (position==1) //if the view has moved to the history fragment:
  176. {
  177. mHistoryFrag.loadHistory(); //reload the history list view
  178. }
  179. invalidateOptionsMenu();
  180. }
  181. });
  182.  
  183. // For each of the sections in the app, add a tab to the action bar.
  184. for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++)
  185. {
  186. // Create a tab with text corresponding to the page title defined by
  187. // the adapter. Also specify this Activity object, which implements
  188. // the TabListener interface, as the callback (listener) for when
  189. // this tab is selected.
  190. actionBar.addTab(actionBar.newTab()
  191. .setText(mSectionsPagerAdapter.getPageTitle(i))
  192. .setTabListener(this));
  193. }//for
  194. }//end of InitializeTabHandlerAndAdapter()
  195.  
  196. /**
  197. * Used to modify menu item according to the app's state
  198. */
  199. @Override
  200. public boolean onPrepareOptionsMenu(Menu menu)
  201. {
  202. super.onPrepareOptionsMenu(menu);
  203.  
  204. //Check wifi state.
  205. ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
  206. NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
  207. WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
  208. if(mWifi.isConnected()||wifi.isWifiEnabled()) {
  209. ChatSearchScreenFrag.mIsWifiDirectEnabled = true;
  210.  
  211. }
  212.  
  213. //if the wifi-direct is disabled, we want to disable the chat room creation option
  214. menu.getItem(0).setEnabled(ChatSearchScreenFrag.mIsWifiDirectEnabled);
  215.  
  216. //if this menu is opened when the chat search is active:
  217. if (mDisplayedFragIndex==0)
  218. {
  219. //hide the 'delete history option:
  220. menu.findItem(R.id.action_delete_all_history).setVisible(false);
  221. }
  222. else //history frag is active:
  223. {
  224. //show the 'delete history option:
  225. menu.findItem(R.id.action_delete_all_history).setVisible(true);
  226. menu.findItem( R.id.clear_ignore_list).setVisible(false);
  227. }
  228.  
  229. return true;
  230. }
  231.  
  232.  
  233. @SuppressLint("HandlerLeak")
  234. Handler FirstTimeMenuUpdater = new Handler()
  235. {
  236. @Override
  237. public void handleMessage(Message msg)
  238. {
  239. MainScreenActivity.this.invalidateOptionsMenu();
  240. }
  241. };
  242.  
  243.  
  244. /**
  245. * Called only once when the app starts
  246. */
  247. @Override
  248. public boolean onCreateOptionsMenu(Menu menu)
  249. {
  250. // Inflate the menu; this adds items to the action bar if it is present.
  251. getMenuInflater().inflate(R.menu.main_screen_menu, menu);
  252.  
  253. FirstTimeMenuUpdater.sendEmptyMessageDelayed(0, 500);
  254.  
  255. return true;
  256. }//end of onCreateOptionsMenu()
  257.  
  258.  
  259. @Override
  260. public boolean onOptionsItemSelected(MenuItem item)
  261. {
  262. switch (item.getItemId())
  263. {
  264. case R.id.action_settings://setting was clicked
  265. {
  266. startActivity(new Intent(this, QuickPrefsActivity.class));
  267. break;
  268. }
  269. case R.id.action_create_new_chat_room: //exit app was clicked
  270. {
  271.  
  272. mDialog =CreatePublicChatCreationDialog();
  273. mDialog.show();
  274.  
  275. AlertCheckBoxClickListener= new OnClickListener()
  276. {
  277. @Override
  278. public void onClick(View v)
  279. {
  280.  
  281. AlertDialog dialog = MainScreenActivity.this.mDialog;
  282. EditText ed = (EditText) dialog.findViewById(R.id.choosePassword);
  283. boolean b= !ed.isEnabled();
  284. ed.setEnabled(b);
  285.  
  286. }
  287. };
  288.  
  289. CheckBox ch = (CheckBox) mDialog.findViewById(R.id.checkBoxSetPassword);
  290. ch.setOnClickListener(AlertCheckBoxClickListener);
  291. break;
  292. }
  293. case R.id.clear_ignore_list: //exit app was clicked
  294. {
  295. if (mSearchFrag!=null)
  296. mSearchFrag.ClearIgnoredUsersList();
  297. break;
  298. }
  299. case R.id.feedback: //exit app was clicked
  300. {
  301. startActivity(new Intent(this, FeedbackActivity.class));
  302. break;
  303. }
  304. case R.id.about: //exit app was clicked
  305. {
  306. startActivity(new Intent(this, AboutusActivity.class));
  307. break;
  308. }
  309. case R.id.action_exit: //exit app was clicked
  310. {
  311. kill();
  312. break;
  313. }
  314. case R.id.action_delete_all_history: //delete all history was clicked
  315. {
  316. mHistoryFrag.DeleteAllHistory();
  317. break;
  318. }
  319. }//switch
  320.  
  321. return true;
  322. }//end of onOptionsItemSelected()
  323.  
  324.  
  325. @Override
  326. public void onTabSelected(ActionBar.Tab tab,FragmentTransaction fragmentTransaction)
  327. {
  328. // When the given tab is selected, switch to the corresponding page in
  329. // the ViewPager.
  330. mViewPager.setCurrentItem(tab.getPosition());
  331. }//end of onTabSelected()
  332.  
  333. @Override
  334. public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction)
  335. {
  336. }
  337.  
  338. @Override
  339. public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction)
  340. {
  341. }
  342.  
  343. /**
  344. * A FragmentPagerAdapter that returns a fragment corresponding to
  345. * one of the sections/tabs/pages.
  346. */
  347. public class SectionsPagerAdapter extends FragmentPagerAdapter
  348. {
  349.  
  350. public SectionsPagerAdapter(FragmentManager fm)
  351. {
  352. super(fm);
  353. }
  354.  
  355. @Override
  356. public Fragment getItem(int position)
  357. {
  358. // getItem is called to instantiate the fragment for the given page.
  359. Fragment fragment=null; //will hold the relevant fragment to be returned
  360.  
  361. switch (position)
  362. {
  363. case 0:
  364. fragment = new ChatSearchScreenFrag(); //create a new chat search fragment
  365. break;
  366. case 1:
  367. fragment = new ChatHistoryScreenFrag(); //create a new history display fragment
  368. break;
  369. }
  370.  
  371. return fragment;
  372. }//end of getItem()
  373.  
  374. @Override
  375. public int getCount()
  376. {
  377. return 2; // Show 2 total pages.
  378. }
  379.  
  380. //Returns the title for each tab
  381. @Override
  382. public CharSequence getPageTitle(int position)
  383. {
  384. Locale l = Locale.getDefault();
  385. switch (position) {
  386. case 0:
  387. return getString(R.string.main_screen_tab1_title).toUpperCase(l);
  388. case 1:
  389. return getString(R.string.main_screen_tab2_title).toUpperCase(l);
  390. }
  391. return null;
  392. }
  393. }//end of class
  394.  
  395.  
  396.  
  397. /**
  398. * Called when the refresh button in the chat search fragment is clicked
  399. */
  400. public void onRefreshButtonClicked (View v)
  401. {
  402. mSearchFrag.onRefreshButtonClicked(v); //call the frag's method
  403. }//end of onRefreshButtonClicked()
  404.  
  405.  
  406. /**
  407. * Reads the saved preferences
  408. */
  409. protected void getPrefs()
  410. {
  411. SharedPreferences prefs = getPreferences(0);
  412. ChatRoomAccumulatingSerialNumber = prefs.getLong(Constants.SHARED_PREF_CHAT_ROOM_SERIAL_NUM, 0);
  413. UserName = prefs.getString(Constants.SHARED_PREF_USER_NAME, null);
  414. UniqueID = prefs.getString(Constants.SHARED_PREF_UNIQUE_ID, null);
  415. isToNotifyOnNewMsg = prefs.getBoolean(Constants.SHARED_PREF_ENABLE_NOTIFICATION, false);
  416. RefreshPeriodInMs = prefs.getInt(Constants.SHARED_PREF_REFRESH_PERIOD, 10000);
  417. mIsRunForTheFirstTime = prefs.getBoolean(Constants.SHARED_PREF_IS_FIRST_RUN, true);
  418. }//end of getPrefs(){
  419.  
  420. /**
  421. * Saved the shared preferences
  422. */
  423. protected void savePrefs()
  424. {
  425. SharedPreferences.Editor editor = getPreferences(0).edit();
  426. editor.putLong(Constants.SHARED_PREF_CHAT_ROOM_SERIAL_NUM, ChatRoomAccumulatingSerialNumber); //save to current SN
  427. editor.putString(Constants.SHARED_PREF_USER_NAME, UserName);
  428. editor.putString(Constants.SHARED_PREF_UNIQUE_ID, UniqueID);
  429. editor.putBoolean(Constants.SHARED_PREF_ENABLE_NOTIFICATION, isToNotifyOnNewMsg);
  430. editor.putInt(Constants.SHARED_PREF_REFRESH_PERIOD, RefreshPeriodInMs);
  431. editor.putBoolean(Constants.SHARED_PREF_IS_FIRST_RUN, false);
  432. editor.commit();
  433. }//end of savePrefs()
  434.  
  435. /**
  436. * Calls the kill() method of {@link ChatSearchScreenFrag}, resets all static variables,
  437. * calls the system's garbage collector and finishes.
  438. */
  439. public void kill(){
  440. savePrefs();
  441. mSearchFrag.kill(); //close the entire app (service and welcome socket)
  442.  
  443.  
  444. //we'de like to reset all static variables in our app:
  445. ChatActivity.mIsActive=false;
  446. ChatActivity.mMsgsWaitingForSendResult=null;
  447. ChatSearchScreenFrag.mService=null;
  448. ChatSearchScreenFrag.mIsWifiDirectEnabled=false;
  449. ChatSearchScreenFrag.mIsConnectedToGroup=false;
  450. ChatSearchScreenFrag.mManager = null;
  451. ChatSearchScreenFrag.mChannel = null;
  452. LocalService.mNotificationManager=null;
  453.  
  454. //Indicates to the VM that it would be a good time to run the garbage collector
  455. System.gc();
  456.  
  457. finish(); //close this activity
  458. }//kill()
  459.  
  460.  
  461. private AlertDialog CreatePublicChatCreationDialog()
  462. {
  463. // This example shows how to add a custom layout to an AlertDialog
  464. LayoutInflater factory = LayoutInflater.from(this);
  465. final View textEntryView = factory.inflate(R.layout.public_chat_creation_dialog, null);
  466. return new AlertDialog.Builder(this)
  467.  
  468. .setTitle("Create A New Room")
  469. .setView(textEntryView)
  470. .setIcon(R.drawable.settings_icon)
  471.  
  472. .setPositiveButton("OK", new DialogInterface.OnClickListener() {
  473. public void onClick(DialogInterface dialog, int whichButton) {
  474. boolean isPassword=false;
  475. String password="";
  476. String roomName=null;
  477.  
  478. EditText ed = (EditText) mDialog.findViewById(R.id.choosePassword);
  479.  
  480. //gets password if exists
  481. isPassword= ed.isEnabled();
  482. if(isPassword){password=ed.getText().toString();}
  483.  
  484. //gets rooms name
  485. ed = (EditText) mDialog.findViewById(R.id.chooseRoomsName);
  486. roomName=ed.getText().toString();
  487.  
  488. //if the room's name is invalid:
  489. if(roomName==null || roomName.length()<1){
  490. // pop alert dialog and reload this dialog
  491. new AlertDialog.Builder(MainScreenActivity.this)
  492. .setTitle("Missing name error")
  493. .setMessage("A room must have a name")
  494.  
  495. //yes button setter
  496. .setPositiveButton("OK", new DialogInterface.OnClickListener() {
  497. public void onClick(DialogInterface dialog, int which) {mDialog.show();}})//setPositive
  498.  
  499. .setOnCancelListener(new OnCancelListener(){
  500. public void onCancel(DialogInterface dialog){mDialog.show();}})
  501.  
  502. .show();
  503. //end of alert dialog
  504. }//if
  505.  
  506. else{//there is a room name
  507. //the room is ready to be created
  508. //call the service and create a new public chat room
  509. if (password.equalsIgnoreCase(""))
  510. password=null;
  511.  
  512. ChatSearchScreenFrag.mService.CreateNewHostedPublicChatRoom(roomName,password);
  513.  
  514. }//else
  515. }//onClick dialog listener
  516.  
  517.  
  518. })
  519. .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
  520. public void onClick(DialogInterface dialog, int whichButton) {}
  521.  
  522. }).create();
  523. }//end of ShowPublicChatCreationDialog()
  524.  
  525. }//end of class
  526.  
  527. [link][3]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement