Skip to content

Instantly share code, notes, and snippets.

@shihabmi7
Created November 21, 2016 17:36
Show Gist options
  • Select an option

  • Save shihabmi7/0c728eb54724137dbcbb5e6d71b838c0 to your computer and use it in GitHub Desktop.

Select an option

Save shihabmi7/0c728eb54724137dbcbb5e6d71b838c0 to your computer and use it in GitHub Desktop.
// How to use Location Service :) Follow carefully..
package com.alhikmah.weather360.activity;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.alhikmah.weather360.R;
import com.alhikmah.weather360.adapter.ContactsSection;
import com.alhikmah.weather360.adapter.DividerItemDecoration;
import com.alhikmah.weather360.adapter.MoviesAdapter;
import com.alhikmah.weather360.adapter.WSAWeeklyForecastAdapter;
import com.alhikmah.weather360.manager.FontManager;
import com.alhikmah.weather360.model.Movie;
import com.alhikmah.weather360.model.WSAForecast;
import com.alhikmah.weather360.model.WSAUserType;
import com.alhikmah.weather360.network.CustomListener;
import com.alhikmah.weather360.network.GetContactListFromAPI;
import com.alhikmah.weather360.network.GetMyWeatherConditionFromAPI;
import com.alhikmah.weather360.network.GetMyWeatherForecastFromAPI;
import com.alhikmah.weather360.utility.ApplicationData;
import com.alhikmah.weather360.utility.PermissionUtils;
import com.alhikmah.weather360.utility.PrefsValues;
import com.alhikmah.weather360.utility.WeatherIcon;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.weather360.androidSDK.ApiInvoker;
import com.weather360.androidSDK.api.UsersApi;
import com.weather360.androidSDK.model.InlineResponse2006;
import com.weather360.androidSDK.model.WSAFullCondition;
import com.weather360.androidSDK.model.WSAShortCondition;
import java.util.ArrayList;
import java.util.List;
import io.github.luizgrp.sectionedrecyclerviewadapter.SectionedRecyclerViewAdapter;
public class ScrollableActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
private List<Movie> movieList = new ArrayList<>();
private RecyclerView recyclerView_weekly_forecast;
private RecyclerView recyclerView_friends_family;
private MoviesAdapter mAdapter;
FloatingActionMenu floatingActionMenu;
FloatingActionButton fab_family_members, fab_others, fab3;
String[] listType = {"Family", "Others"};
List<WSAForecast> forecastList = new ArrayList<WSAForecast>();
WSAWeeklyForecastAdapter weeklyForecastAdapter = null;
PrefsValues prefsValues;
TextView textViewWeatherStatus,
textView_temperature, textView_temperature_feel, textView_temperature_humidity,
textview_lowest_temp, textview_highest_temp, textview_visibility_value, textview_wind_value, textview_uv_value;
private Typeface iconFont, textFont;
protected GoogleApiClient mGoogleApiClient;
protected Location mLastLocation;
protected String mLatitudeText;
protected String mLongitudeText;
protected LocationRequest mLocationRequest;
protected static final String TAG = "Scrollable Activity";
private static final int REQUEST_LOCATION_CODE = 1001;
private int LOCATION_PERMISSION_REQUEST_CODE = 1;
/**
* Flag indicating whether a requested permission has been denied after returning in
* {@link #onRequestPermissionsResult(int, String[], int[])}.
*/
private boolean mPermissionDenied = false;
private LinearLayout linearLayout;
int animationCount = 2;
ImageView imageView_settings;
Context context = this;
Activity activity = this;
/*
todo 1. setting button link 2. pro button link 3. blur when fab menu click 4
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scrollable_activty);
prefsValues = new PrefsValues(getApplicationContext(), ApplicationData.APP_NAME, Context.MODE_PRIVATE);
setFloatingActionMenu();
getFamilyMemeberListFromAPI(prefsValues.getApp_user_id());
textFont = FontManager.getTypeface(getApplicationContext(), FontManager.HELVETICA);
iconFont = FontManager.getTypeface(getApplicationContext(), FontManager.CLIMACONS);
textViewWeatherStatus = (TextView) findViewById(R.id.textView_icon);
textView_temperature = (TextView) findViewById(R.id.textView_temperature);
textView_temperature_feel = (TextView) findViewById(R.id.textView_family_member_name);
textView_temperature_humidity = (TextView) findViewById(R.id.textView_member_status);
textview_lowest_temp = (TextView) findViewById(R.id.textview_lowest_temp);
textview_highest_temp = (TextView) findViewById(R.id.textview_highest_temp);
textview_visibility_value = (TextView) findViewById(R.id.textview_visibility_value);
textview_wind_value = (TextView) findViewById(R.id.textview_wind_value);
textview_uv_value = (TextView) findViewById(R.id.textview_uv_value);
imageView_settings = (ImageView) findViewById(R.id.imageView_settings);
imageView_settings.setOnClickListener(this);
buildGoogleApiClient();
// animation here
linearLayout = (LinearLayout) findViewById(R.id.linier_primium);
linearLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/// goToPremiumActivity();
animationCount++;
if (animationCount % 2 == 0) {
startAnimation();
} else {
endAnimation();
}
}
});
// getConditionData();
getDataWithNewSDK();
}
private void getConditionData() {
ApiInvoker.initializeInstance();
UsersApi apiInstance = new UsersApi();
String userId = "2"; // String | The user identifier string
String xUserId = "1"; // String | Send logged in user identifier as string
apiInstance.usersShortConditionUserIdGet(userId, xUserId, new Response.Listener<WSAShortCondition>() {
@Override
public void onResponse(WSAShortCondition response) {
System.out.print("usersShortConditionUserIdGet: " + response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.print("Error usersShortConditionUserIdGet: " + error);
}
});
/* apiInstance.usersConditionUserIdGet(userId, xUserId, new Response.Listener<InlineResponse2006>() {
@Override
public void onResponse(InlineResponse2006 response) {
WSAFullCondition condition = response.getCondition();
List<com.weather360.androidSDK.model.WSAForecast> forecasts = response.getForecast();
System.out.print(response);
textViewWeatherStatus.setText(condition.getConditionString());
textView_temperature.setText(condition.getTempF().toString());
textview_lowest_temp.setText(condition.getLowF().toString() + WeatherIcon.DEGREE);
textview_highest_temp.setText(condition.getHighF().toString() + WeatherIcon.DEGREE);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.print(error);
}
});*/
}
public void getDataWithNewSDK(){
ApiInvoker.initializeInstance();
UsersApi apiInstance = new UsersApi();
String userId = "2"; // String | The user identifier string
String xUserId = "1"; // String | Send logged in user identifier as string
apiInstance.usersConditionUserIdGet(userId, xUserId, new Response.Listener<InlineResponse2006>() {
@Override
public void onResponse(InlineResponse2006 response) {
WSAFullCondition wsaFullCondition= response.getCondition();
//// TODO: 9/12/2016 font will be changed
// textViewWeatherStatus.setTypeface(iconFont);
textViewWeatherStatus.setTypeface(textFont);
// textViewWeatherStatus.setText("" + WeatherIcon.ClimaconCloud);
textViewWeatherStatus.setText("" + wsaFullCondition.getConditionString());
textViewWeatherStatus.setTextSize(18);
/* textView_temperature.setText(ApplicationData.WSA_CONDITION_OBJ.getTemperature() + WeatherIcon.DEGREE);
textView_temperature_feel.setText(ApplicationData.WSA_CONDITION_OBJ.getFeelLike() + WeatherIcon.DEGREE);
textView_temperature_humidity.setText(ApplicationData.WSA_CONDITION_OBJ.getHumidity());
textview_visibility_value.setText(ApplicationData.WSA_CONDITION_OBJ.getVisibility() + " km");
textview_wind_value.setText(ApplicationData.WSA_CONDITION_OBJ.getWind() + " km");*/
textview_uv_value.setText(wsaFullCondition.getUvIndex());
textview_lowest_temp.setText(wsaFullCondition.getLowF()+ WeatherIcon.DEGREE);
textview_highest_temp.setText(wsaFullCondition.getHighF()+ WeatherIcon.DEGREE);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
}
@Override
public void onClick(View v) {
if (v == fab_family_members) {
goToAddMembersActivity();
//Toast.makeText(getApplicationContext(), floatingActionMenu.getMenuButtonLabelText(), Toast.LENGTH_SHORT).show();
} else if (v == fab_others) {
Toast.makeText(getApplicationContext(), "working...", Toast.LENGTH_SHORT).show();
} else if (v == imageView_settings) {
//Toast.makeText(getApplicationContext(), "working...", Toast.LENGTH_SHORT).show();
goToSettingsActivity();
}
/*else if (v == fab3) {
Toast.makeText(getApplicationContext(), floatingActionMenu.getMenuButtonLabelText(), Toast.LENGTH_SHORT).show();
}*/
}
private void startAnimation() {
TranslateAnimation animation = new TranslateAnimation(0.0f, 400.0f,
0.0f, 0.0f); // new TranslateAnimation(xFrom,xTo, yFrom,yTo)
animation.setDuration(1000); // animation duration
//animation.setRepeatCount(1); // animation repeat count
//animation.setRepeatMode(1); // repeat animation (left to right, right to left )
//animation.setFillAfter(true);
linearLayout.startAnimation(animation); // start animation
}
private void endAnimation() {
TranslateAnimation animation = new TranslateAnimation(400.0f, 0.0f,
0.0f, 0.0f); // new TranslateAnimation(xFrom,xTo, yFrom,yTo)
animation.setDuration(1000); // animation duration
//animation.setRepeatCount(1); // animation repeat count
//animation.setRepeatMode(1); // repeat animation (left to right, right to left )
//animation.setFillAfter(true);
linearLayout.startAnimation(animation); // start animation
}
@Override
protected void onResume() {
if (mPermissionDenied) {
// Permission was not granted, display error dialog.
showMissingPermissionError();
mPermissionDenied = false;
} else {
}
super.onResume();
}
private void getWeatherCondition(String userID, String latitude, String longitude) {
GetMyWeatherConditionFromAPI getMyWeatherConditionFromAPI = new GetMyWeatherConditionFromAPI(this, true, userID, latitude, longitude);
getMyWeatherConditionFromAPI.setListener(new CustomListener() {
@Override
public void ModificationMade() {
if (ApplicationData.WSA_CONDITION_OBJ != null) {
//// TODO: 9/12/2016 font will be changed
// textViewWeatherStatus.setTypeface(iconFont);
textViewWeatherStatus.setTypeface(textFont);
// textViewWeatherStatus.setText("" + WeatherIcon.ClimaconCloud);
textViewWeatherStatus.setText("" + ApplicationData.WSA_CONDITION_OBJ.getStatusText());
textViewWeatherStatus.setTextSize(18);
textView_temperature.setText(ApplicationData.WSA_CONDITION_OBJ.getTemperature() + WeatherIcon.DEGREE);
textView_temperature_feel.setText(ApplicationData.WSA_CONDITION_OBJ.getFeelLike() + WeatherIcon.DEGREE);
textView_temperature_humidity.setText(ApplicationData.WSA_CONDITION_OBJ.getHumidity());
textview_visibility_value.setText(ApplicationData.WSA_CONDITION_OBJ.getVisibility() + " km");
textview_wind_value.setText(ApplicationData.WSA_CONDITION_OBJ.getWind() + " km");
textview_uv_value.setText(ApplicationData.WSA_CONDITION_OBJ.getUv() + "");
textview_lowest_temp.setText(WeatherIcon.DOWN + "18" + WeatherIcon.DEGREE);
textview_highest_temp.setText(WeatherIcon.UP + "35" + WeatherIcon.DEGREE);
}
}
});
getMyWeatherConditionFromAPI.execute();
}
private void prepareWeatherForecastData(String userID, String latitude, String longitude) {
recyclerView_weekly_forecast = (RecyclerView) findViewById(R.id.recyclerView_horizontal);
// recyclerView_weekly_forecast.setNestedScrollingEnabled(true);
RecyclerView.LayoutManager mLayoutManager =
new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
recyclerView_weekly_forecast.setLayoutManager(mLayoutManager);
/*WSAForecast forecast;
forecast = new WSAForecast();
forecast.setDayShortName("MON");
forecast.setTemperature("" + 24.50f);
forecast.setStatusText("" + WeatherIcon.ClimaconFogSun);
forecastList.add(forecast);
forecast = new WSAForecast();
forecast.setDayShortName("MON");
forecast.setTemperature("" + 24.50f);
forecast.setStatusText("" + WeatherIcon.ClimaconDrizzleSun);
forecastList.add(forecast);
forecast = new WSAForecast();
forecast.setDayShortName("MON");
forecast.setStatusText("" + WeatherIcon.ClimaconCloudRefresh);
forecast.setTemperature("" + 24.50f);
forecastList.add(forecast);
forecast = new WSAForecast();
forecast.setStatusText("" + WeatherIcon.ClimaconCloudSun);
forecast.setDayShortName("MON");
forecast.setTemperature("" + 24.50f);
forecastList.add(forecast);
forecast = new WSAForecast();
forecast.setDayShortName("MON");
forecast.setStatusText("" + WeatherIcon.ClimaconWindCloud);
forecast.setTemperature("" + 24.50f);
forecastList.add(forecast);
forecast = new WSAForecast();
forecast.setDayShortName("MON");
forecast.setStatusText("" + WeatherIcon.ClimaconUmbrella);
forecast.setTemperature("" + 24.50f);
forecastList.add(forecast);
*/
GetMyWeatherForecastFromAPI getMyWeatherForecastFromAPI = new GetMyWeatherForecastFromAPI(context, true, userID, latitude, longitude);
getMyWeatherForecastFromAPI.setListener(new CustomListener() {
@Override
public void ModificationMade() {
forecastList = ApplicationData.forecastList;
weeklyForecastAdapter = new WSAWeeklyForecastAdapter(forecastList);
recyclerView_weekly_forecast.setAdapter(weeklyForecastAdapter);
weeklyForecastAdapter.notifyDataSetChanged();
}
});
getMyWeatherForecastFromAPI.execute();
}
public void getFamilyMemeberListFromAPI(String userID) {
//setFriendsNFamilyRecylarAdapter();
GetContactListFromAPI api = new GetContactListFromAPI(
this, true, WSAUserType.FAMILY, userID);
api.setListener(new CustomListener() {
@Override
public void ModificationMade() {
// TODO: 8/6/2016 : set recyler adapter here
//familyUserList = ApplicationData.wsaFamilyUsersArrayList;
setFriendsNFamilyRecylarAdapter();
}
});
api.execute();
}
private void goToAddMembersActivity() {
Intent intent = new Intent();
intent.setClass(ScrollableActivity.this, AddMembersActivity.class);
//intent.setClass(SplashScreenActivity.this, FriendsAndFamilyActivity.class);
startActivity(intent);
}
private void goToSettingsActivity() {
Intent intent = new Intent();
intent.setClass(ScrollableActivity.this, SettingsActivity.class);
//intent.setClass(SplashScreenActivity.this, FriendsAndFamilyActivity.class);
startActivity(intent);
}
private void setFriendsNFamilyRecylarAdapter() {
// TODO : MAKE ActivityStatusRecognition RECYLAR VIEW TO SHOW FORECAST : ADAPTER & CLASS NEEDED
SectionedRecyclerViewAdapter sectionAdapter;
sectionAdapter = new SectionedRecyclerViewAdapter();
for (int i = 0; i < listType.length; i++) {
// TODO: 8/5/2016 fill up the two catergory list by data here .
if (i == 0) {
// TODO: 8/5/2016 fill family list data
sectionAdapter.addSection(new ContactsSection(activity,getApplicationContext(), 0, ApplicationData.getFamilyMemberList(), sectionAdapter));
} else {
// TODO: 8/5/2016 fill other's member data
sectionAdapter.addSection(new ContactsSection(activity,getApplicationContext(), 1, ApplicationData.getOtherMembersLISt(), sectionAdapter));
}
}
recyclerView_friends_family = (RecyclerView) findViewById(R.id.recyclerView_friends_n_family);
recyclerView_friends_family.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView_friends_family.setLayoutManager(llm);
recyclerView_friends_family.setAdapter(sectionAdapter);
// i added this line for smooth scorlling..
recyclerView_friends_family.setNestedScrollingEnabled(false);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// floatingActionMenu.show(true);
floatingActionMenu.setMenuButtonShowAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.design_fab_in));
floatingActionMenu.setMenuButtonHideAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.design_fab_out));
}
}, 300);
recyclerView_friends_family.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (dy > 0) {
// Scroll Down
if (floatingActionMenu.isShown()) {
floatingActionMenu.showMenuButton(false);
}
} else if (dy < 0) {
// Scroll Up
if (!floatingActionMenu.isShown()) {
floatingActionMenu.showMenuButton(true);
}
}
}
});
}
private void setFloatingActionMenu() {
floatingActionMenu = (FloatingActionMenu) findViewById(R.id.floationgMenuHomePage);
fab_family_members = (FloatingActionButton) findViewById(R.id.fab_family_members);
fab_others = (FloatingActionButton) findViewById(R.id.fab_others);
floatingActionMenu.setClosedOnTouchOutside(true);
// fab3 = (FloatingActionButton) findViewById(R.id.fab3);
// set color
floatingActionMenu.setMenuButtonColorNormalResId(R.color.recyl_floating_action);
floatingActionMenu.setMenuButtonColorPressedResId(R.color.recyl_floating_action);
floatingActionMenu.setMenuButtonColorRippleResId(R.color.recyl_floating_action);
// Animation:
// floatingActionMenu.hideMenuButton(false);
// floatingActionMenu.showMenuButton(true);
floatingActionMenu.setOnMenuButtonClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/* if (floatingActionMenu.isOpened()) {
Toast.makeText(getApplicationContext(), floatingActionMenu.getMenuButtonLabelText(), Toast.LENGTH_SHORT).show();
}*/
floatingActionMenu.toggle(true);
}
});
//fab3.setOnClickListener(this);
fab_family_members.setOnClickListener(this);
fab_others.setOnClickListener(this);
}
private void prepareMovieData() {
Movie movie = new Movie("Mad Max: Fury Road", "Action & Adventure", "2015");
movieList.add(movie);
movie = new Movie("Inside Out", "Animation, Kids & Family", "2015");
movieList.add(movie);
movie = new Movie("Star Wars: Episode VII - The Force Awakens", "Action", "2015");
movieList.add(movie);
movie = new Movie("Shaun the Sheep", "Animation", "2015");
movieList.add(movie);
movie = new Movie("The Martian", "Science Fiction & Fantasy", "2015");
movieList.add(movie);
movie = new Movie("Mission: Impossible Rogue Nation", "Action", "2015");
movieList.add(movie);
movie = new Movie("Up", "Animation", "2009");
movieList.add(movie);
movie = new Movie("Star Trek", "Science Fiction", "2009");
movieList.add(movie);
movie = new Movie("The LEGO Movie", "Animation", "2014");
movieList.add(movie);
movie = new Movie("Iron Man", "Action & Adventure", "2008");
movieList.add(movie);
movie = new Movie("Aliens", "Science Fiction", "1986");
movieList.add(movie);
movie = new Movie("Chicken Run", "Animation", "2000");
movieList.add(movie);
movie = new Movie("Back to the Future", "Science Fiction", "1985");
movieList.add(movie);
movie = new Movie("Raiders of the Lost Ark", "Action & Adventure", "1981");
movieList.add(movie);
movie = new Movie("Goldfinger", "Action & Adventure", "1965");
movieList.add(movie);
movie = new Movie("Guardians of the Galaxy", "Science Fiction & Fantasy", "2014");
movieList.add(movie);
mAdapter.notifyDataSetChanged();
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ScrollableActivity.ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ScrollableActivity.ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
@Override
protected void onStop() {
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
super.onStop();
}
/**
* Runs when a GoogleApiClient object successfully connects.
*/
@Override
public void onConnected(Bundle connectionHint) {/**/
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// time interval for req. update
mLocationRequest.setInterval(10000);
//enableMyLocation();
Toast.makeText(getApplicationContext(), "onConnected", Toast.LENGTH_LONG).show();
}
@Override
public void onLocationChanged(Location location) {
Log.i(TAG, location.toString());
//txtOutput.setText(location.toString());
if (mLastLocation != null) {
mLatitudeText = String.valueOf(mLastLocation.getLatitude());
mLongitudeText = String.valueOf(mLastLocation.getLongitude());
}
Toast.makeText(getApplicationContext(), "onLocationChanged", Toast.LENGTH_LONG).show();
}
/**
* Enables the My Location layer if the fine location permission has been granted.
*/
private void enableMyLocation() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Permission to access the location is missing.
PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
Manifest.permission.ACCESS_FINE_LOCATION, true);
} else {
// permission has been granted, continue as usual
// request for location updates, no need to connect wifi oor internet
// cell connection would prove you update lat long
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
// get last known location
mLastLocation =
LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
mLatitudeText = String.valueOf(mLastLocation.getLatitude());
mLongitudeText = String.valueOf(mLastLocation.getLongitude());
getWeatherCondition(prefsValues.getApp_user_id(), mLatitudeText, mLongitudeText);
prepareWeatherForecastData(prefsValues.getApp_user_id(), mLatitudeText, mLongitudeText);
} else {
Toast.makeText(context, "Didn't get Location Updates", Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) {
return;
}
if (PermissionUtils.isPermissionGranted(permissions, grantResults,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Enable the my location layer if the permission has been granted.
enableMyLocation();
} else {
// Display the missing permission error dialog when the fragments resume.
mPermissionDenied = true;
}
}
/**
* Displays a dialog with error message explaining that the location permission is missing.
*/
private void showMissingPermissionError() {
PermissionUtils.PermissionDeniedDialog
.newInstance(true).show(getSupportFragmentManager(), "dialog");
}
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
Toast.makeText(getApplicationContext(), "onConnectionFailed", Toast.LENGTH_LONG).show();
}
@Override
public void onConnectionSuspended(int cause) {
// The connection to Google Play services was lost for some reason. We call connect() to
// attempt to re-establish the connection.
Log.i(TAG, "Connection suspended");
Toast.makeText(getApplicationContext(), "on Connection Suspended", Toast.LENGTH_LONG).show();
mGoogleApiClient.connect();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment