I'm trying to create a class for reading location and that it can be used for different activities in my android application. But nothing works.
I think the problem is when I try to call the method refresh activity.
Location Custom Class
public class Localizacion implements LocationListener {
//Constantes
private static final int LOCATION_MIN_TIME = 30 * 1000;
private static final int LOCATION_MIN_DISTANCE = 10;
/*Objetos de Inicialización*/
private Actividad Actividad;
private LocationManager Administrador;
private Location Localizador;
/*Objetos de Respuesta*/
private Double Longitud;
private Double Latitud;
private Double Altitud;
private String Metodo;
public Localizacion(Context Contexto) {
this.Actividad = (Actividad) Contexto;
if (ActivityCompat.checkSelfPermission(Actividad.getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(Actividad.getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
this.Administrador.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 10, (LocationListener) this);
onLocationChanged(this.Localizador);
}
private void ObtenerMetodo() {
Context ContextoActual = Actividad.getApplicationContext();
if (ActivityCompat.checkSelfPermission(ContextoActual, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(ContextoActual, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
this.Localizador = Administrador.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(this.Localizador == null) {
this.Localizador = Administrador.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(this.Localizador == null){
this.Metodo = "RED";
}
else {
this.Metodo = "N/A";
}
}
else {
this.Metodo = "GPS";
}
}
#Override
public void onLocationChanged(Location location) {
if(Localizador != null) {
Longitud = location.getLongitude();
Latitud = location.getLatitude();
Altitud = location.getAltitude();
}
else
{
Longitud = null;
Latitud = null;
Altitud = null;
ObtenerMetodo();
}
}
public Double AltitudActual(){
return Altitud;
}
public Double LatitudActual(){
return Latitud;
}
public Double LongitudActual(){
return Longitud;
}
public String MetodoActual(){
return Metodo;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
ObtenerMetodo();
}
#Override
public void onProviderDisabled(String provider) {
ObtenerMetodo();
}
}
Activity Custom Class
public abstract class Actividad extends AppCompatActivity {
public Actividad(){
super();
}
public void Actualizar(){
}
}
Activity App
public class ChooseSensor extends Actividad {
Localizacion LocalizacionActual;
FrameLayout Contenido;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_sensor);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Contenido = (FrameLayout) findViewById(android.R.id.content);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_choose_sensor, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void Actualizar(){
TextView textView = (TextView) Contenido.findViewById(R.id.texto);
textView.setText("Metodo: "+LocalizacionActual.MetodoActual()+" Lon: "+LocalizacionActual.LongitudActual()+" Lat: "+LocalizacionActual.LatitudActual()+" Alt: "+LocalizacionActual.AltitudActual());
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onStart() {
super.onStart();
LocalizacionActual = new Localizacion(this);
}
}
Related
I'm creating an app for my website and need to when you click on external links like facebook and google login you get a new window tab that closes after login.
I`ve added mWebView.getSettings().setSupportMultipleWindows(true); but now when I click on the link nothing happens
MainFragment.java
public class MainFragment extends TaskFragment implements SwipeRefreshLayout.OnRefreshListener, AdvancedWebView.Listener {
private static final String ARGUMENT_URL = "url";
private static final String ARGUMENT_SHARE = "share";
private static final int REQUEST_FILE_PICKER = 1;
private boolean mProgress = false;
private View mRootView;
private StatefulLayout mStatefulLayout;
private AdvancedWebView mWebView;
private String mUrl = "about:blank";
private String mShare;
private boolean mLocal = false;
private ValueCallback<Uri> mFilePathCallback4;
private ValueCallback<Uri[]> mFilePathCallback5;
private int mStoredActivityRequestCode;
private int mStoredActivityResultCode;
private Intent mStoredActivityResultIntent;
public static MainFragment newInstance(String url, String share) {
MainFragment fragment = new MainFragment();
// arguments
Bundle arguments = new Bundle();
arguments.putString(ARGUMENT_URL, url);
arguments.putString(ARGUMENT_SHARE, share);
fragment.setArguments(arguments);
return fragment;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
setRetainInstance(true);
// handle fragment arguments
Bundle arguments = getArguments();
if (arguments != null) {
handleArguments(arguments);
}
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
int layout = WebViewAppConfig.PULL_TO_REFRESH == PullToRefreshMode.DISABLED ? R.layout.fragment_main : R.layout.fragment_main_swipeable;
mRootView = inflater.inflate(layout, container, false);
mWebView = mRootView.findViewById(R.id.main_webview);
return mRootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// restore webview state
if (savedInstanceState != null) {
mWebView.restoreState(savedInstanceState);
}
// setup webview
setupView();
// pull to refresh
setupSwipeRefreshLayout();
// setup stateful layout
setupStatefulLayout(savedInstanceState);
// load data
if (mStatefulLayout.getState() == StatefulLayout.EMPTY) loadData();
// progress popup
showProgress(mProgress);
// check permissions
if (WebViewAppConfig.GEOLOCATION) {
PermissionUtility.checkPermissionAccessLocation(this);
}
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume() {
super.onResume();
mWebView.onResume();
}
#Override
public void onPause() {
super.onPause();
mWebView.onPause();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onDestroyView() {
super.onDestroyView();
mRootView = null;
}
#Override
public void onDestroy() {
super.onDestroy();
mWebView.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (PermissionUtility.checkPermissionReadExternalStorageAndCamera(this)) {
// permitted
mWebView.onActivityResult(requestCode, resultCode, intent);
} else {
// not permitted
mStoredActivityRequestCode = requestCode;
mStoredActivityResultCode = resultCode;
mStoredActivityResultIntent = intent;
}
//handleFilePickerActivityResult(requestCode, resultCode, intent); // not used, used advanced webview instead
}
#Override
public void onSaveInstanceState(Bundle outState) {
// save current instance state
super.onSaveInstanceState(outState);
setUserVisibleHint(true);
// stateful layout state
if (mStatefulLayout != null) mStatefulLayout.saveInstanceState(outState);
// save webview state
mWebView.saveState(outState);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// action bar menu
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_main, menu);
// show or hide share button
MenuItem share = menu.findItem(R.id.menu_main_share);
share.setVisible(mShare != null && !mShare.trim().equals(""));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// action bar menu behavior
switch (item.getItemId()) {
case R.id.menu_main_share:
IntentUtility.startShareActivity(getContext(), getString(R.string.app_name), getShareText(mShare));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case PermissionUtility.REQUEST_PERMISSION_READ_EXTERNAL_STORAGE_AND_CAMERA:
case PermissionUtility.REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE:
case PermissionUtility.REQUEST_PERMISSION_ACCESS_LOCATION: {
// if request is cancelled, the result arrays are empty
if (grantResults.length > 0) {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
// permission granted
if (requestCode == PermissionUtility.REQUEST_PERMISSION_READ_EXTERNAL_STORAGE_AND_CAMERA) {
// continue with activity result handling
if (mStoredActivityResultIntent != null) {
mWebView.onActivityResult(mStoredActivityRequestCode, mStoredActivityResultCode, mStoredActivityResultIntent);
mStoredActivityRequestCode = 0;
mStoredActivityResultCode = 0;
mStoredActivityResultIntent = null;
}
}
} else {
// permission denied
}
}
} else {
// all permissions denied
}
break;
}
}
}
#Override
public void onRefresh() {
runTaskCallback(new Runnable() {
#Override
public void run() {
refreshData();
}
});
}
#Override
public void onPageStarted(String url, Bitmap favicon) {
Logcat.d("");
}
#Override
public void onPageFinished(String url) {
Logcat.d("");
}
#Override
public void onPageError(int errorCode, String description, String failingUrl) {
Logcat.d("");
}
#Override
public void onDownloadRequested(String url, String suggestedFilename, String mimeType, long contentLength, String contentDisposition, String userAgent) {
Logcat.d("");
if (PermissionUtility.checkPermissionWriteExternalStorage(MainFragment.this)) {
Toast.makeText(getActivity(), R.string.main_downloading, Toast.LENGTH_LONG).show();
DownloadUtility.downloadFile(getActivity(), url, DownloadFileUtility.getFileName(url));
}
}
#Override
public void onExternalPageRequest(String url) {
Logcat.d("");
}
public void refreshData() {
if (NetworkUtility.isOnline(getActivity()) || mLocal) {
// show progress popup
showProgress(true);
// load web url
String url = mWebView.getUrl();
if (url == null || url.equals("")) url = mUrl;
mWebView.loadUrl(url);
} else {
showProgress(false);
Toast.makeText(getActivity(), R.string.global_network_offline, Toast.LENGTH_LONG).show();
}
}
private void handleArguments(Bundle arguments) {
if (arguments.containsKey(ARGUMENT_URL)) {
mUrl = arguments.getString(ARGUMENT_URL);
mLocal = mUrl.contains("file://");
}
if (arguments.containsKey(ARGUMENT_SHARE)) {
mShare = arguments.getString(ARGUMENT_SHARE);
}
}
// not used, used advanced webview instead
private void handleFilePickerActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_FILE_PICKER) {
if (mFilePathCallback4 != null) {
Uri result = intent == null || resultCode != Activity.RESULT_OK ? null : intent.getData();
if (result != null) {
String path = ContentUtility.getPath(getActivity(), result);
Uri uri = Uri.fromFile(new File(path));
mFilePathCallback4.onReceiveValue(uri);
} else {
mFilePathCallback4.onReceiveValue(null);
}
}
if (mFilePathCallback5 != null) {
Uri result = intent == null || resultCode != Activity.RESULT_OK ? null : intent.getData();
if (result != null) {
String path = ContentUtility.getPath(getActivity(), result);
Uri uri = Uri.fromFile(new File(path));
mFilePathCallback5.onReceiveValue(new Uri[]{uri});
} else {
mFilePathCallback5.onReceiveValue(null);
}
}
mFilePathCallback4 = null;
mFilePathCallback5 = null;
}
}
private void loadData() {
if (NetworkUtility.isOnline(getActivity()) || mLocal) {
// show progress
if (WebViewAppConfig.PROGRESS_PLACEHOLDER) {
mStatefulLayout.showProgress();
} else {
mStatefulLayout.showContent();
}
// load web url
mWebView.loadUrl(mUrl);
} else {
mStatefulLayout.showOffline();
}
}
private void showProgress(boolean visible) {
// show pull to refresh progress bar
SwipeRefreshLayout contentSwipeRefreshLayout = mRootView.findViewById(R.id.container_content_swipeable);
SwipeRefreshLayout offlineSwipeRefreshLayout = mRootView.findViewById(R.id.container_offline_swipeable);
SwipeRefreshLayout emptySwipeRefreshLayout = mRootView.findViewById(R.id.container_empty_swipeable);
if (contentSwipeRefreshLayout != null) contentSwipeRefreshLayout.setRefreshing(visible);
if (offlineSwipeRefreshLayout != null) offlineSwipeRefreshLayout.setRefreshing(visible);
if (emptySwipeRefreshLayout != null) emptySwipeRefreshLayout.setRefreshing(visible);
mProgress = visible;
}
private void showContent(final long delay) {
final Handler timerHandler = new Handler();
final Runnable timerRunnable = new Runnable() {
#Override
public void run() {
runTaskCallback(new Runnable() {
public void run() {
if (getActivity() != null && mRootView != null) {
Logcat.d("timer");
mStatefulLayout.showContent();
}
}
});
}
};
timerHandler.postDelayed(timerRunnable, delay);
}
private void setupView() {
// webview settings
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setAppCacheEnabled(true);
mWebView.getSettings().setAppCachePath(getActivity().getCacheDir().getAbsolutePath());
mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.getSettings().setDatabaseEnabled(true);
mWebView.getSettings().setGeolocationEnabled(true);
mWebView.getSettings().setSupportZoom(true);
mWebView.getSettings().setBuiltInZoomControls(false);
mWebView.getSettings().setSupportMultipleWindows(true);
mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
// user agent
if (WebViewAppConfig.WEBVIEW_USER_AGENT != null && !WebViewAppConfig.WEBVIEW_USER_AGENT.equals("")) {
mWebView.getSettings().setUserAgentString(WebViewAppConfig.WEBVIEW_USER_AGENT);
}
// advanced webview settings
mWebView.setListener(getActivity(), this);
mWebView.setGeolocationEnabled(true);
// webview style
mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); // fixes scrollbar on Froyo
// webview hardware acceleration
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
// webview chrome client
View nonVideoLayout = getActivity().findViewById(R.id.main_non_video_layout);
ViewGroup videoLayout = getActivity().findViewById(R.id.main_video_layout);
View progressView = getActivity().getLayoutInflater().inflate(R.layout.placeholder_progress, null);
VideoEnabledWebChromeClient webChromeClient = new VideoEnabledWebChromeClient(nonVideoLayout, videoLayout, progressView, (VideoEnabledWebView) mWebView);
webChromeClient.setOnToggledFullscreen(new MyToggledFullscreenCallback());
mWebView.setWebChromeClient(webChromeClient);
//mWebView.setWebChromeClient(new MyWebChromeClient()); // not used, used advanced webview instead
// webview client
mWebView.setWebViewClient(new MyWebViewClient());
// webview key listener
mWebView.setOnKeyListener(new WebViewOnKeyListener((DrawerStateListener) getActivity()));
// webview touch listener
mWebView.requestFocus(View.FOCUS_DOWN); // http://android24hours.blogspot.cz/2011/12/android-soft-keyboard-not-showing-on.html
mWebView.setOnTouchListener(new WebViewOnTouchListener());
// webview scroll listener
//((RoboWebView) mWebView).setOnScrollListener(new WebViewOnScrollListener()); // not used
// admob
setupBannerView();
}
private void setupBannerView() {
if (WebViewAppConfig.ADMOB_UNIT_ID_BANNER != null && !WebViewAppConfig.ADMOB_UNIT_ID_BANNER.equals("") && NetworkUtility.isOnline(getActivity())) {
ViewGroup contentLayout = mRootView.findViewById(R.id.container_content);
AdMobUtility.createAdView(getActivity(), WebViewAppConfig.ADMOB_UNIT_ID_BANNER, AdSize.BANNER, contentLayout);
}
}
private void controlBack() {
if (mWebView.canGoBack()) mWebView.goBack();
}
private void controlForward() {
if (mWebView.canGoForward()) mWebView.goForward();
}
private void controlStop() {
mWebView.stopLoading();
}
private void controlReload() {
mWebView.reload();
}
private void setupStatefulLayout(Bundle savedInstanceState) {
// reference
mStatefulLayout = (StatefulLayout) mRootView;
// state change listener
mStatefulLayout.setOnStateChangeListener(new StatefulLayout.OnStateChangeListener() {
#Override
public void onStateChange(View view, #StatefulLayout.State int state) {
Logcat.d(String.valueOf(state));
// do nothing
}
});
// restore state
mStatefulLayout.restoreInstanceState(savedInstanceState);
}
private void setupSwipeRefreshLayout() {
SwipeRefreshLayout contentSwipeRefreshLayout = mRootView.findViewById(R.id.container_content_swipeable);
SwipeRefreshLayout offlineSwipeRefreshLayout = mRootView.findViewById(R.id.container_offline_swipeable);
SwipeRefreshLayout emptySwipeRefreshLayout = mRootView.findViewById(R.id.container_empty_swipeable);
if (WebViewAppConfig.PULL_TO_REFRESH == PullToRefreshMode.ENABLED) {
contentSwipeRefreshLayout.setOnRefreshListener(this);
offlineSwipeRefreshLayout.setOnRefreshListener(this);
emptySwipeRefreshLayout.setOnRefreshListener(this);
} else if (WebViewAppConfig.PULL_TO_REFRESH == PullToRefreshMode.PROGRESS) {
contentSwipeRefreshLayout.setDistanceToTriggerSync(Integer.MAX_VALUE);
offlineSwipeRefreshLayout.setDistanceToTriggerSync(Integer.MAX_VALUE);
emptySwipeRefreshLayout.setDistanceToTriggerSync(Integer.MAX_VALUE);
}
}
private String getShareText(String text) {
if (mWebView != null) {
if (mWebView.getTitle() != null) {
text = text.replaceAll("\\{TITLE\\}", mWebView.getTitle());
}
if (mWebView.getUrl() != null) {
text = text.replaceAll("\\{URL\\}", mWebView.getUrl());
}
}
return text;
}
private boolean isLinkExternal(String url) {
for (String rule : WebViewAppConfig.LINKS_OPENED_IN_EXTERNAL_BROWSER) {
if (url.contains(rule)) return true;
}
return false;
}
private boolean isLinkInternal(String url) {
for (String rule : WebViewAppConfig.LINKS_OPENED_IN_INTERNAL_WEBVIEW) {
if (url.contains(rule)) return true;
}
return false;
}
// not used, used advanced webview instead
private class MyWebChromeClient extends WebChromeClient {
#Override
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
if (PermissionUtility.checkPermissionReadExternalStorageAndCamera(MainFragment.this)) {
mFilePathCallback5 = filePathCallback;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "File Chooser"), REQUEST_FILE_PICKER);
return true;
}
return false;
}
#Override
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
callback.invoke(origin, true, false);
}
public void openFileChooser(ValueCallback<Uri> filePathCallback) {
if (PermissionUtility.checkPermissionReadExternalStorageAndCamera(MainFragment.this)) {
mFilePathCallback4 = filePathCallback;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "File Chooser"), REQUEST_FILE_PICKER);
}
}
public void openFileChooser(ValueCallback<Uri> filePathCallback, String acceptType) {
if (PermissionUtility.checkPermissionReadExternalStorageAndCamera(MainFragment.this)) {
mFilePathCallback4 = filePathCallback;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "File Chooser"), REQUEST_FILE_PICKER);
}
}
public void openFileChooser(ValueCallback<Uri> filePathCallback, String acceptType, String capture) {
if (PermissionUtility.checkPermissionReadExternalStorageAndCamera(MainFragment.this)) {
mFilePathCallback4 = filePathCallback;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "File Chooser"), REQUEST_FILE_PICKER);
}
}
}
private class MyToggledFullscreenCallback implements VideoEnabledWebChromeClient.ToggledFullscreenCallback {
#Override
public void toggledFullscreen(boolean fullscreen) {
if (fullscreen) {
WindowManager.LayoutParams attrs = getActivity().getWindow().getAttributes();
attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
attrs.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
getActivity().getWindow().setAttributes(attrs);
getActivity().getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
} else {
WindowManager.LayoutParams attrs = getActivity().getWindow().getAttributes();
attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
attrs.flags &= ~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
getActivity().getWindow().setAttributes(attrs);
getActivity().getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
}
}
}
private class MyWebViewClient extends WebViewClient {
private boolean mSuccess = true;
#Override
public void onPageFinished(final WebView view, final String url) {
runTaskCallback(new Runnable() {
public void run() {
if (getActivity() != null && mSuccess) {
showContent(500); // hide progress bar with delay to show webview content smoothly
showProgress(false);
if (WebViewAppConfig.ACTION_BAR_HTML_TITLE) {
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(view.getTitle());
}
CookieSyncManager.getInstance().sync(); // save cookies
}
mSuccess = true;
}
});
}
#SuppressWarnings("deprecation")
#Override
public void onReceivedError(final WebView view, final int errorCode, final String description, final String failingUrl) {
runTaskCallback(new Runnable() {
public void run() {
if (getActivity() != null) {
mSuccess = false;
mStatefulLayout.showEmpty();
showProgress(false);
}
}
});
}
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
// forward to deprecated method
onReceivedError(view, error.getErrorCode(), error.getDescription().toString(), request.getUrl().toString());
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (DownloadFileUtility.isDownloadableFile(url)) {
if (PermissionUtility.checkPermissionWriteExternalStorage(MainFragment.this)) {
Toast.makeText(getActivity(), R.string.main_downloading, Toast.LENGTH_LONG).show();
DownloadUtility.downloadFile(getActivity(), url, DownloadFileUtility.getFileName(url));
return true;
}
return true;
} else if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) {
// load url listener
((LoadUrlListener) getActivity()).onLoadUrl(url);
// determine for opening the link externally or internally
boolean external = isLinkExternal(url);
boolean internal = isLinkInternal(url);
if (!external && !internal) {
external = WebViewAppConfig.OPEN_LINKS_IN_EXTERNAL_BROWSER;
}
// open the link
if (external) {
IntentUtility.startWebActivity(getContext(), url);
return true;
} else {
showProgress(true);
return false;
}
} else if (url != null && url.startsWith("file://")) {
// load url listener
((LoadUrlListener) getActivity()).onLoadUrl(url);
return false;
} else {
return IntentUtility.startIntentActivity(getContext(), url);
}
}
}
}
I'm trying to use the mapbox SDK to get my current location and set the navigation, but it's not working. I was trying to implement this code following the tutorial from the mapbox website.
public class pos extends AppCompatActivity implements LocationEngineListener, PermissionsListener {
private MapView mapView;
// variables for adding location layer
private MapboxMap map;
private PermissionsManager permissionsManager;
private LocationLayerPlugin locationPlugin;
private LocationEngine locationEngine;
private Location originLocation;
// variables for adding a marker
private Marker destinationMarker;
private LatLng originCoord;
private LatLng destinationCoord;
// variables for calculating and drawing a route
private Point originPosition;
private Point destinationPosition;
private DirectionsRoute currentRoute;
private static final String TAG = "DirectionsActivity";
private NavigationMapRoute navigationMapRoute;
//private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this,"pk.eyJ1IjoiaWhkaW5hIiwiYSI6ImNqaDRveHdhcjB1ZTIyd253M2R2MGhwY28ifQ.If9oJq_rILeuaK1sjp9-nw");
setContentView(R.layout.activity_pos);
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(final MapboxMap mapboxMap) {
map = mapboxMap;
enableLocationPlugin();
originCoord = new LatLng(originLocation.getLatitude(), originLocation.getLongitude());
mapboxMap.addOnMapClickListener(new MapboxMap.OnMapClickListener() {
#Override
public void onMapClick(#NonNull LatLng point) {
if (destinationMarker != null) {
mapboxMap.removeMarker(destinationMarker);
}
destinationCoord = point;
destinationMarker = mapboxMap.addMarker(new MarkerOptions()
.position(destinationCoord)
);
destinationPosition = Point.fromLngLat(destinationCoord.getLongitude(), destinationCoord.getLatitude());
originPosition = Point.fromLngLat(originCoord.getLongitude(), originCoord.getLatitude());
getRoute(originPosition, destinationPosition);
/* button.setEnabled(true);
button.setBackgroundResource(R.color.mapboxBlue);*/
}
;
});
/*button = findViewById(R.id.startButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Point origin = originPosition;
Point destination = destinationPosition;
// Pass in your Amazon Polly pool id for speech synthesis using Amazon Polly
// Set to null to use the default Android speech synthesizer
String awsPoolId = null;
boolean simulateRoute = true;
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.origin(origin)
.destination(destination)
.awsPoolId(awsPoolId)
.shouldSimulateRoute(simulateRoute)
.build();
// Call this method with Context from within an Activity
NavigationLauncher.startNavigation(NavigationActivity.this, options);
}
});*/
}
;
});
}
private void getRoute(Point origin, Point destination) {
NavigationRoute.builder()
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
// You can get the generic HTTP info about the response
Log.d(TAG, "Response code: " + response.code());
if (response.body() == null) {
Log.e(TAG, "No routes found, make sure you set the right user and access token.");
return;
} else if (response.body().routes().size() < 1) {
Log.e(TAG, "No routes found");
return;
}
currentRoute = response.body().routes().get(0);
// Draw the route on the map
if (navigationMapRoute != null) {
navigationMapRoute.removeRoute();
} else {
navigationMapRoute = new NavigationMapRoute(null, mapView, map, R.style.NavigationMapRoute);
}
navigationMapRoute.addRoute(currentRoute);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
Log.e(TAG, "Error: " + throwable.getMessage());
}
});
}
#SuppressWarnings( {"MissingPermission"})
private void enableLocationPlugin() {
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(this)) {
// Create an instance of LOST location engine
initializeLocationEngine();
locationPlugin = new LocationLayerPlugin(mapView, map, locationEngine);
locationPlugin.setLocationLayerEnabled(true);
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
#SuppressWarnings( {"MissingPermission"})
private void initializeLocationEngine() {
locationEngine = new LocationEngineProvider(this).obtainBestLocationEngineAvailable();
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.activate();
Location lastLocation = locationEngine.getLastLocation();
if (lastLocation != null) {
originLocation = lastLocation;
setCameraPosition(lastLocation);
} else {
locationEngine.addLocationEngineListener(this);
}
}
private void setCameraPosition(Location location) {
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 13));
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
}
#Override
public void onPermissionResult(boolean granted) {
if (granted) {
enableLocationPlugin();
} else {
finish();
}
}
#Override
#SuppressWarnings( {"MissingPermission"})
public void onConnected() {
locationEngine.requestLocationUpdates();
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
originLocation = location;
setCameraPosition(location);
locationEngine.removeLocationEngineListener(this);
}
}
#Override
#SuppressWarnings( {"MissingPermission"})
protected void onStart() {
super.onStart();
if (locationEngine != null) {
locationEngine.requestLocationUpdates();
}
if (locationPlugin != null) {
locationPlugin.onStart();
}
mapView.onStart();
}
#Override
protected void onStop() {
super.onStop();
if (locationEngine != null) {
locationEngine.removeLocationUpdates();
}
if (locationPlugin != null) {
locationPlugin.onStop();
}
mapView.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
if (locationEngine != null) {
locationEngine.deactivate();
}
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
}
Try modifying your methods with this:
private void enableLocationPlugin() {
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(this)) {
initializeLocationEngine();
locationPlugin = new LocationLayerPlugin(mapView, map, locationEngine);
locationPlugin.setLocationLayerEnabled(true);
locationPlugin.setCameraMode(CameraMode.TRACKING);
locationPlugin.setRenderMode(RenderMode.COMPASS);
getLifecycle().addObserver(locationPlugin);
Log.e(TAG, "enableLocationPlugin:Permission Granted" );
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
Log.e(TAG, "enableLocationPlugin:Permission Not Granted" );
}
}
private void initializeLocationEngine() {
locationEngine = new LocationEngineProvider(this).obtainBestLocationEngineAvailable();
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.addLocationEngineListener(this);
locationEngine.activate();
Location lastLocation = locationEngine.getLastLocation();
if (lastLocation != null) {
setCameraPosition(lastLocation);
} else {
locationEngine.addLocationEngineListener(this);
}
}
and your onStart with this:
#Override
#SuppressWarnings({"MissingPermission"})
protected void onStart() {
super.onStart();
if (locationEngine != null) {
locationEngine.requestLocationUpdates();
locationEngine.addLocationEngineListener(this);
}
if (locationPlugin != null) {
locationPlugin.onStart();
}
mapView.onStart();
}
I'm very new to android studio, and I'm working with an app that demands more of accuracy of location, first i used location manager but it provides not so accurate location of the user now i want to change it to fused location api but im confused with it, i don't know how to put it in my activity,I already search the net but nothing seems to have sense to me.
here is my Main Activity
public class MainActivity extends AppCompatActivity {
ContactDbAdapter contactDbAdapter;
private GoogleApiClient client;
EditText messageText;
UserDbAdapter userDbAdapter;
Cursor cursor;
TextView locationText;
#Override
public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
return super.checkUriPermission(uri, pid, uid, modeFlags);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
userDbAdapter = new UserDbAdapter(this);
messageText = (EditText) findViewById(R.id.messageText);
locationText = (TextView) findViewById(R.id.locationTextView);
try {
userDbAdapter.open();
} catch (SQLException error) {
Log.e("mytag", "Error open userDbAdapter\n");
}
contactDbAdapter = new ContactDbAdapter(this);
try {
contactDbAdapter.open();
} catch (SQLException error) {
Log.e("mytag", "Error open contactDbAdapter\n");
}
cursor = contactDbAdapter.getContacts();
final Button sos = (Button) findViewById(R.id.redbutton);
final Button finish = (Button) findViewById(R.id.greenbutton);
final CountDownTimer timer = new CountDownTimer(3999, 100) {
public void onTick(long millisUntilFinished) {
sos.setText("" + ((int) (millisUntilFinished) / 1000));
}
public void onFinish() {
sos.setVisibility(View.GONE);
finish.setVisibility(View.VISIBLE);
finish.setText("finish");
SmsManager smsManager = SmsManager.getDefault();
cursor = contactDbAdapter.getContacts();
String msg = messageText.getText().toString() + "#" + locationText.getText().toString();
Log.e("mytag", msg);
if(cursor.moveToFirst()){
do{
String number=cursor.getString(cursor.getColumnIndex(contactDbAdapter.PHONE_NUM));
smsManager.sendTextMessage(number, null, msg, null, null);
}while(cursor.moveToNext());
}
}
};
sos.setTag(1);
sos.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
final int status = (Integer) v.getTag();
if (status != 1) {
sos.setText("sos");
sos.setTag(1);
timer.cancel();
} else {
sos.setTag(0);
timer.start();
}
}
}
);
finish.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
sos.setVisibility(View.VISIBLE);
finish.setVisibility(View.GONE);
sos.callOnClick();
}
}
);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
switch (id) {
case R.id.contact:
Intent contactIntent = new Intent(getApplicationContext(), LogInActivity.class);
startActivity(contactIntent);
return true;
case R.id.message:
Intent messageIntent = new Intent(getApplicationContext(), DisplayMessageActivity.class);
startActivity(messageIntent);
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.cse4471.osu.sos_osu/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onResume() {
super.onResume();
// refresh user message
cursor = userDbAdapter.getUsers();
if (cursor.moveToFirst()) {
messageText.setText(cursor.getString(cursor.getColumnIndex(userDbAdapter.MESSAGE)));
}
// Acquire a reference to the system Location Manager
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.INTERNET}, 10);
return;
}
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
locationText.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, locationListener);
Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(loc != null) {
// messageText.setText("Latitude:" + loc.getLatitude() + ", Longitude:" + loc.getLongitude());
locationText.setText("Latitude:" + loc.getLatitude() + ", Longitude:" + loc.getLongitude());
}
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.cse4471.osu.sos_osu/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
#Override
public void onDestroy() {
super.onDestroy();
if (cursor != null) {
cursor.close();
}
}
I already put in my manifest the permissions and I also added the 'com.google.android.gms:play-services-location:10.0.0' in my gradle file. The issue now is i want to change the location manager into fused location provider api.
Since location provider is deprecated with LocationProviderClient in latest play services version but if you want to continue with the location provider here is the sample working activity code for location provider in activity
public class LocationActivity extends AppCompatActivity implements
GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks,
LocationListener, GetAddressFromLatLng.LocationAddressResponse {
private LocationRequest mLocationRequest;
public static final int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
private static final int MILLISECONDS_PER_SECOND = 1000;
private FusedLocationProviderApi locationProvider = LocationServices.FusedLocationApi;
private GoogleApiClient mGoogleApiClient;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// create GoogleClient
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
requestLocationUpdates();
}
}
public void requestLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// runtime permissions
return;
}
locationProvider.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
switch (requestCode) {
case LOCATION_PERMISSION_REQUEST_CODE:
if (grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
requestLocationUpdates();
}
}
break;
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
// every time location changed it calls itself
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case PLAY_SERVICES_RESOLUTION_REQUEST:
switch (resultCode) {
case Activity.RESULT_OK:
requestLocationUpdates();
break;
case Activity.RESULT_CANCELED:
// Do failure task
break;
}
break;
}
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient != null && mGoogleApiClient.isConnected())
mGoogleApiClient.disconnect();
}
#Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
requestLocationUpdates();
}
}
}
I am getting the location data using a service, this service is started when my app runs on a activity, and i need that activity to ask for the permissions.
So basicly this is my service (it works fine)
public class GoogleLocation extends Service implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private static final String TAG = "BOOMBOOMTESTGPS";
private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 0;
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 0;
private static final float LOCATION_DISTANCE = 0f;
private int updatePriority;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private final IBinder mBinder = new LocalBinder();
private Intent intent;
private String provider;
Context context;
Location mLastLocation;
public class LocalBinder extends Binder {
public GoogleLocation getServerInstance() {
return GoogleLocation.this;
}
}
public Location getLocation() {
Log.d("IMHERE", "HELLO");
return mLastLocation;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
context = getApplicationContext();
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public void onCreate() {
Log.e(TAG, "onCreate");
initializeLocationManager();
if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
this.updatePriority = LocationRequest.PRIORITY_HIGH_ACCURACY;
} else if (mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
this.updatePriority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY;
} else {
this.updatePriority = LocationRequest.PRIORITY_HIGH_ACCURACY;
}
this.buildGoogleApiClient();
this.createLocationRequest();
this.googleApiClient.connect();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
// Request location updates
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(this.googleApiClient, this.locationRequest,this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
Log.d("localizacao",mLastLocation.toString());
}
#Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
super.onDestroy();
this.googleApiClient.unregisterConnectionCallbacks(this);
this.googleApiClient.unregisterConnectionFailedListener(this);
this.googleApiClient.disconnect();
this.mLastLocation = null;
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
private synchronized void buildGoogleApiClient() {
this.googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
private void createLocationRequest() {
this.locationRequest = new LocationRequest();
this.locationRequest.setInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
this.locationRequest.setPriority(updatePriority);
}
here is where i start it
package com.example.afcosta.inesctec.pt.android;
import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.example.afcosta.inesctec.pt.android.services.GoogleLocation;
public class LocationPermission extends AppCompatActivity {
public static final int REQ_PERMISSION = 99;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
askPermission();
Intent i = new Intent(this,Login.class);
startActivity(i);
}
// PEDIDO DE PERMISSÃO
private void askPermission() {
checkLocationPermission();
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission. ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission. ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(this)
.setTitle("Partilhar localização")
.setMessage("Permitir a partilha de dados sobre a sua localização?")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(LocationPermission.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission. ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
startService(new Intent(this, GoogleLocation.class));
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission. ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
startService(new Intent(this, GoogleLocation.class));
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
}
}
}
the thing is, i need to ask for permissions when he runs the app for the first time, or he has the location disabled. And that never happens.
I should just start the service when the user has give the permission.
Any help with this?
Thanks
you can ask for any permission in runtime in this way:
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)) {
} else {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, RC_ACCESS_FINE_LOCATION);
}
}
and you can get it's result in:
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case RC_ACCESS_FINE_LOCATION: {
}
}
}
#Override
protected Boolean processInBackground(Void... params) {
PermissionResponse response = PermissionEverywhere.getPermission(getApplicationContext(),
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQ_CODE,
"Notification title",
"This app need external permisison",
R.launcher)
.call();
boolean isGranted = response.isGranted();
if(isGrante){
// here do your stuff
}
}
So when I comment out past the facebook code comment, the Location manager does work and onLocationChanged does update the proper Latitude and Longitude. However, when I uncomment it, the Facebook functionality works but the onLocationChanged never gets called for some reason.
MainActivity.java
public class MainActivity extends FragmentActivity implements OnClickListener {
private MainFragment mainFragment;
Button sendIPbutton; //Button for sending IP Address
EditText mEdit; //Get info from what user enters in form
//TextView mText;
TextView coordinates;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*http://www.firstdroid.com/2010/04/29/android-development-using-gps-to-get-current-location-2/*/
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
/**************************Facebook code********************************************/
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
getSupportFragmentManager()
.beginTransaction()
.add(android.R.id.content, mainFragment)
.commit();
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
/*********************************************************************************/
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location loc){
loc.getLatitude();
loc.getLongitude();
String Text = "Latitude: " + loc.getLatitude() + "\nLongitude: " + loc.getLongitude();
// Toast.makeText( getApplicationContext(),Text, Toast.LENGTH_SHORT).show();
coordinates = (TextView)findViewById(R.id.coordinates);
coordinates.setText(Text);
}
#Override
public void onProviderDisabled(String provider){
Toast.makeText( getApplicationContext(),
"Gps Disabled",
Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider){
Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras){
}
}/* End of Class MyLocationListener */
#Override
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.
INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
public void setObject(View view){
Intent intent = new Intent(this, SetObjectActivity.class);
startActivity(intent);
}
I think there must be something going on in the oncreate function.
Here is my MainFragment.java code. Note that it's primarily from the Facebook Login and Sharing tutorial on their website.
public class MainFragment extends Fragment {
private Button shareButton;
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;
private static final String TAG = MainFragment.class.getSimpleName();
private TextView coordinates;
private UiLifecycleHelper uiHelper;
private final List<String> permissions;
public MainFragment() {
permissions = Arrays.asList("user_status");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
shareButton = (Button) view.findViewById(R.id.shareButton);
coordinates = (TextView) view.findViewById(R.id.coordinates);
shareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
publishStory();
}
});
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
authButton.setFragment(this);
authButton.setReadPermissions(permissions);
if (savedInstanceState != null) {
pendingPublishReauthorization =
savedInstanceState.getBoolean(PENDING_PUBLISH_KEY, false);
}
return view;
}
#Override
public void onResume() {
super.onResume();
// For scenarios where the main activity is launched and user
// session is not null, the session state change notification
// may not be triggered. Trigger it if it's open/closed.
Session session = Session.getActiveSession();
if (session != null &&
(session.isOpened() || session.isClosed()) ) {
onSessionStateChange(session, session.getState(), null);
}
uiHelper.onResume();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(PENDING_PUBLISH_KEY, pendingPublishReauthorization);
uiHelper.onSaveInstanceState(outState);
}
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
shareButton.setVisibility(View.VISIBLE);
if (pendingPublishReauthorization &&
state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
pendingPublishReauthorization = false;
publishStory();
}
} else if (state.isClosed()) {
shareButton.setVisibility(View.INVISIBLE);
}
}
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private void publishStory() {
Session session = Session.getActiveSession();
if (session != null){
// Check for publish permissions
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new Session
.NewPermissionsRequest(this, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
return;
}
String text = coordinates.getText().toString();
Bundle postParams = new Bundle();
postParams.putString("name", "My Location!");
postParams.putString("caption", "Thanks to Hot and Cold");
postParams.putString("description", text);
postParams.putString("link", null);
postParams.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
Request.Callback callback= new Request.Callback() {
public void onCompleted(Response response) {
JSONObject graphResponse = response
.getGraphObject()
.getInnerJSONObject();
String postId = null;
try {
postId = graphResponse.getString("id");
} catch (JSONException e) {
Log.i(TAG,
"JSON error "+ e.getMessage());
}
FacebookRequestError error = response.getError();
if (error != null) {
Toast.makeText(getActivity()
.getApplicationContext(),
error.getErrorMessage(),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity()
.getApplicationContext(),
postId,
Toast.LENGTH_LONG).show();
}
}
};
Request request = new Request(session, "me/feed", postParams,
HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
}
private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
for (String string : subset) {
if (!superset.contains(string)) {
return false;
}
}
return true;
}
}
So apparently I was spot on about the Fragment causing the issue. to Resolve it, I just added Context to the fragment class, i imported all of the Location logic into MainFragment, and now it works!