Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MainActivity extends AppCompatActivity implements View.OnClickListener,
- ViewPagerFragment.OnViewPagerUpdatePositionListener,
- PrivacyDialogFragment.OnApplyFragmentListener,
- ChangePasswordDialogFragment.OnSaveFragmentListener,
- CustomViewPager.OnSwipeOutListener,
- MapListFragment.OnMapListClickListener,
- MapContainerFragment.OnZoomInToSelectedLocationListener,
- GoogleApiClient.ConnectionCallbacks,
- GoogleApiClient.OnConnectionFailedListener,
- LocationListener,
- ResultCallback<LocationSettingsResult> {
- private DrawerLayout drawerLayout;
- private ScrimInsetsFrameLayout rightDrawer;
- private RoundedImageView profileImage;
- private DisplayImageOptions options;
- private RelativeLayout logoutPlaceholder, profilePlaceholder, settingsPLaceholder, passwordPlaceholder, invitePlaceholder;
- protected static final int CAMERA_REQUEST_CODE = 1;
- protected static final int GALLERY_REQUEST_CODE = 2;
- private String picturePath;
- private static final int PLACE_PICKER_REQUEST = 5;
- private Place place;
- private Button backButton, doneButton;
- private ArrayList<FishLocation> arrayList;
- private ViewPagerFragment viewPagerFragment = null;
- //Google API Location-Aware
- public static final int REQUEST_CHECK_SETTINGS = 0x99;
- //Location-aware variable
- public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 300000;
- public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
- UPDATE_INTERVAL_IN_MILLISECONDS / 2;
- protected final static String KEY_REQUESTING_LOCATION_UPDATES = "requesting-location-updates";
- protected final static String KEY_LOCATION = "location";
- protected final static String KEY_LAST_UPDATED_TIME_STRING = "last-updated-time-string";
- protected GoogleApiClient mGoogleApiClient;
- protected Location mCurrentLocation = null;
- protected LocationSettingsRequest mLocationSettingsRequest;
- protected Boolean mRequestingLocationUpdates = true;
- public static final int MY_PERMISSION_REQUEST_LOCATION_ACCESS = 101;
- protected final static String REQUESTING_LOCATION_UPDATES_KEY = "requesting-location-updates-key";
- protected final static String LOCATION_KEY = "location-key";
- protected LocationRequest mLocationRequest;
- public static final String TAG = "LocationManager";
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- if (!isNetworkAvailable()) {
- Toast.makeText(MainActivity.this, "No Internet Connection", Toast.LENGTH_LONG).show();
- }
- updateValuesFromBundle(savedInstanceState);
- initView();
- buildGoogleApiClient();
- createLocationRequest();
- buildLocationSettingsRequest();
- }
- @Override
- public void onStart() {
- super.onStart();
- mGoogleApiClient.connect();
- Branch branch = Branch.getInstance();
- branch.initSession(new Branch.BranchReferralInitListener() {
- @Override
- public void onInitFinished(JSONObject referringParams, BranchError error) {
- if (error == null) {
- // params are the deep linked params associated with the link that the user clicked before showing up
- Log.i("BranchConfigTest", "deep link data: " + referringParams.toString());
- }
- }
- }, this.getIntent().getData(), this);
- }
- @Override
- public void onNewIntent(Intent intent) {
- this.setIntent(intent);
- }
- public void onSaveInstanceState(Bundle savedInstanceState) {
- savedInstanceState.putBoolean(REQUESTING_LOCATION_UPDATES_KEY, mRequestingLocationUpdates);
- savedInstanceState.putParcelable(LOCATION_KEY, mCurrentLocation);
- super.onSaveInstanceState(savedInstanceState);
- }
- private void updateValuesFromBundle(Bundle savedInstanceState) {
- if (savedInstanceState != null) {
- // Update the value of mRequestingLocationUpdates from the Bundle, and make sure that
- // the Start Updates and Stop Updates buttons are correctly enabled or disabled.
- if (savedInstanceState.keySet().contains(REQUESTING_LOCATION_UPDATES_KEY)) {
- mRequestingLocationUpdates = savedInstanceState.getBoolean(
- REQUESTING_LOCATION_UPDATES_KEY);
- }
- // Update the value of mCurrentLocation from the Bundle and update the UI to show the
- // correct latitude and longitude.
- if (savedInstanceState.keySet().contains(LOCATION_KEY)) {
- // Since LOCATION_KEY was found in the Bundle, we can be sure that mCurrentLocation
- // is not null.
- mCurrentLocation = savedInstanceState.getParcelable(LOCATION_KEY);
- }
- updateLocationUI();
- }
- }
- private void updateLocationUI() {
- if (mCurrentLocation != null) {
- Log.i("CurrentLocation", mCurrentLocation.getLatitude()+"," + mCurrentLocation.getLongitude());
- getApiFishingLocation(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
- }
- }
- protected void stopLocationUpdates() {
- // It is a good practice to remove location requests when the activity is in a paused or
- // stopped state. Doing so helps battery performance and is especially
- // recommended in applications that request frequent location updates.
- // The final argument to {@code requestLocationUpdates()} is a LocationListener
- // (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
- LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
- }
- private void initView() {
- LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- drawerLayout = (DrawerLayout) inflater.inflate(R.layout.decor_layout, null); // "null" is important.
- rightDrawer = (ScrimInsetsFrameLayout) drawerLayout.findViewById(R.id.right_drawer);
- profileImage = (RoundedImageView) drawerLayout.findViewById(R.id.profileImage);
- profileImage.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- //selectImage();
- }
- });
- profilePlaceholder = (RelativeLayout) drawerLayout.findViewById(R.id.profile_placeholder);
- settingsPLaceholder = (RelativeLayout) drawerLayout.findViewById(R.id.settings_placeholder);
- passwordPlaceholder = (RelativeLayout) drawerLayout.findViewById(R.id.password_placeholder);
- invitePlaceholder = (RelativeLayout) drawerLayout.findViewById(R.id.invite_placeholder);
- logoutPlaceholder = (RelativeLayout) drawerLayout.findViewById(R.id.logoutPlaceholder);
- logoutPlaceholder.setOnClickListener(this);
- profilePlaceholder.setOnClickListener(this);
- settingsPLaceholder.setOnClickListener(this);
- passwordPlaceholder.setOnClickListener(this);
- invitePlaceholder.setOnClickListener(this);
- initNavBar(drawerLayout);
- options = new DisplayImageOptions.Builder()
- .cacheInMemory(false)
- .cacheOnDisk(true)
- .showImageOnLoading(R.drawable.default_avatar)
- .showImageForEmptyUri(R.drawable.default_avatar)
- .showImageOnFail(R.drawable.default_avatar)
- .considerExifParams(true)
- .bitmapConfig(Bitmap.Config.RGB_565)
- .build();
- //This is where magic happened.
- stealFirstView(drawerLayout);
- // if(mSimpleFacebook.isLogin())
- // ImageLoader.getInstance().displayImage(AppController.getInstance().getFbProfileImage(), profileImage, options);
- // else
- ImageLoader.getInstance().displayImage(AppController.getInstance().getAvatarUrl(), profileImage, options);
- viewPagerFragment = new ViewPagerFragment();
- getSupportFragmentManager()
- .beginTransaction()
- .replace(R.id.mainContent, viewPagerFragment)
- .commit();
- }
- public int getStatusBarHeight() {
- int result = 0;
- int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
- if (resourceId > 0) {
- result = getResources().getDimensionPixelSize(resourceId);
- }
- return result;
- }
- private void initNavBar(View view) {
- backButton = (Button) view.findViewById(R.id.backBtn);
- doneButton = (Button) view.findViewById(R.id.doneBtn);
- //styling the navigation button
- doneButton.setVisibility(View.VISIBLE);
- doneButton.setBackground(getResources().getDrawable(R.drawable.menu_drawer));
- backButton.setVisibility(View.INVISIBLE);
- backButton.setBackground(getResources().getDrawable(R.drawable.back_icon));
- backButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- }
- });
- doneButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- //TODO
- if (drawerLayout.isDrawerOpen(rightDrawer)) {
- drawerLayout.closeDrawer(rightDrawer);
- } else {
- drawerLayout.openDrawer(rightDrawer);
- }
- }
- });
- }
- public float dpTopxConverter(int dp) {
- Resources r = getResources();
- return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics());
- }
- //This is hack to steal first view to allow drawer to slide on top of actionBar/Toolbar without using design material
- public void stealFirstView(DrawerLayout drawer) {
- ViewGroup decor = (ViewGroup) getWindow().getDecorView();
- View child = decor.getChildAt(0);
- decor.removeView(child);
- LinearLayout mainContainer = (LinearLayout) drawer.findViewById(R.id.mainPlaceholer); // This is the container we defined just now.
- mainContainer.addView(child);
- ViewGroup.LayoutParams lp = ((ViewGroup) mainContainer).getLayoutParams();
- if (lp instanceof ViewGroup.MarginLayoutParams) {
- ((ViewGroup.MarginLayoutParams) lp).topMargin = getStatusBarHeight();
- }
- // Make the drawer replace the first child
- decor.addView(drawer);
- }
- @Override
- public void onSwipeOutAtStart() {
- }
- @Override
- public void onSwipeOutAtEnd() {
- if (drawerLayout.isDrawerOpen(rightDrawer)) {
- drawerLayout.closeDrawer(rightDrawer);
- } else {
- drawerLayout.openDrawer(rightDrawer);
- }
- }
- public int getDensity(Context context) {
- DisplayMetrics metrics = context.getResources().getDisplayMetrics();
- return (int) metrics.density;
- }
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- switch (requestCode) {
- case CAMERA_REQUEST_CODE:
- switch (resultCode) {
- case RESULT_OK:
- File file = new File(picturePath);
- if (file.exists()) {
- uploadProfilePicture(picturePath);
- }
- else{
- uploadProfilePicture(picturePath);
- }
- break;
- case RESULT_CANCELED:
- break;
- }
- break;
- case GALLERY_REQUEST_CODE:
- switch (resultCode) {
- case RESULT_OK:
- try {
- Uri selectedImage = data.getData();
- String[] filePath = {MediaStore.Images.Media.DATA};
- Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
- c.moveToFirst();
- int columnIndex = c.getColumnIndex(filePath[0]);
- picturePath = c.getString(columnIndex);
- c.close();
- uploadProfilePicture(picturePath);
- } catch (Exception e) {
- // TODO: handle exception
- }
- break;
- case RESULT_CANCELED:
- break;
- }
- break;
- case PLACE_PICKER_REQUEST:
- switch (resultCode) {
- case RESULT_OK:
- place = PlacePicker.getPlace(data, this);
- popupDialog();
- break;
- case RESULT_CANCELED:
- break;
- }
- break;
- case REQUEST_CHECK_SETTINGS:
- switch (resultCode) {
- case RESULT_OK:
- startLocationUpdate();
- break;
- case RESULT_CANCELED:
- break;
- }
- break;
- }
- super.onActivityResult(requestCode, resultCode, data);
- }
- private void selectImage() {
- final CharSequence[] options = {getResources().getString(R.string.take_photo), getResources().getString(R.string.choose_gallery), getResources().getString(R.string.cancel)};
- AlertDialog.Builder builder = new AlertDialog.Builder(this);
- builder.setTitle(getResources().getString(R.string.add_photo));
- builder.setItems(options, new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int item) {
- if (options[item].equals(getResources().getString(R.string.take_photo))) {
- Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
- File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
- Environment.DIRECTORY_PICTURES), "FishTalk");
- File f = new File(mediaStorageDir, String.valueOf(System.currentTimeMillis()) + ".jpg");
- picturePath = f.getAbsolutePath();
- intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
- startActivityForResult(intent, CAMERA_REQUEST_CODE);
- } else if (options[item].equals(getResources().getString(R.string.choose_gallery))) {
- Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
- startActivityForResult(intent, GALLERY_REQUEST_CODE);
- } else if (options[item].equals(getResources().getString(R.string.cancel))) {
- dialog.dismiss();
- }
- }
- });
- builder.show();
- }
- public void uploadProfilePicture(String picturePath) {
- final ProgressDialog progressDialog = new ProgressDialog(this);
- progressDialog.setCancelable(false);
- progressDialog.setMessage("Uploading...");
- progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
- progressDialog.show();
- progressDialog.setMax(100);
- File file = new File(picturePath);
- Ion.with(this)
- .load(API_Config.API_DOMAIN() + "api/file/UploadAvatar")
- .uploadProgressHandler(new ProgressCallback() {
- @Override
- public void onProgress(long uploaded, long total) {
- // Displays the progress bar for the first time.
- if ((int) uploaded == (int) total) {
- if (progressDialog.isShowing())
- progressDialog.dismiss();
- //Finished, Do nothing
- } else {
- int progress = ((int) uploaded / (int) total) * 100;
- progressDialog.setProgress(progress);
- }
- }
- })
- .setTimeout(60 * 60 * 1000)
- .setHeader("Authorization", AppController.getInstance().getAccessToken())
- .setMultipartFile("Avatar", "image/jpeg", file)
- .asJsonObject()
- // run a callback on completion
- .setCallback(new FutureCallback<JsonObject>() {
- @Override
- public void onCompleted(Exception e, JsonObject result) {
- if (progressDialog.isShowing())
- progressDialog.dismiss();
- try {
- JSONObject obj = new JSONObject(result.toString());
- Log.i("Check result ", result.toString());
- // When the loop is finished, updates the notification
- Toast.makeText(MainActivity.this, obj.getString("error_description"), Toast.LENGTH_LONG).show();
- AppController.getInstance().deleteAvatarUrl();
- AppController.getInstance().setAvatarUrl(obj.getString("AvatarUrl"));
- ImageLoader.getInstance().displayImage(obj.getString("AvatarUrl"), profileImage, options);
- } catch (NullPointerException f) {
- } catch (JSONException e1) {
- e1.printStackTrace();
- }
- }
- });
- }
- public void getAddNewLocationApi(final Place place, String placeName) {
- Retrofit retrofit = new Retrofit.Builder()
- .baseUrl(API_Config.API_DOMAIN())
- .addConverter(String.class, new ToStringConverter())
- .build();
- Map<String, String> map = new HashMap<>();
- map.put("Latitude", String.valueOf(place.getLatLng().latitude));
- map.put("Longtitude", String.valueOf(place.getLatLng().longitude));
- map.put("Name", placeName);
- APIService service = retrofit.create(APIService.class);
- Call<String> call = service.addNewLocationAPI(AppController.getInstance().getAccessToken(), map);
- call.enqueue(new Callback<String>() {
- @Override
- public void onResponse(Response<String> response) {
- sendMapListBroadcast();
- try {
- JSONObject obj = new JSONObject(response.body());
- if (obj.getInt("error") == 0) {
- getApiFishingLocation(place.getLatLng().latitude, place.getLatLng().longitude);
- Toast.makeText(MainActivity.this, obj.getString("error_description"), Toast.LENGTH_LONG).show();
- }
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- @Override
- public void onFailure(Throwable t) {
- Toast.makeText(MainActivity.this, t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
- }
- });
- }
- private void sendMapListBroadcast() {
- Intent intent = new Intent("MapListFragment");
- LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
- }
- @Override
- public void onUpdatePosition(int position) {
- //Postion 3 will open the drawer
- if (position == 3) {
- if (drawerLayout.isDrawerOpen(rightDrawer)) {
- drawerLayout.closeDrawer(rightDrawer);
- } else {
- drawerLayout.openDrawer(rightDrawer);
- }
- } else {
- //TODO
- }
- }
- @Override
- public boolean onKeyDown(int keyCode, KeyEvent event) {
- if (keyCode == KeyEvent.KEYCODE_BACK) {
- if (drawerLayout.isDrawerOpen(rightDrawer)) {
- drawerLayout.closeDrawer(rightDrawer);
- }
- else{
- moveTaskToBack(true);
- }
- }
- return super.onKeyDown(keyCode, event);
- }
- public void popupDialog() {
- View dialoglayout = getLayoutInflater().inflate(R.layout.map_dialog_layout, null);
- AlertDialog.Builder builder = new AlertDialog.Builder(this);
- final EditText placeEditText = (EditText) dialoglayout.findViewById(R.id.placeName);
- builder.setView(dialoglayout);
- builder.setCancelable(false).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int id) {
- getAddNewLocationApi(place, placeEditText.getText().toString());
- }
- }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int id) {
- }
- });
- AlertDialog alert = builder.create();
- alert.show();
- }
- private void showPrivacyDialog() {
- if (drawerLayout.isDrawerOpen(rightDrawer)) {
- drawerLayout.closeDrawer(rightDrawer);
- }
- new Handler().postDelayed(new Runnable() {
- @Override
- public void run() {
- /* Create an Intent that will start the Menu-Activity. */
- DialogFragment newFragment = new PrivacyDialogFragment();
- newFragment.show(getSupportFragmentManager(), "Privacy");
- }
- }, 500);
- }
- private void showChangePasswordDialog() {
- if (drawerLayout.isDrawerOpen(rightDrawer)) {
- drawerLayout.closeDrawer(rightDrawer);
- }
- new Handler().postDelayed(new Runnable() {
- @Override
- public void run() {
- /* Create an Intent that will start the Menu-Activity. */
- DialogFragment newFragment = new ChangePasswordDialogFragment();
- newFragment.show(getSupportFragmentManager(), "Change Password");
- }
- }, 500);
- }
- @Override
- public void onClick(View view) {
- switch (view.getId()) {
- case R.id.logoutPlaceholder:
- AppController.getInstance().deleteUserCredential();
- getPreferences(Context.MODE_PRIVATE).edit().clear().commit();
- if (AppController.getInstance().getAccessToken() != null) {
- Log.i("SharedPref", "Something wrong with sharedPref");
- } else {
- Intent intent = new Intent(MainActivity.this, LoginActivity.class);
- startActivity(intent);
- finish();
- }
- break;
- case R.id.profile_placeholder:
- if (drawerLayout.isDrawerOpen(rightDrawer)) {
- drawerLayout.closeDrawer(rightDrawer);
- }
- new Handler().postDelayed(new Runnable() {
- @Override
- public void run() {
- Intent intent = new Intent(MainActivity.this, ProfileActivity.class);
- startActivity(intent);
- }
- }, 200);
- break;
- case R.id.settings_placeholder:
- showPrivacyDialog();
- break;
- case R.id.password_placeholder:
- showChangePasswordDialog();
- break;
- case R.id.invite_placeholder:
- fishTalkShare();
- break;
- }
- }
- private boolean isNetworkAvailable() {
- ConnectivityManager connectivityManager
- = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
- NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
- return activeNetworkInfo != null && activeNetworkInfo.isConnected();
- }
- @Override
- public void onSaveClicked(DialogFragment dialogFragment, String oldPass, String newPass, String confPass) {
- dialogFragment.dismiss();
- final ProgressDialog progressDialog = new ProgressDialog(this);
- progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
- progressDialog.setMessage("Changing password...");
- progressDialog.setCancelable(false);
- progressDialog.show();
- Retrofit retrofit = new Retrofit.Builder()
- .baseUrl(API_Config.API_DOMAIN())
- .addConverter(String.class, new ToStringConverter())
- .build();
- Map<String, String> map = new HashMap<>();
- map.put("oldpassword", oldPass);
- map.put("newpassword", newPass);
- map.put("confirmpassword", confPass);
- APIService service = retrofit.create(APIService.class);
- Call<String> call = service.changePasswordAPI(AppController.getInstance().getAccessToken(), map);
- call.enqueue(new Callback<String>() {
- @Override
- public void onResponse(Response<String> response) {
- if (progressDialog.isShowing())
- progressDialog.dismiss();
- Log.i("ChangePassword API", response.body());
- try {
- JSONObject obj = new JSONObject(response.body());
- if (obj.getInt("error") == 0) {
- Toast.makeText(MainActivity.this, obj.getString("error_description"), Toast.LENGTH_SHORT).show();
- }
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- @Override
- public void onFailure(Throwable t) {
- if (progressDialog.isShowing())
- progressDialog.dismiss();
- try {
- Log.i("ChangePassword ", t.getMessage());
- } catch (NullPointerException e) {
- }
- }
- });
- }
- @Override
- public void onApplyClicked(DialogFragment dialogFragment, String radius) {
- dialogFragment.dismiss();
- AppController.getInstance().setRadiusSetting(radius);
- //TODO
- }
- public void getApiFishingLocation(final double lat, final double lng) {
- OkHttpClient client = new OkHttpClient();
- client.setConnectTimeout(30, TimeUnit.SECONDS); // connect timeout
- client.setReadTimeout(30, TimeUnit.SECONDS);
- Log.i("Current Radius", AppController.getInstance().getRadiusSetting());
- Map<String, String> map = new HashMap<>();
- map.put("Latitude", String.valueOf(lat));
- map.put("Longtitude", String.valueOf(lng));
- map.put("Index", "0");
- map.put("Offset", "50");
- map.put("Radius", AppController.getInstance().getRadiusSetting());
- Retrofit retrofit = new Retrofit.Builder()
- .baseUrl(API_Config.API_DOMAIN())
- .addConverter(String.class, new ToStringConverter())
- .client(client)
- .build();
- APIService service = retrofit.create(APIService.class);
- final Call<String> call = service.getFishingLocationAPI(AppController.getInstance().getAccessToken(), map);
- call.enqueue(new Callback<String>() {
- @Override
- public void onResponse(Response<String> response) {
- Gson gson = new Gson();
- Log.i("Check Location", response.body());
- try {
- JSONObject obj = new JSONObject(response.body());
- JSONArray array = obj.getJSONArray("fishlocations");
- arrayList = new ArrayList<FishLocation>();
- for (int i = 0; i < array.length(); i++) {
- JSONObject jsonObject = array.getJSONObject(i);
- FishLocation fishLocation = gson.fromJson(jsonObject.toString(), FishLocation.class);
- arrayList.add(fishLocation);
- }
- List<Fragment> fragments = getSupportFragmentManager().getFragments();
- for (Fragment fragment : fragments) {
- if (fragment instanceof MapContainerFragment) {
- ((MapContainerFragment) fragment).updateList(arrayList, lat, lng);
- }
- }
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- @Override
- public void onFailure(Throwable t) {
- }
- });
- }
- @Override
- public void onMapListClick(LatLng selectedLocation) {
- List<Fragment> fragments = getSupportFragmentManager().getFragments();
- if(fragments != null){
- for(Fragment fragment: fragments){
- if(fragment instanceof MapContainerFragment){
- ((MapContainerFragment)fragment).zoomInToSelectedLocation(selectedLocation);
- }
- //Log.i("Check SelectedMap", fragment.toString()+" "+selectedLocation.latitude+","+selectedLocation.longitude);
- }
- }
- }
- @Override
- public void onZoomInToSelectedLocation() {
- if(viewPagerFragment != null)
- viewPagerFragment.setCheckedWhenZoomInLocation();
- }
- public void fishTalkShare(){
- Log.i("Check GUID", AppController.getInstance().getUserGuid());
- BranchUniversalObject branchUniversalObject = new BranchUniversalObject()
- .setCanonicalIdentifier("jomfishing/"+AppController.getInstance().getUserGuid())
- .setTitle("FishTalk")
- .setContentDescription("Our truly unique and engaging mobile app for sharing your awesome fishing moments!")
- .setContentImageUrl("http://www.jomfishing.com/img/logo.png")
- .addContentMetadata("userId", AppController.getInstance().getUserGuid())
- .addContentMetadata("userName", AppController.getInstance().getUserEmail())
- .addContentMetadata("Name", AppController.getInstance().getProfileName());
- LinkProperties linkProperties = new LinkProperties()
- .setChannel("facebook")
- .setFeature("sharing");
- ShareSheetStyle shareSheetStyle = new ShareSheetStyle(this, "FishTalk", "Our truly unique and engaging mobile app for sharing your awesome fishing moments!")
- .setCopyUrlStyle(null , "Copy", "Added to clipboard")
- .setMoreOptionStyle(null, "Show more")
- .addPreferredSharingOption(SharingHelper.SHARE_WITH.FACEBOOK)
- .addPreferredSharingOption(SharingHelper.SHARE_WITH.EMAIL);
- branchUniversalObject.showShareSheet(this,
- linkProperties,
- shareSheetStyle,
- new Branch.BranchLinkShareListener() {
- @Override
- public void onShareLinkDialogLaunched() {
- }
- @Override
- public void onShareLinkDialogDismissed() {
- }
- @Override
- public void onLinkShareResponse(String sharedLink, String sharedChannel, BranchError error) {
- }
- @Override
- public void onChannelSelected(String channelName) {
- }
- });
- }
- @Override
- public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
- switch (requestCode) {
- case MY_PERMISSION_REQUEST_LOCATION_ACCESS: {
- // If request is cancelled, the result arrays are empty.
- if (grantResults.length > 0
- && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
- // permission was granted, yay! Do the
- // contacts-related task you need to do.
- Log.i("OnPermission", " is called");
- buildLocationSettingsRequest();
- } else {
- // permission denied, boo! Disable the
- // functionality that depends on this permission.
- }
- break;
- }
- }
- }
- protected synchronized void buildGoogleApiClient() {
- mGoogleApiClient = new GoogleApiClient.Builder(this)
- .addConnectionCallbacks(this)
- .addOnConnectionFailedListener(this)
- .addApi(LocationServices.API)
- .build();
- }
- protected void createLocationRequest() {
- mLocationRequest = new LocationRequest();
- // Sets the desired interval for active location updates. This interval is
- // inexact. You may not receive updates at all if no location sources are available, or
- // you may receive them slower than requested. You may also receive updates faster than
- // requested if other applications are requesting location at a faster interval.
- mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
- // Sets the fastest rate for active location updates. This interval is exact, and your
- // application will never receive updates faster than this value.
- mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
- mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
- }
- protected void buildLocationSettingsRequest() {
- LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
- builder.setAlwaysShow(true);
- builder.addLocationRequest(mLocationRequest);
- mLocationSettingsRequest = builder.build();
- checkLocationSettings();
- }
- protected void checkLocationSettings() {
- PendingResult<LocationSettingsResult> result =
- LocationServices.SettingsApi.checkLocationSettings(
- mGoogleApiClient,
- mLocationSettingsRequest
- );
- result.setResultCallback(this);
- }
- @Override
- protected void onStop() {
- super.onStop();
- if (mGoogleApiClient.isConnected()) {
- mGoogleApiClient.disconnect();
- }
- }
- /**
- * Runs when a GoogleApiClient object successfully connects.
- */
- @Override
- public void onConnected(Bundle connectionHint) {
- Log.i("GoogleApiClient", " is connected");
- startLocationUpdate();
- if (mCurrentLocation == null) {
- Log.i("GoogleApiClient", " location is null");
- if (Build.VERSION.SDK_INT >= 23) {
- if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
- Log.i("GoogleApiClient", " request location above 23 true");
- Utils.checkWriteLocationPermissionFor23(this, MY_PERMISSION_REQUEST_LOCATION_ACCESS);
- } else {
- startLocationUpdate();
- }
- }
- else{
- startLocationUpdate();
- }
- }
- else{
- updateLocationUI();
- }
- }
- private void startLocationUpdate(){
- if (Build.VERSION.SDK_INT >= 23) {
- if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
- if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
- Utils.checkLocationPermissionFor23(this, MY_PERMISSION_REQUEST_LOCATION_ACCESS);
- } else {
- LocationServices.FusedLocationApi.requestLocationUpdates(
- mGoogleApiClient,
- mLocationRequest,
- this
- ).setResultCallback(new ResultCallback<Status>() {
- @Override
- public void onResult(Status status) {
- mRequestingLocationUpdates = true;
- }
- });
- }
- }
- else{
- LocationServices.FusedLocationApi.requestLocationUpdates(
- mGoogleApiClient,
- mLocationRequest,
- this
- ).setResultCallback(new ResultCallback<Status>() {
- @Override
- public void onResult(Status status) {
- mRequestingLocationUpdates = true;
- }
- });
- }
- }
- else{
- LocationServices.FusedLocationApi.requestLocationUpdates(
- mGoogleApiClient,
- mLocationRequest,
- this
- ).setResultCallback(new ResultCallback<Status>() {
- @Override
- public void onResult(Status status) {
- mRequestingLocationUpdates = true;
- }
- });
- }
- }
- @Override
- public void onConnectionFailed(ConnectionResult result) {
- Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
- }
- @Override
- public void onConnectionSuspended(int cause) {
- Log.i(TAG, "Connection suspended");
- mGoogleApiClient.connect();
- }
- @Override
- public void onResult(LocationSettingsResult locationSettingsResult) {
- final Status status = locationSettingsResult.getStatus();
- switch (status.getStatusCode()) {
- case LocationSettingsStatusCodes.SUCCESS:
- Log.i(TAG, "All location settings are satisfied.");
- startLocationUpdate();
- break;
- case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
- Log.i(TAG, "Location settings are not satisfied. Show the user a dialog to" +
- "upgrade location settings ");
- try {
- // Show the dialog by calling startResolutionForResult(), and check the result
- // in onActivityResult().
- status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
- } catch (IntentSender.SendIntentException e) {
- Log.i(TAG, "PendingIntent unable to execute request.");
- }
- break;
- case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
- Log.i(TAG, "Location settings are inadequate, and cannot be fixed here. Dialog " +
- "not created.");
- break;
- }
- }
- @Override
- public void onLocationChanged(Location location) {
- mCurrentLocation = location;
- updateLocationUI();
- }
- @Override
- public void onResume() {
- super.onResume();
- ImageLoader.getInstance().displayImage(AppController.getInstance().getAvatarUrl(), profileImage, options);
- if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
- //do something
- }
- }
- @Override
- protected void onPause() {
- super.onPause();
- // Stop location updates to save battery, but don't disconnect the GoogleApiClient object.
- if (mGoogleApiClient.isConnected()) {
- stopLocationUpdates();
- }
- }
- }
- //getApiFishingLocation
- List<Fragment> fragments = getSupportFragmentManager().getFragments();
- for (Fragment fragment : fragments) {
- if (fragment instanceof MapContainerFragment) {
- ((MapContainerFragment) fragment).updateList(arrayList, lat, lng);
- }
- }
- //UpdateList
- public void updateList(ArrayList<FishLocation> fishLocations, Double lat, Double lng){
- List<Fragment> fragments = getChildFragmentManager().getFragments();
- if(fragments != null) {
- for (Fragment fragment : fragments) {
- if(fragment instanceof MapsFragment) {
- ((MapsFragment) fragment).onRefreshMap(fishLocations, new LatLng(lat, lng));
- }
- else if (fragment instanceof MapListFragment){
- ((MapListFragment)fragment).refreshList(fishLocations, lat, lng);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement