Related
I'm trying to catch onMeetingStatusChanged event. But for my case, the onMeetingStatusChanged is sometimes invoked, not all the time. Below is my implemented code:
#Override
protected void onCreate(Bundle savedInstanceState) {
registerListener();
InitAuthSDKHelper.getInstance().initSDK(this, new InitAuthSDKCallback() {
#Override
public void onZoomSDKInitializeResult(int i, int i1) {
}
#Override
public void onZoomAuthIdentityExpired() {
}
});
}
private void registerListener() {
ZoomSDK zoomSDK = ZoomSDK.getInstance();
MeetingService meetingService = zoomSDK.getMeetingService();
if (meetingService != null) {
meetingService.addListener(this);
}
}
#Override
public void onMeetingStatusChanged(MeetingStatus meetingStatus,
int errorCode,
int internalErrorCode) {
LogD.d(TAG, String.valueOf(meetingStatus));
if (meetingStatus == MeetingStatus.MEETING_STATUS_IDLE) {
layout_zoom_loading.setVisibility(View.VISIBLE);
} else {
layout_zoom_loading.setVisibility(View.GONE);
}
if(meetingStatus == MeetingStatus.MEETING_STATUS_FAILED
&& errorCode == MeetingError.MEETING_ERROR_CLIENT_INCOMPATIBLE) {
Toast.makeText(this, "Version of ZoomSDK is too low!", Toast.LENGTH_LONG).show();
}
}
public void joinMeeting(String meetingNo, String meetingPassword) {
ZoomSDK zoomSDK = ZoomSDK.getInstance();
if (!zoomSDK.isInitialized()) {
Toast.makeText(this, getString(R.string.msg_zoom_init_fail), Toast.LENGTH_LONG).show();
return;
}
JoinMeetingHelper.getInstance().joinMeetingWithNumber(this, meetingNo, meetingPassword);
}
I see the cause of this problem. We need to separate the initSDK method to BaseActivity class. So when user forward into the next Activity which runs Zoom meeting, onMeetingStatusChanged always be invoked.
I am trying to launch the NavigationLauncher.startNavigation, from another activity but am unable to do so. I have a button in the second activity which I want to use to start the navigation.
Any suggestions are welcome. Thanks
Here is my code:
/*
fabstart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean simulateRoute = false;
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.directionsRoute(route)
.shouldSimulateRoute(simulateRoute)
.build();
// Call this method with Context from within an Activity
NavigationLauncher.startNavigation(MainActivity.this, options);
}
});
*/
fabstart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, Before_Go.class);
startActivity(intent);
// Here is where I want to go to a new activity, inside this activity have a button to
// launch the "NavigationLauncher.startNavigation"
}
});
NavigationLauncher.startnavigation() opens a new activity that handles the navigation. Therefore it does not matter from where it is called. However, wherever it is called from, the NavigationLauncher must be defined, and the options object that is passed as the second parameter has to contain the directionsRoute object.
Can you please share code of the activity from which you call it, as well as how you initialize and define the options object?
thanks for your response to my question. I am new to stakoverflow, so i hope i get this additional posting of code right.
MainActivity
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, PermissionsListener,
MapboxMap.OnMapLongClickListener, OnRouteSelectionChangeListener {
private static final int REQUEST_CODE_AUTOCOMPLETE = 1;
private static final int ONE_HUNDRED_MILLISECONDS = 100;
//private static final String DROPPED_MARKER_LAYER_ID = "DROPPED_MARKER_LAYER_ID";
//Mapbox
private MapView mapView;
private MapboxMap mapboxMap;
private LocationComponent locationComponent;
private PermissionsManager permissionsManager;
private LocationEngine locationEngine;
private long DEFAULT_INTERVAL_IN_MILLISECONDS = 1000L;
private long DEFAULT_MAX_WAIT_TIME = DEFAULT_INTERVAL_IN_MILLISECONDS * 5;
private final MainActivityLocationCallback callback = new MainActivityLocationCallback(this);
private NavigationMapRoute mapRoute;
private DirectionsRoute route;
private String symbolIconId = "symbolIconId";
private String geojsonSourceLayerId = "geojsonSourceLayerId";
private StyleCycle styleCycle = new StyleCycle();
CarmenFeature selectedCarmenFeature;
CarmenFeature feature;
Layer layer;
private static final String TAG = "DirectionsActivity";
// variables
private FloatingActionButton fablocation;
private FloatingActionButton fabstart;
private FloatingActionButton fabRemoveRoute;
private FloatingActionButton fabStyles;
private TextView search;
private TextView kmDisplay;
private TextView timeDisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.access_token));
setContentView(R.layout.activity_main);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
search=findViewById(R.id.search);
kmDisplay = findViewById(R.id.kmDisplay);
timeDisplay = findViewById(R.id.timeDisplay);
fablocation=findViewById(R.id.fabLocation);
fabstart=findViewById(R.id.fabStart);
fabRemoveRoute=findViewById(R.id.fabRemoveRoute);
fabStyles=findViewById(R.id.fabStyles);
fablocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Location lastKnownLocation = mapboxMap.getLocationComponent().getLastKnownLocation();
// Move map camera back to current device location
mapboxMap.animateCamera(CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder()
.target(new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude()))
.zoom(15)
.build()), 3000);
}
});
}
#Override
public boolean onMapLongClick(#NonNull LatLng point) {
vibrate();
Point destinationPoint = Point.fromLngLat(point.getLongitude(), point.getLatitude());
Point originPoint = Point.fromLngLat(locationComponent.getLastKnownLocation().getLongitude(),
locationComponent.getLastKnownLocation().getLatitude());
GeoJsonSource source = mapboxMap.getStyle().getSourceAs("destination-source-id");
if (source != null) {
source.setGeoJson(Feature.fromGeometry(destinationPoint));
} else {
// Use the map camera target's coordinates to make a reverse geocoding search
reverseGeocode(Point.fromLngLat(point.getLongitude(), point.getLatitude()));
}
getRoute(originPoint, destinationPoint);
if(destinationPoint !=originPoint) {
fabRemoveRoute.setOnClickListener(new View.OnClickListener() {
#SuppressLint("RestrictedApi")
#Override
public void onClick(View view) {
removeRouteAndMarkers();
fabstart.setVisibility(View.INVISIBLE);
fabRemoveRoute.setVisibility(View.INVISIBLE);
//fablocation.setVisibility(View.INVISIBLE);
kmDisplay.setText("");
timeDisplay.setText("");
search.setText(String.format(getString(R.string.hint_where_to)));
Location lastKnownLocation = mapboxMap.getLocationComponent().getLastKnownLocation();
// Move map camera back to current device location
mapboxMap.animateCamera(CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder()
.target(new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude()))
.zoom(15)
.build()), 3000);
}
});
}
//imageView.setEnabled(true);
//imageView.setBackgroundResource(R.color.mapboxBlue);
return true;
}
private void getRoute(Point origin, Point destination) {
NavigationRoute.builder(this)
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.voiceUnits(DirectionsCriteria.METRIC)
.alternatives(true)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#SuppressLint("RestrictedApi")
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
// You can get the generic HTTP info about the response
if (response.isSuccessful()
&& response.body() != null
&& !response.body().routes().isEmpty()) {
List<DirectionsRoute> routes = response.body().routes();
mapRoute.addRoutes(routes);
//routeLoading.setVisibility(View.INVISIBLE);
fabRemoveRoute.setVisibility(View.VISIBLE);
fablocation.setVisibility(View.VISIBLE);
fabstart.setVisibility(View.VISIBLE);
route = response.body().routes().get(0);
routeCalcs();
}
// Once you have the route zoom the camera out to show the route within the bounds of the device
mapboxMap.easeCamera(CameraUpdateFactory.newLatLngBounds(
new LatLngBounds.Builder()
.include(new LatLng(origin.latitude(), origin.longitude()))
.include(new LatLng(destination.latitude(), destination.longitude()))
.build(), 150), 4000);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
Log.e(TAG, "Error: " + throwable.getMessage());
}
});
}
private void removeRouteAndMarkers() {
mapRoute.removeRoute();
toggleLayer();
}
#Override
public void onNewPrimaryRouteSelected(DirectionsRoute directionsRoute) {
route = directionsRoute;
routeCalcs();
}
private void routeCalcs(){
// rounds the kilometer to zero decimals
kmDisplay.setText((int) Math.ceil(route.distance()/1000) + " km");
//Log.d(TAG1,(int) Math.ceil(currentRoute.distance()/1000) + " km");
// This converts to output of duration() in seconds to minutes and hours format
int minutes = (int) (route.duration() / 60);
long hour = TimeUnit.MINUTES.toHours(minutes);
long remainMinute = minutes - TimeUnit.HOURS.toMinutes(hour);
if (hour >= 1) {
timeDisplay.setText(String.format(getString(R.string.hours_textview),hour)
+ String.format(getString(R.string.minutes_textview),remainMinute));
} else {
timeDisplay.setText(String.format(getString(R.string.minutes_textview), remainMinute));
}
}
private void reverseGeocode(Point point) {
if (selectedCarmenFeature == null) {
try {
MapboxGeocoding client = MapboxGeocoding.builder()
.accessToken(getString(R.string.access_token))
.query(Point.fromLngLat(point.longitude(), point.latitude()))
.geocodingTypes(GeocodingCriteria.TYPE_ADDRESS)
.build();
client.enqueueCall(new Callback<GeocodingResponse>() {
#Override
public void onResponse(Call<GeocodingResponse> call, Response<GeocodingResponse> response) {
if (response.body() != null) {
List<CarmenFeature> results = response.body().features();
if (results.size() > 0) {
feature = results.get(0);
// If the geocoder returns a result, we take the first in the list and show a Toast with the place name.
mapboxMap.getStyle(new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
if (style.getLayer("SYMBOL_LAYER_ID") != null) {
search.setText(feature.placeName());
}
}
});
} else {
Toast.makeText(MainActivity.this,
getString(R.string.location_picker_dropped_marker_snippet_no_results), Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onFailure(Call<GeocodingResponse> call, Throwable throwable) {
Timber.e("Geocoding Failure: %s", throwable.getMessage());
}
});
} catch (ServicesException servicesException) {
Timber.e("Error geocoding: %s", servicesException.toString());
servicesException.printStackTrace();
}
}
}
#Override
public void onMapReady(#NonNull MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style){
mapRoute = new NavigationMapRoute(null, mapView, mapboxMap);
mapRoute.setOnRouteSelectionChangeListener(MainActivity.this::onNewPrimaryRouteSelected);
mapboxMap.addOnMapLongClickListener(MainActivity.this);
initializeLocationComponent(style);
// Add the symbol layer icon to map for future use
style.addImage(symbolIconId, BitmapFactory.decodeResource(
MainActivity.this.getResources(), R.drawable.mapbox_marker_icon_default));
// Create an empty GeoJSON source using the empty feature collection
setUpSource(style);
// Set up a new symbol layer for displaying the searched location's feature coordinates
setupLayer(style);
fabStyles.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mapboxMap != null) {
mapboxMap.setStyle(styleCycle.getNextStyle());
}
}
});
initSearchFab();
}
});
// This is the code in the docs, but this launches the turn by turn navigation inside this activity
// and this is not what I need
/* fabstart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean simulateRoute = false;
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.directionsRoute(route)
.shouldSimulateRoute(simulateRoute)
.build();
// Call this method with Context from within an Activity
NavigationLauncher.startNavigation(MainActivity.this, options);
}
});*/
fabstart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, Before_Go.class);
startActivity(intent);
// Here is where I want to go to a new activity, inside this activity have a button to
// launch the "NavigationLauncher.startNavigation"
}
});
}
private static class StyleCycle {
private static final String[] STYLES = new String[] {
Style.MAPBOX_STREETS,
Style.OUTDOORS,
Style.LIGHT,
Style.DARK,
//Style.SATELLITE_STREETS,
Style.TRAFFIC_DAY,
Style.TRAFFIC_NIGHT
};
private int index;
private String getNextStyle() {
index++;
if (index == STYLES.length) {
index = 0;
}
return getStyle();
}
private String getStyle() {
return STYLES[index];
}
}
private void initSearchFab() {
findViewById(R.id.search).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new PlaceAutocomplete.IntentBuilder()
.accessToken(Mapbox.getAccessToken())
.placeOptions(PlaceOptions.builder()
.backgroundColor(Color.parseColor("#EEEEEE"))
.limit(10)
//.addInjectedFeature(home)
//.addInjectedFeature(work)
.build(PlaceOptions.MODE_CARDS))
.build(MainActivity.this);
startActivityForResult(intent, REQUEST_CODE_AUTOCOMPLETE);
}
});
}
#SuppressWarnings( {"MissingPermission"})
private void initializeLocationComponent(#NonNull Style loadedMapStyle) {
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(this)) {
locationComponent = mapboxMap.getLocationComponent();
// Set the LocationComponent activation options
LocationComponentActivationOptions locationComponentActivationOptions =
LocationComponentActivationOptions.builder(this, loadedMapStyle)
.useDefaultLocationEngine(false)
.build();
// Activate with the LocationComponentActivationOptions object
locationComponent.activateLocationComponent(locationComponentActivationOptions);
locationComponent.setLocationComponentEnabled(true);
locationComponent.setRenderMode(RenderMode.NORMAL);
locationComponent.setCameraMode(CameraMode.TRACKING);
//locationComponent.zoomWhileTracking(10d);
initLocationEngine();
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_AUTOCOMPLETE) {
// Retrieve selected location's CarmenFeature
selectedCarmenFeature = PlaceAutocomplete.getPlace(data);
search.setText(selectedCarmenFeature.placeName());
// Create a new FeatureCollection and add a new Feature to it using selectedCarmenFeature above.
// Then retrieve and update the source designated for showing a selected location's symbol layer icon
if (mapboxMap != null) {
Style style = mapboxMap.getStyle();
if (style != null) {
GeoJsonSource source = style.getSourceAs(geojsonSourceLayerId);
if (source != null) {
source.setGeoJson(FeatureCollection.fromFeatures(
new Feature[] {Feature.fromJson(selectedCarmenFeature.toJson())}));
}
// Move map camera to the selected location
mapboxMap.animateCamera(CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder()
.target(new LatLng(((Point) selectedCarmenFeature.geometry()).latitude(),
((Point) selectedCarmenFeature.geometry()).longitude()))
.zoom(14)
.build()), 4000);
}
}
}
}
#SuppressLint("MissingPermission")
private void vibrate() {
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (vibrator == null) {
return;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
vibrator.vibrate(VibrationEffect.createOneShot(ONE_HUNDRED_MILLISECONDS, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
vibrator.vibrate(ONE_HUNDRED_MILLISECONDS);
}
}
/**
* Set up the LocationEngine and the parameters for querying the device's location
*/
#SuppressLint("MissingPermission")
private void initLocationEngine() {
locationEngine = LocationEngineProvider.getBestLocationEngine(this);
LocationEngineRequest request = new LocationEngineRequest.Builder(DEFAULT_INTERVAL_IN_MILLISECONDS)
.setPriority(LocationEngineRequest.PRIORITY_HIGH_ACCURACY)
.setMaxWaitTime(DEFAULT_MAX_WAIT_TIME).build();
locationEngine.requestLocationUpdates(request, callback, getMainLooper());
locationEngine.getLastLocation(callback);
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
Toast.makeText(this, R.string.user_location_permission_explanation, Toast.LENGTH_LONG).show();
}
#Override
public void onPermissionResult(boolean granted) {
if (granted) {
if (mapboxMap.getStyle() != null) {
initializeLocationComponent(mapboxMap.getStyle());
}
} else {
Toast.makeText(this, R.string.user_location_permission_not_granted, Toast.LENGTH_LONG).show();
finish();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
private static class MainActivityLocationCallback
implements LocationEngineCallback<LocationEngineResult> {
private final WeakReference<MainActivity> activityWeakReference;
MainActivityLocationCallback(MainActivity activity) {
this.activityWeakReference = new WeakReference<>(activity);
}
#Override
public void onSuccess(LocationEngineResult result) {
MainActivity activity = activityWeakReference.get();
if (activity != null) {
Location location = result.getLastLocation();
if (location == null) {
return;
}
if (activity.mapboxMap != null && result.getLastLocation() != null) {
activity.mapboxMap.getLocationComponent().forceLocationUpdate(result.getLastLocation());
}
}
}
#Override
public void onFailure(#NonNull Exception exception) {
Timber.d(exception.getLocalizedMessage());
MainActivity activity = activityWeakReference.get();
if (activity != null) {
Toast.makeText(activity, exception.getLocalizedMessage(),
Toast.LENGTH_SHORT).show();
}
}
}
/**
* Adds the GeoJSON source to the map
*/
private void setUpSource(#NonNull Style loadedMapStyle) {
loadedMapStyle.addSource(new GeoJsonSource(geojsonSourceLayerId));
}
/**
* Setup a layer with maki icons, eg. west coast city.
*/
private void setupLayer(#NonNull Style loadedMapStyle) {
loadedMapStyle.addLayer(new SymbolLayer("SYMBOL_LAYER_ID", geojsonSourceLayerId).withProperties(
iconImage(symbolIconId),
iconOffset(new Float[] {0f, -8f})
));
}
// This method will remove the destination icon
private void toggleLayer() {
mapboxMap.getStyle(new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
layer = style.getLayer("SYMBOL_LAYER_ID");
if (layer != null) {
if (VISIBLE.equals(layer.getVisibility().getValue())) {
layer.setProperties(visibility(NONE));
} else {
layer.setProperties(visibility(VISIBLE));
}
}
}
});
}
// Add the mapView lifecycle to the activity's lifecycle methods
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onStart() {
super.onStart();
mapView.onStart();
if (mapRoute != null) {
mapRoute.onStart();
}
}
#Override
protected void onStop() {
super.onStop();
mapView.onStop();
if (mapRoute != null) {
mapRoute.onStop();
}
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
}
Before_Go - this is the activity where i want to click the button and launch the navigationlauncher
public class Before_Go extends AppCompatActivity {
Button btnGo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_before__go);
btnGo=findViewById(R.id.btnGo);
btnGo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent btnGo = new Intent(Before_Go.this, Go.class);
startActivity(btnGo);
}
});
}
}
GoActivity, this is where the navigation launcher needs to launch after the button click in the Before_Go activity
public class Go extends AppCompatActivity implements OnNavigationReadyCallback,
NavigationListener {
private NavigationView navigationView;
private DirectionsRoute route;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
setTheme(R.style.Theme_AppCompat_NoActionBar);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_go);
navigationView = findViewById(R.id.navigationViewB);
navigationView.onCreate(savedInstanceState);
}
/*fabstart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean simulateRoute = false;
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.directionsRoute(route)
.shouldSimulateRoute(simulateRoute)
.build();
// Call this method with Context from within an Activity
NavigationLauncher.startNavigation(MainActivity.this, options);
}
});*/
#Override
public void onNavigationReady(boolean isRunning) {
MapboxNavigationOptions.Builder navigationOptions = MapboxNavigationOptions.builder();
NavigationViewOptions.Builder options = NavigationViewOptions.builder();
options.navigationListener(this);
extractRoute(options);
extractConfiguration(options);
options.navigationOptions(navigationOptions.build());
//options.navigationOptions(new MapboxNavigationOptions.Builder().build());
launchNavigationWithRoute();
//navigationView.startNavigation(options.build());
navigationView.initialize(this);
/*MapboxNavigationOptions.Builder navigationOptions = MapboxNavigationOptions.builder();
NavigationViewOptions.Builder options = NavigationViewOptions.builder();
options.navigationListener(this);
extractRoute(options);
options.navigationOptions(navigationOptions.build());
//navigationView = NavigationLauncher.startNavigation(options.build());
navigationView.startNavigation(options.build());
initialize();*/
}
#Override
public void onCancelNavigation() {
// Navigation canceled, finish the activity
showCustomCancel();
finishNavigation();
}
#Override
public void onNavigationFinished() {
}
#Override
public void onNavigationRunning() {
}
private void launchNavigationWithRoute() {
if (route != null) {
NavigationLauncher.startNavigation(this, route);
}
}
private void extractRoute(NavigationViewOptions.Builder options) {
route = NavigationLauncher.extractRoute(this);
options.directionsRoute(route);
}
private void extractConfiguration(NavigationViewOptions.Builder options) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
options.shouldSimulateRoute(preferences.getBoolean(NavigationConstants.NAVIGATION_VIEW_SIMULATE_ROUTE, false));
}
private void finishNavigation() {
NavigationLauncher.cleanUpPreferences(this);
finish();
}
private void showCustomCancel(){
ViewGroup viewGroup = findViewById(android.R.id.content);
View dialogView2 = LayoutInflater.from(this).inflate(R.layout.my_dialog_logout, viewGroup, false);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(dialogView2);
AlertDialog alertDialog2 = builder.create();
Button buttonNo = dialogView2.findViewById(R.id.buttonNo);
Button buttonYes = dialogView2.findViewById(R.id.buttonYes);
buttonYes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (alertDialog2 != null && alertDialog2.isShowing()) {
alertDialog2.dismiss();
}
Intent intentCancelTrip_Yes = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intentCancelTrip_Yes);
finish();
navigationView.stopNavigation();
}
});
buttonNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (alertDialog2 != null && alertDialog2.isShowing()) {
alertDialog2.dismiss();
}
navigationView.onResume();
}
});
alertDialog2.show();
}
/* private void initialize() {
Parcelable position = getIntent().getParcelableExtra(NavigationConstants.NAVIGATION_VIEW_INITIAL_MAP_POSITION);
if (position != null) {
navigationView.initialize(this, (CameraPosition) position);
} else {
navigationView.initialize(this);
}
}*/
#Override
public void onStart() {
super.onStart();
navigationView.onStart();
}
#Override
public void onResume() {
super.onResume();
navigationView.onResume();
}
#Override
public void onLowMemory() {
super.onLowMemory();
navigationView.onLowMemory();
}
#Override
public void onBackPressed() {
// If the navigation view didn't need to do anything, call super
if (!navigationView.onBackPressed()) {
super.onBackPressed();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
navigationView.onSaveInstanceState(outState);
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
navigationView.onRestoreInstanceState(savedInstanceState);
}
#Override
public void onPause() {
super.onPause();
navigationView.onPause();
}
#Override
public void onStop() {
super.onStop();
navigationView.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
navigationView.onDestroy();
}
}
NavigationLauncher class i am using to try initiate the navigation inside the Go activity
public class NavigationLauncher {
public static void startNavigation(Activity activity, DirectionsRoute route) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(NavigationConstants.NAVIGATION_VIEW_ROUTE_KEY, new Gson().toJson(route));
//editor.putString(NavigationConstants.NAVIGATION_VIEW_AWS_POOL_ID, awsPoolId);
//editor.putBoolean(NavigationConstants.NAVIGATION_VIEW_SIMULATE_ROUTE, simulateRoute);
editor.apply();
Intent navigationActivity = new Intent(activity, Go.class);
activity.startActivity(navigationActivity);
}
/* public static void startNavigation(Activity activity, NavigationLauncherOptions options){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
SharedPreferences.Editor editor = preferences.edit();
storeDirectionsRouteValue(options, editor);
storeConfiguration(options, editor);
editor.apply();
Intent navigationActivity = new Intent(activity, Go.class);
storeInitialMapPosition(options, navigationActivity);
activity.startActivity(navigationActivity);
}*/
private static void storeConfiguration(NavigationLauncherOptions options, SharedPreferences.Editor editor) {
editor.putBoolean(NavigationConstants.NAVIGATION_VIEW_SIMULATE_ROUTE, options.shouldSimulateRoute());
}
private static void storeDirectionsRouteValue(NavigationLauncherOptions options, SharedPreferences.Editor editor) {
editor.putString(NavigationConstants.NAVIGATION_VIEW_ROUTE_KEY, options.directionsRoute().toJson());
/*if (options.directionsRoute() != null) {
storeDirectionsRouteValue(options, editor);
}
else {
throw new RuntimeException("A valid DirectionsRoute or origin and "
+ "destination must be provided in NavigationViewOptions");
}*/
}
static DirectionsRoute extractRoute(Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
String directionsRouteJson = preferences.getString(NavigationConstants.NAVIGATION_VIEW_ROUTE_KEY, "");
return DirectionsRoute.fromJson(directionsRouteJson);
}
static void cleanUpPreferences(Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor
.remove(NavigationConstants.NAVIGATION_VIEW_ROUTE_KEY)
.remove(NavigationConstants.NAVIGATION_VIEW_SIMULATE_ROUTE)
.apply();
}
private static void storeInitialMapPosition(NavigationLauncherOptions options, Intent navigationActivity) {
if (options.initialMapCameraPosition() != null) {
navigationActivity.putExtra(
NavigationConstants.NAVIGATION_VIEW_INITIAL_MAP_POSITION, options.initialMapCameraPosition()
);
}
}
}
I assume that the application crashes once the activity "Go.java" is launched.
The problem appears to be that you are not instantiating the Mapbox object in this activity. You are doing it correclty in your "mainactivity.java" however you are missing it in "go.java". Make sure to have the line Mapbox.getInstance(this, getString(R.string.access_token)); also in your "go.java" activity before calling setContentView()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.access_token));
setContentView(R.layout.activity_main);
I am doing live streaming for the youtube videos. By entering into the picture in picture mode the player pause the video with the Error UNAUTHORIZED_OVERLAY .
VideoLayout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linear_youtube_rootlayout"
android:orientation="vertical"
android:background="#color/black"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtube_player"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
ACtivity.cs
[Activity(Label = "", ResizeableActivity = true, Theme = "#style/Theme.MyAppTheme", TaskAffinity = "com.m", MainLauncher =true,AllowTaskReparenting = true, AutoRemoveFromRecents = true, ExcludeFromRecents = true, LaunchMode = Android.Content.PM.LaunchMode.SingleTask, SupportsPictureInPicture = true/*, ConfigurationChanges = Android.Content.PM.ConfigChanges.ScreenSize | Android.Content.PM.ConfigChanges.SmallestScreenSize | Android.Content.PM.ConfigChanges.ScreenLayout | Android.Content.PM.ConfigChanges.Orientation*/)]
public class YoutubeActivity: YouTubeBaseActivity,IYouTubePlayerOnInitializedListener,View.IOnClickListener,IYouTubePlayerPlayerStateChangeListener,IYouTubePlayerPlaybackEventListener,IYouTubePlayerOnFullscreenListener
{
private YouTubePlayerView mYoutubePlayer;
private PictureInPictureParams.Builder pictureInPictureParamsBuilder =
new PictureInPictureParams.Builder();
private LinearLayout linear_rootlayout;
private TextView txtMinimizevideo,txtCloseVideo;
private IYouTubePlayer youtubevideo;
private bool isbackbuttonpress = false;
private RelativeLayout relative_youtubecontrols;
public void OnInitializationFailure(IYouTubePlayerProvider p0, YouTubeInitializationResult p1)
{
}
public void OnInitializationSuccess(IYouTubePlayerProvider provider, IYouTubePlayer player, bool p2)
{
this.youtubevideo = player;
// youtubevideo.SetPlayerStyle(YouTubePlayerPlayerStyle.Minimal);
youtubevideo.SetOnFullscreenListener(this);
youtubevideo.SetPlayerStateChangeListener(this);
youtubevideo.SetPlaybackEventListener(this);
youtubevideo.FullscreenControlFlags = YouTubePlayer.FullscreenFlagCustomLayout;
youtubevideo.LoadVideo("VideoKey");
}
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.youtube_player_layout);
mYoutubePlayer = FindViewById<YouTubePlayerView>(Resource.Id.youtube_player);
linear_rootlayout = FindViewById<LinearLayout>(Resource.Id.linear_youtube_rootlayout);
relative_youtubecontrols = FindViewById<RelativeLayout>(Resource.Id.rel_youtube_control);
mYoutubePlayer.Initialize("SerialKey", this);
}
public override void OnPictureInPictureModeChanged(bool isInPictureInPictureMode, Configuration newConfig)
{
base.OnPictureInPictureModeChanged(isInPictureInPictureMode, newConfig);
if (IsInPictureInPictureMode)
{
youtubevideo.Release();
Window.AddFlags(WindowManagerFlags.Fullscreen);
}
}
public override void OnBackPressed()
{
pictureInPictureMode();
}
protected override void OnUserLeaveHint()
{
base.OnUserLeaveHint();
if (!IsInPictureInPictureMode)
{
pictureInPictureMode();
}
}
private void pictureInPictureMode()
{
isbackbuttonpress = true;
Rational aspectRatio = new Rational(200, 110);
pictureInPictureParamsBuilder.SetAspectRatio(aspectRatio).Build();
EnterPictureInPictureMode(pictureInPictureParamsBuilder.Build());
}
public void OnBuffering(bool p0)
{
}
public void OnPaused()
{
}
public void OnPlaying()
{
}
public void OnSeekTo(int p0)
{
}
public void OnStopped()
{
// youtubevideo.Play();
}
public void OnAdStarted()
{
}
public void OnError(YouTubePlayerErrorReason p0)
{
}
public void OnLoaded(string p0)
{
youtubevideo.Play();
}
public void OnLoading()
{
}
public void OnVideoEnded()
{
}
public void OnVideoStarted()
{
}
public void OnFullscreen(bool p0)
{
}
}
}
I am loading the video on the oninitializedsuccess and play the video in the on Loaded.
I have tried all the possible solutions so that no view is on the top of the youtube player view but it always gives me same error.
I think the issue is with your OnPictureInPictureModeChanged method..
public override void OnPictureInPictureModeChanged(bool isInPictureInPictureMode, Configuration newConfig)
{
base.OnPictureInPictureModeChanged(isInPictureInPictureMode, newConfig);
if (IsInPictureInPictureMode)
{
youtubevideo.Release();
Window.AddFlags(WindowManagerFlags.Fullscreen);
}
}
The reason I see here why the error UNAUTHORIZED_OVERLAY pops up is your AddFlags Call when in PIP Mode..
Modify your code as below and check to see if the error persists..
#Override
public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode) {
if (isInPictureInPictureMode) {
// Hide the controls in picture-in-picture mode.
...
} else {
// Restore the playback UI based on the playback status.
...
}
}
With regards to your addflags call, try the following code:
#Override
public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode) {
super.onPictureInPictureModeChanged(isInPictureInPictureMode);
if (!isInPictureInPictureMode) {
getApplication().startActivity(new Intent(this, getClass())
.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT));
}
}
I'm using this example code to build a MediaPlayer Service. I have it more or less working, however if a user returns to the Activity that contains the media controls, I need to detect what state the MediaPlayer is in. The code I'm currently using throws a NullReferenceException error in onResume because getPlaybackState() is always null.
I'm new to using MediaSessionCompat and according to the documentation, I can get the current session somehow:
"Once a session is created the owner of the session may pass its session token to other processes to allow them to create a MediaControllerCompat to interact with the session."
public class MediaActivity extends AppCompatActivity {
private MediaBrowserCompat mMediaBrowserCompat;
private MediaControllerCompat mMediaControllerCompat;
private Activity mActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_media);
mActivity = this;
mPlayButton = (Button)findViewById(R.id.btn_play);
mMediaBrowserCompat = new MediaBrowserCompat(
getApplicationContext(),
new ComponentName(mContext, MediaPlayerService.class),
mMediaBrowserCompatConnectionCallback,
getIntent().getExtras()
);
mMediaBrowserCompat.connect();
mPlayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if( mCurrentState == STATE_PAUSED ) {
getSupportMediaController().getTransportControls().play();
mCurrentState = STATE_PLAYING;
mPlayButton.setText("Pause");
} else {
MediaControllerCompat.getMediaController(mActivity).getTransportControls().pause();
mCurrentState = STATE_PAUSED;
mPlayButton.setText("Play");
}
}
});
#Override
public void onResume() {
super.onResume();
if (MediaControllerCompat.getMediaController(mActivity).getPlaybackState().getState() == PlaybackStateCompat.STATE_PLAYING) {
mPlayButton.setText("Pause")
}
else{
mPlayButton.setText("Play")
}
}
private MediaBrowserCompat.ConnectionCallback mMediaBrowserCompatConnectionCallback = new MediaBrowserCompat.ConnectionCallback() {
#Override
public void onConnected() {
super.onConnected();
try {
mMediaControllerCompat = new MediaControllerCompat(PodcastEpisodeActivity.this, mMediaBrowserCompat.getSessionToken());
mMediaControllerCompat.registerCallback(mMediaControllerCompatCallback);
MediaControllerCompat.setMediaController(mActivity, mMediaControllerCompat);
MediaControllerCompat.getMediaController(mActivity).getTransportControls().playFromUri(Uri.parse("http://www.url.com"), extras);
} catch( RemoteException e ) {
Log.e(mActivity.getPackageName(), e.toString());
}
}
};
private MediaControllerCompat.Callback mMediaControllerCompatCallback = new MediaControllerCompat.Callback() {
#Override
public void onPlaybackStateChanged(PlaybackStateCompat state) {
super.onPlaybackStateChanged(state);
if (state == null ) return;
switch (state.getState()) {
case PlaybackStateCompat.STATE_PLAYING: {
mCurrentState = STATE_PLAYING;
break;
}
case PlaybackStateCompat.STATE_PAUSED: {
mCurrentState = STATE_PAUSED;
break;
}
}
}
};
}
}
I couldn't figure out a way through the available API, so I'm just tracking which media is being played through local storage (sqlite) and updating the display through that. Probably not the most elegant solution but it works.
I have an issue with a small project in android studio where on animal drawings guess things etc. But guess I have to write the name to accept a button and image lights up and goes to the next , what I want you to show me an answer with buttons say 3 button 1 is the correct answer and the other two false I took a long time with this and even I can not do it if I would appreciate any help
Here the code of the class where the shadows and images run
public class Categoria extends Activity {
public static String[] nombre_cosa={"cerdo","ave","caballo","conejo","elefante","gallina","gato",
"rana","perro","pato","oveja","leon","jirafa",
"raton","vaca","autobus","automovil","avion","bicicleta","camioneta",
"casa","celular","guitarra","motocicleta","silla","television","durazno","fresa","mango",
"uvas","sandia","platano","coco","pera","naranja","manzana",
"bart","batman","cerebro","chavo","goku","homero","marge",
"patricio","pepa","phineas","quico","spiderman","thor","superman"};
public static String[] sombra_cosa={"s_cerdo","s_ave","s_caballo","s_conejo","s_elefante","s_gallina","s_gato",
"s_rana","s_perro","s_pato","s_oveja","s_leon","s_jirafa",
"s_raton","s_vaca","s_autobus","s_automovil","s_avion","s_bicicleta","s_camioneta",
"s_casa","s_celular","s_guitarra","s_motocicleta","s_silla","s_television","s_durazno","s_fresa","s_mango",
"s_uvas","s_sandia","s_platano","s_coco","s_pera","s_naranja","s_manzana",
"s_bart","s_batman","s_cerebro","s_chavo","s_goku","s_homero","s_marge",
"s_patricio","s_pepa","s_phineas","s_quico","s_spiderman","s_thor","s_superman"};
public static boolean[] estado={false,false,false,false,false,false,
false,false,false,false,false,false,
false,false,false,false,false,false,false,
false,false,false,false,false,false,false,false,
false,false,false,false,false,false,false,
false,false,false,false,false,false,false,false,false,false,
false,false,false,false,false,false};
public static int cosas_adivinadas=0;
private int intentos=3;
private Button aceptar;
private TextView mensaje_intentos,mensaje_cuenta;
private EditText usuario_cosa;
private int numero_generado=0;
private ImageView miimagen;
private MediaPlayer reproductor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_categoria);
aceptar=(Button) findViewById(R.id.btnaceptar);
mensaje_intentos=(TextView) findViewById(R.id.lblintentos);
mensaje_cuenta=(TextView) findViewById(R.id.lblcuenta);
usuario_cosa=(EditText) findViewById(R.id.txtcosa);
miimagen=(ImageView) findViewById(R.id.imgcosa);
CargarPreferencias();
new MiTarea().execute();
reproductor= MediaPlayer.create(this,R.raw.yansha);
reproductor.setLooping(true);
reproductor.start();
mensaje_intentos.setText("Tiene " + intentos + " intentos");
aceptar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String nombre=usuario_cosa.getText().toString().toLowerCase();
if(nombre.equals(nombre_cosa[numero_generado]))
{
establecer_cosa(numero_generado);
estado[numero_generado]=true;
cosas_adivinadas++;
esperar();
}
else
{
Toast.makeText(getApplicationContext(), "Incorrecto", Toast.LENGTH_SHORT).show();
intentos=intentos-1;
mensaje_intentos.setText("Tiene " + intentos + " intentos");
}
if (intentos==0)
{
removerPreferencias();
Intent i = new Intent(Categoria.this,Perder.class);
startActivity(i);
finish();
}
}
});
}
#Override
protected void onResume() {
super.onResume();
reproductor.start();
}
public void esperar()
{
new CountDownTimer(5000,1000)
{
#Override
public void onTick(long millisUntilFinished) {
mensaje_cuenta.setText("Generando en " + (millisUntilFinished/1000));
}
#Override
public void onFinish() {
if (cosas_adivinadas==nombre_cosa.length)
{
finish();
}
else
{
new MiTarea().execute();
mensaje_cuenta.setText("");
usuario_cosa.setText("");
}
}
}.start();
}
public void CargarPreferencias()
{
SharedPreferences mispreferencias = getSharedPreferences("PreferenciaCosa", Context.MODE_PRIVATE);
intentos=mispreferencias.getInt("intentos",3);
cosas_adivinadas=mispreferencias.getInt("adivinados",0);
for (int i=0;i<nombre_cosa.length;i++)
{
estado[i]=mispreferencias.getBoolean(nombre_cosa[i],false);
}
}
public void GuardarPreferencias()
{
SharedPreferences mispreferencias = getSharedPreferences("PreferenciaCosa", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mispreferencias.edit();
editor.putInt("intentos",intentos);
editor.putInt("adivinados",cosas_adivinadas);
for (int i=0;i<nombre_cosa.length;i++)
{
editor.putBoolean(nombre_cosa[i], estado[i]);
}
editor.commit();
}
private void establecer_cosa(int numero)
{
int resId = getResources().getIdentifier(nombre_cosa[numero], "drawable", getPackageName());
miimagen.setImageResource(resId);
}
private void establecer_sombra(int numero)
{
int resId = getResources().getIdentifier(sombra_cosa[numero], "drawable", getPackageName());
miimagen.setImageResource(resId);
}
private void removerPreferencias()
{
SharedPreferences settings = getSharedPreferences("PreferenciaCosa", Context.MODE_PRIVATE);
settings.edit().clear().commit();
}
#Override
protected void onStop() {
if (intentos==0)
{
removerPreferencias();
}
else
{
GuardarPreferencias();
}
reproductor.pause();
super.onStop();
}
#Override
protected void onDestroy() {
if (reproductor.isPlaying())
{
reproductor.stop();
reproductor.release();
}
super.onDestroy();
}
private class MiTarea extends AsyncTask<Void, Void, Void> {
private int valor_generado;
#Override
protected Void doInBackground(Void... params) {
do {
valor_generado=((int)(Math.random()*nombre_cosa.length));
}while(estado[valor_generado]);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
numero_generado = valor_generado;
establecer_sombra(valor_generado);
super.onPostExecute(aVoid);
}
}
}
Create a variable like this:
boolean isTextCorrect = false;
In default, the button is invisible.
Implement a listener. If the text in the textfield changed and its correct switch isTextCorrect to true and make the button visible (clickable).
if(isTextCorrect){
button.setVisible(View.VISIBLE);
}