I'm trying to create a small application which both retrieves depth data and shows a little "preview" from my RGB camera.
Here's the code of my MainScreen class:
private static final String TAG = MainScreen.class.getSimpleName();
public static TangoConfig mConfig;
public static Tango mTango;
public TangoCameraPreview preview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
preview = new TangoCameraPreview(this);
ViewGroup layout = (ViewGroup)findViewById(R.id.content_main_screen);
layout.addView(preview);
}
#Override
protected void onDestroy() {
super.onDestroy();
preview.disconnectFromTangoCamera();
mTango.disconnect();
}
#Override
protected void onPause() {
super.onPause();
preview.onPause();
synchronized (this) {
try {
mTango.disconnect();
} catch (TangoErrorException e) {
Log.e(TAG, getString(R.string.exception_tango_error), e);
}
}
}
#Override
protected void onResume() {
super.onResume();
mTango = new Tango(MainScreen.this, new Runnable() {
#Override
public void run() {
synchronized (MainScreen.this) {
try {
mConfig = setupTangoConfig(mTango);
mTango.connect(mConfig);
preview.connectToTangoCamera(mTango, TangoCameraIntrinsics.TANGO_CAMERA_COLOR);
startupTango();
} catch (TangoOutOfDateException e) {
Log.e(TAG, getString(R.string.exception_out_of_date), e);
} catch (TangoErrorException e) {
Log.e(TAG, getString(R.string.exception_tango_error), e);
} catch (TangoInvalidException e) {
Log.e(TAG, getString(R.string.exception_tango_invalid), e);
}
}
}
});
preview.onResume();
}
private TangoConfig setupTangoConfig(Tango tango) {
TangoConfig config = tango.getConfig(TangoConfig.CONFIG_TYPE_DEFAULT);
config.putBoolean(TangoConfig.KEY_BOOLEAN_LOWLATENCYIMUINTEGRATION, true);
config.putBoolean(TangoConfig.KEY_BOOLEAN_DEPTH, true);
config.putInt(TangoConfig.KEY_INT_DEPTH_MODE, TangoConfig.TANGO_DEPTH_MODE_POINT_CLOUD);
return config;
}
private void startupTango() {
final ArrayList<TangoCoordinateFramePair> framePairs =
new ArrayList<TangoCoordinateFramePair>();
mTango.connectListener(framePairs, new Tango.OnTangoUpdateListener() {
#Override
public void onPoseAvailable(final TangoPoseData pose) {
// We are not using TangoPoseData for this application.
}
#Override
public void onXyzIjAvailable(TangoXyzIjData xyzIj) {
// We are not using onXyzIjAvailable for this app.
}
#Override
public void onPointCloudAvailable(final TangoPointCloudData pointCloudData) {
logPointCloud(pointCloudData);
}
#Override
public void onTangoEvent(final TangoEvent event) {
// Ignoring TangoEvents.
}
#Override
public void onFrameAvailable(int cameraId) {
if(cameraId == TangoCameraIntrinsics.TANGO_CAMERA_COLOR) {
preview.onFrameAvailable();
}
}
});
}
private void logPointCloud(TangoPointCloudData pointCloudData) {
Log.i(TAG, String.format(getString(R.string.log_pointcloud_data),
pointCloudData.numPoints,
calculateAveragedDepth(pointCloudData.points, pointCloudData.numPoints)));
}
private float calculateAveragedDepth(FloatBuffer pointCloudBuffer, int numPoints) {
float totalZ = 0;
float averageZ = 0;
if (numPoints != 0) {
int numFloats = 4 * numPoints;
for (int i = 2; i < numFloats; i = i + 4) {
totalZ = totalZ + pointCloudBuffer.get(i);
}
averageZ = totalZ / numPoints;
}
return averageZ;
}
When I start this code, the TangoCameraPreview stays empty, and the onFrameAvailable()-Method is never called.
I have included Camera persmissions in my Android manifest xml, but it still isn't calling the handler.
Sadly, I haven't found any good tutorials on this topic, and since this is just a first step in my project, I don't want to write my own renderer just yet, if at all.
What could be the problem?
after startup Tango make a call to 'connectTextureId':
tango.ConnectTextureId(TangoCameraIntrinsics.TangoCameraColor, -1);
Related
I'm actually trying to use the useroffroute function but it's not working, I saw this other post and it said to NavigationView, only I don't know how to do it exactly. I am currently using this code to detect if the user has left the route, but he is not calling the useroffroute function. What I'm trying to do is that when the user leaves the route he fires a Toast for the user, but unfortunately I was not successful.
public class mapbox extends AppCompatActivity{
private MapView mapView;
Button button;
private static final String TAG = "resultados";
private MapboxNavigation navigation;
private boolean running;
private NavigationMapboxMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.mapbox_access_token));
setContentView(R.layout.activity_mapbox);
button = findViewById(R.id.button);
MapboxNavigationOptions options = MapboxNavigationOptions.builder().isDebugLoggingEnabled(true).build();
navigation = new MapboxNavigation(getApplicationContext(), getString(R.string.mapbox_access_token), options);
/*
navigation.addOffRouteListener(new OffRouteListener() {
#Override
public void userOffRoute(Location location) {
Toast.makeText(getApplicationContext(), "Off route detected.........", Toast.LENGTH_SHORT).show();
// Make sure you call for a new DirectionsRoute object
// and end by calling MapboxNavigation#startNavigation on a successful
}
});
*/
/*
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(#NonNull MapboxMap mapboxMap) {
mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
// Map is set up and the style has loaded. Now you can add data or make other map adjustments
}
});
}
});
*/
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// From Mapbox to The White House
Point origin = Point.fromLngLat(-38.62882018, -3.78666528);
Point destination = Point.fromLngLat(-38.56038094, -3.7337361F);
NavigationRoute.builder(mapbox.this)
.accessToken(getString(R.string.mapbox_access_token))
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
Log.i(TAG, response+"");
// Route fetched from NavigationRoute
DirectionsRoute route = response.body().routes().get(0);
// Create a NavigationLauncherOptions object to package everything together
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.directionsRoute(route)
.shouldSimulateRoute(false)
.build();
// Call this method with Context from within an Activity
NavigationLauncher.startNavigation(mapbox.this, options);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable t) {
}
});
}
});
}
#Override
protected void onStart() {
super.onStart();
//mapView.onStart();
}
#Override
protected void onResume() {
super.onResume();
//mapView.onResume();
}
#Override
protected void onPause() {
super.onPause();
//mapView.onPause();
}
#Override
protected void onStop() {
super.onStop();
//mapView.onStop();
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState, #NonNull PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
//mapView.onSaveInstanceState(outState);
}
#Override
public void onLowMemory() {
super.onLowMemory();
//mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
//mapView.onDestroy();
}
}
After many hours looking for a solution, I finally found one. You have to use NavigationViewer to obtain the parameters that the application passes, so you can listen if the user leaves the route. Here's an example:
public class last extends AppCompatActivity implements OnNavigationReadyCallback,
NavigationListener, RouteListener, ProgressChangeListener {
private NavigationView navigationView;
private boolean dropoffDialogShown;
private Location lastKnownLocation;
private List<Point> points = new ArrayList<>();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
Mapbox.getInstance(this, getString(R.string.mapbox_access_token));
setTheme(R.style.Theme_AppCompat_NoActionBar);
super.onCreate(savedInstanceState);
points.add(Point.fromLngLat(-38.62882018, -3.78666528));
points.add(Point.fromLngLat(-38.56038094, -3.7337361));
setContentView(R.layout.activity_last);
navigationView = findViewById(R.id.navigationView);
navigationView.onCreate(savedInstanceState);
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();
}
#Override
public void onNavigationReady(boolean isRunning) {
fetchRoute(points.remove(0), points.remove(0));
}
#Override
public void onCancelNavigation() {
// Navigation canceled, finish the activity
finish();
}
#Override
public void onNavigationFinished() {
// Intentionally empty
}
#Override
public void onNavigationRunning() {
// Intentionally empty
}
#Override
public boolean allowRerouteFrom(Point offRoutePoint) {
return true;
}
#Override
public void onOffRoute(Point offRoutePoint) {
Toast.makeText(this, "Off route", Toast.LENGTH_SHORT).show();
}
#Override
public void onRerouteAlong(DirectionsRoute directionsRoute) {
}
#Override
public void onFailedReroute(String errorMessage) {
}
#Override
public void onArrival() {
if (!dropoffDialogShown && !points.isEmpty()) {
showDropoffDialog();
dropoffDialogShown = true; // Accounts for multiple arrival events
Toast.makeText(this, "You have arrived!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onProgressChange(Location location, RouteProgress routeProgress) {
lastKnownLocation = location;
}
private void startNavigation(DirectionsRoute directionsRoute) {
NavigationViewOptions navigationViewOptions = setupOptions(directionsRoute);
navigationView.startNavigation(navigationViewOptions);
}
private void showDropoffDialog() {
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setMessage(getString(R.string.dropoff_dialog_text));
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.dropoff_dialog_positive_text),
(dialogInterface, in) -> fetchRoute(getLastKnownLocation(), points.remove(0)));
alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.dropoff_dialog_negative_text),
(dialogInterface, in) -> {
// Do nothing
});
alertDialog.show();
}
private void fetchRoute(Point origin, Point destination) {
NavigationRoute.builder(this)
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.alternatives(true)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
DirectionsResponse directionsResponse = response.body();
if (directionsResponse != null && !directionsResponse.routes().isEmpty()) {
startNavigation(directionsResponse.routes().get(0));
}
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable t) {
}
});
}
private NavigationViewOptions setupOptions(DirectionsRoute directionsRoute) {
dropoffDialogShown = false;
NavigationViewOptions.Builder options = NavigationViewOptions.builder();
options.directionsRoute(directionsRoute)
.navigationListener(this)
.progressChangeListener(this)
.routeListener(this)
.shouldSimulateRoute(false);
return options.build();
}
private Point getLastKnownLocation() {
return Point.fromLngLat(lastKnownLocation.getLongitude(), lastKnownLocation.getLatitude());
}
}
XML File:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.mapbox.services.android.navigation.ui.v5.NavigationView
android:id="#+id/navigationView"
android:layout_width="0dp"
android:layout_height="0dp"
app:navigationLightTheme="#style/NavigationViewLight"
app:navigationDarkTheme="#style/NavigationViewDark"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
When I start navigation with multiple waypoints, the navigation stops after reaching first waypoint.
Please suggest changes.`
try{
NavigationRoute.Builder builder = NavigationRoute.builder(this)
.accessToken("pk." + getString(R.string.gh_key))
.baseUrl(getString(R.string.base_url))
.user("gh")
.alternatives(true);
Location lastKnownLocation = new Location(LocationManager.GPS_PROVIDER);
lastKnownLocation.setLatitude(Double.parseDouble(SharePref.getInstance(MapBoxNavActivity.this).getJavaRXPref(getString(R.string.latitude))));
lastKnownLocation.setLongitude(Double.parseDouble(SharePref.getInstance(MapBoxNavActivity.this).getJavaRXPref(getString(R.string.longitude))));
Point location = Point.fromLngLat(lastKnownLocation.getLongitude(), lastKnownLocation.getLatitude());
if (lastKnownLocation.hasBearing()){
// 90 seems to be the default tolerance of the SDK
builder.origin(location, (double) lastKnownLocation.getBearing(), 90.0);
}
else{
builder.origin(location);
}
try {
if(waypoints.size()>0){
for (int i = 0; i < waypoints.size(); i++) {
Point p = waypoints.get(i);
if (i < waypoints.size() - 1) {
try {
builder.addWaypoint(p);
}catch (Exception e){
e.printStackTrace();
}
} else {
builder.destination(p);
}
}
}
}catch (Exception se){
se.printStackTrace();
}
builder.build().getRoute(new SimplifiedCallback() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
if (validRouteResponse(response)) {
route = response.body().routes().get(0);
try {
MapboxNavigationOptions.Builder navigationOptions = MapboxNavigationOptions.builder();
NavigationViewOptions.Builder options = NavigationViewOptions.builder();
options.navigationListener(MapBoxNavActivity.this);
options.directionsRoute(route);
options.shouldSimulateRoute(false);
options.directionsProfile(DirectionsCriteria.PROFILE_DRIVING_TRAFFIC);
navigationOptions.enableOffRouteDetection(true);
navigationOptions.snapToRoute(true);
options.navigationOptions(navigationOptions.build());
navigationView.startNavigation(options.build());
}catch (Exception e){
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
super.onFailure(call, throwable);
Log.i("Fetch route error",throwable.getMessage());
}
});
}
}
catch ( Exception se){
se.printStackTrace();
}
}
`
"Using the default milestones requires the directions route to include the route options object"
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, PermissionsListener , MapboxMap.OnMapClickListener , MapboxMap.OnMapLongClickListener{
private PermissionsManager permissionsManager;
private MapboxMap mapboxMap;
private MapView mapView;
LocationComponent locationComponent;
Double lattt, langgg;
FloatingActionButton floatingActionButton , floatingActionButtonnavigate;
AlertDialog alertDialog;
public MapboxOptimization optimizedClient;
public DirectionsRoute optimizedRoute;
private Point origin;
private NavigationMapRoute navigationMapRoute;
private InstructionView instructionView;
private List<Point> stops = new ArrayList<>();
private static final String ICON_GEOJSON_SOURCE_ID = "icon-source-id";
private static final String FIRST = "first";
private static final String ANY = "any";
private static final String TEAL_COLOR = "#23D2BE";
private static final float POLYLINE_WIDTH = 5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.access_token));
token is configured.
setContentView(R.layout.activity_main);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
floatingActionButton = findViewById(R.id.floatingActionButtonforsaveloc);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
opendialoyge();
}
});
}
#Override
public void onMapReady(#NonNull final MapboxMap mapboxMap) {
MainActivity.this.mapboxMap = mapboxMap;
mapboxMap.setStyle(new Style.Builder().fromUri("mapbox://styles/mapbox/satellite-streets-v11"),
new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
enableLocationComponent(style);
addFirstStopToStopsList();
initMarkerIconSymbolLayer(Objects.requireNonNull(style));
initOptimizedRouteLineLayer(style);
Toast.makeText(MainActivity.this, R.string.click_instructions, Toast.LENGTH_SHORT).show();
mapboxMap.addOnMapClickListener(MainActivity.this);
mapboxMap.addOnMapLongClickListener(MainActivity.this);
floatingActionButtonnavigate=findViewById(R.id.floatingActionButtonnavigation);
floatingActionButtonnavigate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean simulateRoute = true;
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.directionsRoute(optimizedRoute)
.shouldSimulateRoute(simulateRoute)
.build();
NavigationLauncher.startNavigation(MainActivity.this, options);
}
});
}
});
}
private void addFirstStopToStopsList() {
origin = Point.fromLngLat(locationComponent.getLastKnownLocation().getLongitude(), locationComponent.getLastKnownLocation().getLatitude());
stops.add(origin);
}
private void initMarkerIconSymbolLayer(#NonNull Style loadedMapStyle) {
loadedMapStyle.addImage("icon-image", BitmapFactory.decodeResource(
this.getResources(), R.drawable.mapbox_marker_icon_default));
loadedMapStyle.addSource(new GeoJsonSource(ICON_GEOJSON_SOURCE_ID,
Feature.fromGeometry(Point.fromLngLat(origin.longitude(), origin.latitude()))));
loadedMapStyle.addLayer(new SymbolLayer("icon-layer-id", ICON_GEOJSON_SOURCE_ID).withProperties(
iconImage("icon-image"),
iconSize(1f),
iconAllowOverlap(true),
iconIgnorePlacement(true),
iconOffset(new Float[] {0f, -4f})
));
}
private void initOptimizedRouteLineLayer(#NonNull Style loadedMapStyle) {
loadedMapStyle.addSource(new GeoJsonSource("optimized-route-source-id"));
loadedMapStyle.addLayerBelow(new LineLayer("optimized-route-layer-id", "optimized-route-source-id")
.withProperties(
lineColor(Color.parseColor(TEAL_COLOR)),
lineWidth(POLYLINE_WIDTH)
), "icon-layer-id");
}
#SuppressWarnings({"MissingPermission"})
private void enableLocationComponent(#NonNull Style loadedMapStyle) {
if (PermissionsManager.areLocationPermissionsGranted(this)) {
locationComponent = mapboxMap.getLocationComponent();
locationComponent.activateLocationComponent(
LocationComponentActivationOptions.builder(this, loadedMapStyle).build());
locationComponent.setLocationComponentEnabled(true);
locationComponent.setCameraMode(CameraMode.TRACKING);
locationComponent.setRenderMode(RenderMode.COMPASS);
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#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) {
mapboxMap.getStyle(new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
enableLocationComponent(style);
}
});
} else {
Toast.makeText(this, R.string.user_location_permission_not_granted, Toast.LENGTH_LONG).show();
finish();
}
}
public void opendialoyge() {
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
final View mView = inflater.inflate(R.layout.custome_dialouge, null);
final EditText txt_input = mView.findViewById(R.id.entertext);
Button btn_cancle = (Button) mView.findViewById(R.id.butcancle);
Button btn_ok = (Button) mView.findViewById(R.id.butok);
alert.setView(mView);
alertDialog = alert.create();
alertDialog.show();
alertDialog.setCanceledOnTouchOutside(false);
btn_cancle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alertDialog.dismiss();
}
});
btn_ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = txt_input.getText().toString();
if (!text.isEmpty()) {
assert locationComponent.getLastKnownLocation() != null;
lattt = locationComponent.getLastKnownLocation().getLatitude();
langgg = locationComponent.getLastKnownLocation().getLongitude();
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Hajj&Umrah_App");
myRef.child(text).child("lattt").setValue(lattt.toString());
myRef.child(text).child("lang").setValue(langgg.toString());
} else {
Toast.makeText(MainActivity.this, "Please Enter group Name", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public boolean onMapClick(#NonNull LatLng point) {
if (alreadyTwelveMarkersOnMap()) {
Toast.makeText(MainActivity.this, R.string.only_twelve_stops_allowed, Toast.LENGTH_LONG).show();
} else {
Style style = mapboxMap.getStyle();
if (style != null) {
addDestinationMarker(style, point);
addPointToStopsList(point);
getOptimizedRoute(style, stops);
}
}
return true;
}
#Override
public boolean onMapLongClick(#NonNull LatLng point) {
stops.clear();
if (mapboxMap != null) {
Style style = mapboxMap.getStyle();
if (style != null) {
resetDestinationMarkers(style);
removeOptimizedRoute(style);
addFirstStopToStopsList();
return true;
}
}
return false;
}
private void resetDestinationMarkers(#NonNull Style style) {
GeoJsonSource optimizedLineSource = style.getSourceAs(ICON_GEOJSON_SOURCE_ID);
if (optimizedLineSource != null) {
optimizedLineSource.setGeoJson(Point.fromLngLat(origin.longitude(), origin.latitude()));
}
}
private void removeOptimizedRoute(#NonNull Style style) {
GeoJsonSource optimizedLineSource = style.getSourceAs("optimized-route-source-id");
if (optimizedLineSource != null) {
optimizedLineSource.setGeoJson(FeatureCollection.fromFeatures(new Feature[] {}));
}
}
private boolean alreadyTwelveMarkersOnMap() {
return stops.size() == 3;
}
private void addDestinationMarker(#NonNull Style style, LatLng point) {
List<Feature> destinationMarkerList = new ArrayList<>();
for (Point singlePoint : stops) {
destinationMarkerList.add(Feature.fromGeometry(
Point.fromLngLat(singlePoint.longitude(), singlePoint.latitude())));
}
destinationMarkerList.add(Feature.fromGeometry(Point.fromLngLat(point.getLongitude(), point.getLatitude())));
GeoJsonSource iconSource = style.getSourceAs(ICON_GEOJSON_SOURCE_ID);
if (iconSource != null) {
iconSource.setGeoJson(FeatureCollection.fromFeatures(destinationMarkerList));
}
}
private void addPointToStopsList(LatLng point) {
stops.add(Point.fromLngLat(point.getLongitude(), point.getLatitude()));
}
private void getOptimizedRoute(#NonNull final Style style, List<Point> coordinates) {
NavigationRoute.builder(this);
optimizedClient = MapboxOptimization.builder()
.source(FIRST)
.destination(ANY)
.coordinates(coordinates)
.overview(DirectionsCriteria.OVERVIEW_FULL)
.profile(DirectionsCriteria.PROFILE_DRIVING)
.accessToken(Mapbox.getAccessToken())
.build();
optimizedClient.enqueueCall(new Callback<OptimizationResponse>() {
#Override
public void onResponse(Call<OptimizationResponse> call, Response<OptimizationResponse> response) {
if (!response.isSuccessful()) {
Timber.d( getString(R.string.no_success));
Toast.makeText(MainActivity.this, R.string.no_success, Toast.LENGTH_SHORT).show();
return;
} else {
if (response.body().trips().isEmpty()) {
Timber.d("%s size = %s", getString(R.string.successful_but_no_routes), response.body().trips().size());
Toast.makeText(MainActivity.this, R.string.successful_but_no_routes,
Toast.LENGTH_SHORT).show();
return;
}
}
optimizedRoute = Objects.requireNonNull(response.body().trips()).get(0);
if (navigationMapRoute!=null){
navigationMapRoute.removeRoute();
}
else {
navigationMapRoute = new NavigationMapRoute(null,mapView,mapboxMap,R.style.NavigationMapRoute);
}
drawOptimizedRoute(style, optimizedRoute);
}
#Override
public void onFailure(Call<OptimizationResponse> call, Throwable throwable) {
Timber.d("Error: %s", throwable.getMessage());
}
});
}
private void drawOptimizedRoute(#NonNull Style style, DirectionsRoute route) {
GeoJsonSource optimizedLineSource = style.getSourceAs("optimized-route-source-id");
if (optimizedLineSource != null) {
optimizedLineSource.setGeoJson(FeatureCollection.fromFeature(Feature.fromGeometry(
LineString.fromPolyline(route.geometry(), PRECISION_6))));
}
}
#Override
#SuppressWarnings({"MissingPermission"})
protected void onStart() {
super.onStart();
mapView.onStart();
}
#Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
#Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (optimizedClient != null) {
optimizedClient.cancelCall();
}
if (mapboxMap != null) {
mapboxMap.removeOnMapClickListener(this);
}
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}
The exception I am getting:
2019-08-15 17:12:35.879 7522-7522/com.example.chekoptimizationnnnn
E/Mbgl-MapChangeReceiver: Exception in onDidFinishLoadingStyle
java.util.MissingFormatArgumentException: Format specifier 'Using the default milestones requires the directions route to include the
route options object.'
at com.mapbox.services.android.navigation.v5.utils.ValidationUtils.checkNullRouteOptions(ValidationUtils.java:26)
at com.mapbox.services.android.navigation.v5.utils.ValidationUtils.validDirectionsRoute(ValidationUtils.java:18)
at com.mapbox.services.android.navigation.v5.navigation.MapboxNavigation.startNavigationWith(MapboxNavigation.java:938)
at com.mapbox.services.android.navigation.v5.navigation.MapboxNavigation.startNavigation(MapboxNavigation.java:346)
at com.mapbox.services.android.navigation.ui.v5.NavigationViewModel.startNavigation(NavigationViewModel.java:434)
at com.mapbox.services.android.navigation.ui.v5.NavigationViewModel.updateRoute(NavigationViewModel.java:251)
at com.mapbox.services.android.navigation.ui.v5.NavigationViewRouteEngineListener.onRouteUpdate(NavigationViewRouteEngineListener.java:17)
at com.mapbox.services.android.navigation.ui.v5.NavigationViewRouter.updateCurrentRoute(NavigationViewRouter.java:96)
at com.mapbox.services.android.navigation.ui.v5.NavigationViewRouter.extractRouteFrom(NavigationViewRouter.java:121)
at com.mapbox.services.android.navigation.ui.v5.NavigationViewRouter.extractRouteOptions(NavigationViewRouter.java:72)
at com.mapbox.services.android.navigation.ui.v5.NavigationViewModel.initialize(NavigationViewModel.java:213)
at com.mapbox.services.android.navigation.ui.v5.NavigationView.initializeNavigation(NavigationView.java:618)
at com.mapbox.services.android.navigation.ui.v5.NavigationView.startNavigation(NavigationView.java:381)
at com.mapbox.services.android.navigation.ui.v5.MapboxNavigationActivity.onNavigationReady(MapboxNavigationActivity.java:99)
at com.mapbox.services.android.navigation.ui.v5.NavigationView$1.onStyleLoaded(NavigationView.java:225)
at com.mapbox.mapboxsdk.maps.MapboxMap.notifyStyleLoaded(MapboxMap.java:855)
at "Using the default milestones requires the directions route to include the route options object"
com.mapbox.mapboxsdk.maps.MapboxMap.onFinishLoadingStyle(MapboxMap.java:212)
at com.mapbox.mapboxsdk.maps.MapView$MapCallback.onDidFinishLoadingStyle(MapView.java:1264)
at com.mapbox.mapboxsdk.maps.MapChangeReceiver.onDidFinishLoadingStyle(MapChangeReceiver.java:198)
at com.mapbox.mapboxsdk.maps.NativeMapView.onDidFinishLoadingStyle(NativeMapView.java:1035)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:323)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
2019-08-15 17:12:35.886 7522-7522/com.example.chekoptimizationnnnn
A/libc:
/usr/local/google/buildbot/src/android/ndk-release-r19/external/libcxx/../../external/libcxxabi/src/abort_message.cpp:73:
abort_message: assertion "terminating with uncaught exception of type
jni::PendingJavaException" failed 2019-08-15 17:12:35.933
7522-7522/com.example.chekoptimizationnnnn A/libc: Fatal signal 6
(SIGABRT), code -6 in tid 7522 (ptimizationnnnn)
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
How to solve "'catch' or 'finally' expected" error in android studio..?
a screenshot of the error
public class FragmentRecent extends Fragment {
View root_view, parent_view;
private RecyclerView recyclerView;
private AdapterChannel adapterChannel;
private SwipeRefreshLayout swipeRefreshLayout;
private Call<CallbackChannel> callbackCall = null;
private int post_total = 0;
private int failed_page = 0;
private InterstitialAd interstitialAd;
private OfflineDatabase databaseHelper;
int counter = 3;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root_view = inflater.inflate(R.layout.fragment_recent, null);
parent_view = getActivity().findViewById(R.id.main_content);
loadInterstitialAd();
swipeRefreshLayout = (SwipeRefreshLayout) root_view.findViewById(R.id.swipe_refresh_layout_home);
swipeRefreshLayout.setColorSchemeResources(R.color.orange, R.color.green, R.color.blue, R.color.red);
recyclerView = (RecyclerView) root_view.findViewById(R.id.recyclerViewHome);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setHasFixedSize(true);
//set data and list adapter
adapterChannel = new AdapterChannel(getActivity(), recyclerView, new ArrayList<Channel>());
recyclerView.setAdapter(adapterChannel);
// on item list clicked
adapterChannel.setOnItemClickListener(new AdapterChannel.OnItemClickListener() {
#Override
public void onItemClick(View v, Channel obj, int position) {
Intent intent = new Intent(getActivity(), ActivityDetailChannel.class);
intent.putExtra(Constant.KEY_CHANNEL_CATEGORY, obj.category_name);
intent.putExtra(Constant.KEY_CHANNEL_ID, obj.channel_id);
intent.putExtra(Constant.KEY_CHANNEL_NAME, obj.channel_name);
intent.putExtra(Constant.KEY_CHANNEL_IMAGE, obj.channel_image);
intent.putExtra(Constant.KEY_CHANNEL_URL, obj.channel_url);
intent.putExtra(Constant.KEY_CHANNEL_DESCRIPTION, obj.channel_description);
startActivity(intent);
showInterstitialAd();
}
});
// detect when scroll reach bottom
adapterChannel.setOnLoadMoreListener(new AdapterChannel.OnLoadMoreListener() {
#Override
public void onLoadMore(int current_page) {
if (post_total > adapterChannel.getItemCount() && current_page != 0) {
int next_page = current_page + 1;
requestAction(next_page);
} else {
adapterChannel.setLoaded();
}
}
});
// on swipe list
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
if (callbackCall != null && callbackCall.isExecuted()) callbackCall.cancel();
adapterChannel.resetListData();
requestAction(1);
}
});
requestAction(1);
return root_view;
}
private void displayApiResult(final List<Channel> channels) {
adapterChannel.insertData(channels);
swipeProgress(false);
if (channels.size() == 0) {
showNoItemView(true);
}
}
private void requestListPostApi(final int page_no) {
ApiInterface apiInterface = RestAdapter.createAPI();
callbackCall = apiInterface.getPostByPage(page_no, Config.LOAD_MORE);
callbackCall.enqueue(new Callback<CallbackChannel>() {
#Override
public void onResponse(Call<CallbackChannel> call, Response<CallbackChannel> response) {
CallbackChannel resp = response.body();
if (resp != null && resp.status.equals("ok")) {
post_total = resp.count_total;
displayApiResult(resp.posts);
} else {
onFailRequest(page_no);
}
}
#Override
public void onFailure(Call<CallbackChannel> call, Throwable t) {
if (!call.isCanceled()) onFailRequest(page_no);
}
});
}
private void onFailRequest(int page_no) {
failed_page = page_no;
adapterChannel.setLoaded();
swipeProgress(false);
if (NetworkCheck.isConnect(getActivity())) {
} else {
//showToast("Internet Not");
if (databaseHelper.getOfflineData("FragmentCategory").length() != 0) {
setJson(databaseHelper.getOfflineData("FragmentCategory"), false);
}
}
}
//databaseHelper.removeAll();
private void requestAction(final int page_no) {
showFailedView(false, "");
showNoItemView(false);
if (page_no == 1) {
swipeProgress(true);
} else {
adapterChannel.setLoading();
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
requestListPostApi(page_no);
}
}, Constant.DELAY_TIME);
}
#Override
public void onDestroy() {
super.onDestroy();
swipeProgress(false);
if (callbackCall != null && callbackCall.isExecuted()) {
callbackCall.cancel();
}
}
private void showFailedView(boolean show, String message) {
View lyt_failed = (View) root_view.findViewById(R.id.lyt_failed_home);
((TextView) root_view.findViewById(R.id.failed_message)).setText(message);
if (show) {
recyclerView.setVisibility(View.GONE);
lyt_failed.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_failed.setVisibility(View.GONE);
}
((Button) root_view.findViewById(R.id.failed_retry)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestAction(failed_page);
}
});
}
private void showNoItemView(boolean show) {
View lyt_no_item = (View) root_view.findViewById(R.id.lyt_no_item_home);
((TextView) root_view.findViewById(R.id.no_item_message)).setText(R.string.no_post_found);
if (show) {
recyclerView.setVisibility(View.GONE);
lyt_no_item.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_no_item.setVisibility(View.GONE);
}
}
private void swipeProgress(final boolean show) {
if (!show) {
swipeRefreshLayout.setRefreshing(show);
return;
}
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(show);
}
});
}
public void setJson(String result, Boolean isOnline) {
try {
//inseting result to database
if(isOnline) {
ContentValues offline_data = new ContentValues();
offline_data.put(OfflineDatabase.KEY_OFFLINE_DATA, result);
if(databaseHelper.getOfflineData("FragmentCategory").length()!=0) {
databaseHelper.update("FragmentCategory",offline_data);
} else {
offline_data.put(OfflineDatabase.KEY_ACTIVITY_NAME, "FragmentCategory");
databaseHelper.addOfflineData(offline_data, null);
//handle both exceptions
}
}}}
private void loadInterstitialAd() {
if (Config.ENABLE_ADMOB_INTERSTITIAL_ADS) {
interstitialAd = new InterstitialAd(getActivity());
interstitialAd.setAdUnitId(getResources().getString(R.string.admob_interstitial_unit_id));
interstitialAd.loadAd(new AdRequest.Builder().build());
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
interstitialAd.loadAd(new AdRequest.Builder().build());
}
});
} else {
Log.d("AdMob", "AdMob Interstitial is Enabled");
}
}
private void showInterstitialAd() {
if (Config.ENABLE_ADMOB_INTERSTITIAL_ADS) {
if (interstitialAd != null && interstitialAd.isLoaded()) {
if (counter == Config.ADMOB_INTERSTITIAL_ADS_INTERVAL) {
interstitialAd.show();
counter = 1;
} else {
counter++;
}
} else {
Log.d("AdMob", "Interstitial Ad is Disabled");
}
} else {
Log.d("AdMob", "AdMob Interstitial is Disabled");
}
}}
there you start with try:
public void setJson(String result, Boolean isOnline) {
try {
...
}
...
}
which has to continue with:
try {
...
} catch(Exception e) {
} finally {
}
where either catch or finally are optional (depending where the Exception shall be handled).
in my app i want to offer the user a option to set an animation as live wallpaper using WallpaeprService, also my app include a Radio player (playing in the backgroud) if app is open so you can navigate in other apps while music is playing.
my problem :
if live wallpaper is working and user try to close the app by (Swipe to exit / Recent Task),the music keeps playing although app is closed.
i tried to stop music like this ,but doesn't work :
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
#SuppressLint({"CommitPrefEdits", "Assert"})
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, KillNotificationService.class));
trackSelector = new DefaultTrackSelector();
loadControl = new DefaultLoadControl();
exoPlayer = ExoPlayerFactory.newSimpleInstance(new DefaultRenderersFactory(getApplicationContext()), trackSelector, loadControl);
MusicButton.setVisibility(View.INVISIBLE);
MusicButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (Build.VERSION.SDK_INT > 15) {
if (started && MusicButton.isChecked()) {
started = false;
exoPlayer.setPlayWhenReady(false);
MusicButton.setChecked(true);
releaseAudioFocusForMyApp(MainActivity.this);
} else {
boolean gotFocus = requestAudioFocusForMyApp(MainActivity.this);
if (gotFocus) {
started = true;
exoPlayer.setPlayWhenReady(true);
MusicButton.setChecked(false);
}
}
} else {
if (started && MusicButton.isChecked()) {
started = false;
mediaPlayer.pause();
MusicButton.setChecked(true);
releaseAudioFocusForMyApp(MainActivity.this);
} else {
boolean gotFocus = requestAudioFocusForMyApp(MainActivity.this);
if (gotFocus) {
started = true;
mediaPlayer.start();
MusicButton.setChecked(false);
}
}
}
}
});
private void playRadio(String url) {
Uri audioUri = Uri.parse(url);
DefaultHttpDataSourceFactory dataSourceFactory = new DefaultHttpDataSourceFactory("ExoPlayerDemo");
ExtractorsFactory extractor = new DefaultExtractorsFactory();
MediaSource audioSource = new ExtractorMediaSource.Factory(dataSourceFactory).setExtractorsFactory(extractor).createMediaSource(audioUri);
exoPlayer.prepare(audioSource);
prepared = true;
exoPlayer.setPlayWhenReady(true);
exoPlayer.addListener(new Player.EventListener() {
#Override
public void onTimelineChanged(Timeline timeline, #Nullable Object manifest, int reason) {
}
#Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
}
#Override
public void onLoadingChanged(boolean isLoading) {
}
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if (isPreparing && playbackState == ExoPlayer.STATE_READY) {
MusicButton.setVisibility(View.VISIBLE);
MusicButton.setChecked(true);
isPreparing = false;
isReady = true;
}
}
#Override
public void onRepeatModeChanged(int repeatMode) {
}
#Override
public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {
}
#Override
public void onPlayerError(ExoPlaybackException error) {
}
#Override
public void onPositionDiscontinuity(int reason) {
}
#Override
public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
}
#Override
public void onSeekProcessed() {
}
});
}
#Override
protected void onResume() {
super.onResume();
try {
MApplication.sBus.register(this);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
MApplication.sBus.unregister(this);
} catch (Exception e) {
e.printStackTrace();
}
MApplication.sBus.post(PlaybackEvent.PAUSE);
}
#Override
protected void onStart() {
super.onStart();
}
#Subscribe
public void handlePlaybackEvent(PlaybackEvent event) {
switch (event) {
case PAUSE:
if (Build.VERSION.SDK_INT > 15) {
if (exoPlayer.getPlayWhenReady()) {
exoPlayer.setPlayWhenReady(false);
MusicButton.setChecked(true);
}
} else {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
MusicButton.setChecked(true);
}
}
break;
case PLAY:
if (Build.VERSION.SDK_INT > 15) {
if (!exoPlayer.getPlayWhenReady()) {
exoPlayer.setPlayWhenReady(true);
MusicButton.setChecked(false);
}
} else {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
MusicButton.setChecked(false);
}
}
break;
}
}
#Override
public void onPause() {
super.onPause();
}
}
}
problem solved by checking if live wallpaper are running in the backgroud or not:
#Override
protected void onDestroy() {
super.onDestroy();
try {
WallpaperManager wpm = WallpaperManager.getInstance(this);
WallpaperInfo info = wpm.getWallpaperInfo();
if (info != null && info.getPackageName().equals(this.getPackageName())) {
/*stop music*/
} else {
Log.d(TAG, "We're not running");
}
} catch (Exception e) {
e.printStackTrace();
}
}
In my application I have a button and when it gets clicked I start a new thread and change the text of button. If I press the button again it will start changing its text faster.
I would like to interrupt the thread when the button is pressed in the second time. What's the correct way to do it?
public class TestActivity extends Activity {
Button btn;
int i = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button)findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
runThread();
}
});
}
private void runThread() {
new Thread() {
public void run() {
while (i++ < 1000) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
btn.setText("#" + i);
}
});
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
In this case, just keep a reference to your thread and use Thread.interrupt():
private Thread runThread() {
return new Thread() {
public void run() {
while (i++ < 1000) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
btn.setText("#" + i);
}
});
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Then:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (myThread != null) myThread.interrupt();
myThread = runThread();
myThread.start();
}
});
Read this post for more info and options:
How to properly stop the Thread in Java?
In my opinion, the best way would be using a variable to control this.
Something like:
while(i++ < 1000 && keepRunning)
I see that as a good solution because it cant cause unexpected behavior, as you are sure the exactly moment your thread would exit.
extra--
As a suggestion, I also would recommend you to set your thread non-Damon (setDaemon(false)) because it makes layout changes
Also it is a good practice to give thread a name (setName()) to make it easy on debugging.
Right now you start a new Thread each time you press the button.
Something like this should work.
public class TestActivity extends Activity {
Button btn;
int i = 0;
Thread countThread = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
countThread = new Thread() {
public void run() {
while (i++ < 1000) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
btn.setText("#" + i);
}
});
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
btn = (Button)findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
runThread();
}
});
}
private void runThread() {
if(countThread != null) {
if(countThread.isAlive()) {
countThread.stop();
} else {
countThread.start();
}
}
}
I only had a text editor so I can't guarantee if this solves your problem.
You can use thread.interrupt() to interrupt the thread.
Try this, Just take another variable j and it will handle your code:-
public class TestActivity extends Activity {
Button btn;
int i = 0,j=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button)findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
j=1;
runThread();
}
});
}
private void runThread() {
new Thread() {
public void run() {
while (i++ < 1000) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(j==1){
btn.setText("#" + i);
j=0;
}
else
Thread.interrupted();
}
});
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
You can use normal Thread in Android (and call interrupt() for your use case) but frameworks provides other better options by providing helper classes around Threads. You can refer to official documentation page for other options.
HandlerThread is preferred option. You can call quitSafely() or quit() for your use case if you go for HandlerThread
Related post:
Why use HandlerThread in Android