RecogniseListener stops at onReadyForSpeech - java

RecogniseListener works fine when there's continuous talk, but whenever there are 5-10seconds of silence, the listener's onReadyForSpeech() method is called, but onBegginingOfSpeech() is never called.
Here's my listener:
sr = SpeechRecognizer.createSpeechRecognizer(this);
sr.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle params) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float rmsdB) {
}
#Override
public void onBufferReceived(byte[] buffer) {
}
#Override
public void onEndOfSpeech() {
startRecognising();
}
#Override
public void onError(int error) {
}
#Override
public void onResults(Bundle results) {
adapter.add(new MessageData(MessageData.TYPE_VOICE, recognisedText.getText().toString()), 0);
recyclerView.scrollToPosition(0);
recognisedText.setText("");
}
#Override
public void onPartialResults(Bundle partialResults) {
ArrayList data = partialResults.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
String word = (String) data.get(data.size() - 1);
recognisedText.setText(word);
}
#Override
public void onEvent(int eventType, Bundle params) {
}
});
The startRecognising() method:
private void startRecognising(){
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS, 20000000);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"voice.recognition.test");
intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,1);
sr.startListening(intent);
}
By the way, are there any free alternatives that can recognise speech in real-time continuously?

Related

Android Nearby Connections cannot connect to device. Always returns 8011

I am trying to use Google Nearby Connections API to connect two Android devices to exchange data but no success.
The devices can found eachother none of them can connect to the other. It always fails at onConnectionInitiated() with
STATUS_ENDPOINT_UNKNOWN when I try to accept the connection.
I tried it with Strategy.P2P_POINT_TO_POINT Strategy.CLUSTER and Strategy.STAR but I get the same result.
Anyone can help me what do I miss?
Both devices are physical and running on Android 9.0
This is the code:
public static ConnectionLifecycleCallback connectionLifecycleCallback;
public static EndpointDiscoveryCallback endpointDiscoveryCallback;
public static PayloadCallback payloadCallback;
public static String SERVICE_ID;
public Context ctx;
public static Strategy STRATEGY;
public NearbyHandler(Context ctx,Strategy STRATEGY){
this.ctx = ctx;
this.STRATEGY = STRATEGY;
SERVICE_ID = ctx.getPackageName();
payloadCallback = new PayloadCallback() {
#Override
public void onPayloadReceived(#NonNull String s, #NonNull Payload payload) {
Log.d("NEARBY_", "PAYLOAD RECEIVED " + s);
}
#Override
public void onPayloadTransferUpdate(#NonNull String s, #NonNull PayloadTransferUpdate payloadTransferUpdate) {
Log.d("NEARBY_", "PAYLOAD TRANSFER UPDATE " + s);
}
};
connectionLifecycleCallback = new ConnectionLifecycleCallback() {
#Override
public void onConnectionInitiated(#NonNull String s, #NonNull ConnectionInfo connectionInfo) {
Nearby.getConnectionsClient(ctx)
.acceptConnection(s, payloadCallback)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("NEARBY_", "SUCCESSFULLY CONNECTED");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
e.printStackTrace();
}
});
}
#Override
public void onConnectionResult(#NonNull String s, #NonNull ConnectionResolution connectionResolution) {
switch (connectionResolution.getStatus().getStatusCode()) {
case ConnectionsStatusCodes.STATUS_OK:
Nearby.getConnectionsClient(ctx).stopAdvertising();
Nearby.getConnectionsClient(ctx).stopDiscovery();
break;
case ConnectionsStatusCodes.STATUS_CONNECTION_REJECTED:
break;
case ConnectionsStatusCodes.STATUS_ERROR:
break;
}
}
#Override
public void onDisconnected(#NonNull String s) {
Log.d("NEARBY_", "DISCONNECTED " + s);
}
};
endpointDiscoveryCallback = new EndpointDiscoveryCallback() {
#Override
public void onEndpointFound(#NonNull String s, #NonNull DiscoveredEndpointInfo discoveredEndpointInfo) {
Nearby.getConnectionsClient(ctx)
.requestConnection(
s,
ctx.getPackageName(),
connectionLifecycleCallback)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("NEARBY_", "ENDPOINT CONNECTED");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("NEARBY_", "FAILED TO CONNECT ENDPOINT " + e.getMessage());
e.printStackTrace();
}
});
}
#Override
public void onEndpointLost(#NonNull String s) {
Log.d("NEARBY_", "ENDPOINT LOST: " + s);
}
};
}
public void startDiscovering() {
Nearby.getConnectionsClient(ctx)
.startDiscovery(
SERVICE_ID,
endpointDiscoveryCallback,
new DiscoveryOptions.Builder()
.setStrategy(CONSTANTS.PEERTOPEER_STRATEGY).build())
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("NEARBY_DISCOVERER_", "onSuccess");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
e.printStackTrace();
}
});
}
public void startAdvertising() {
Nearby.getConnectionsClient(ctx)
.startAdvertising(
Build.MODEL,
SERVICE_ID,
connectionLifecycleCallback,
new AdvertisingOptions.Builder()
.setStrategy(CONSTANTS.PEERTOPEER_STRATEGY).build())
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
e.printStackTrace();
}
});
}
}
NearbyHandler nearby = new NearbyHandler(getApplicationContext(), Strategy.P2P_POINT_TO_POINT);
if (IS_DEVICE_A) {
nearby.startAdvertising();
} else {
nearby.startDiscovering();
}
Update: Google's walkietalkie demo app works fine on both phones.
Finally I've managed to get it working but not sure about the problem.
I managed the connection lifecycle a bit different way than in the API Docs.
So I created a private helper class
class Endpoint {
#NonNull
private final String id;
#NonNull
private final String name;
public Endpoint(#NonNull String id, #NonNull String name) {
this.id = id;
this.name = name;
}
#NonNull
public String getId() {
return id;
}
#NonNull
public String getName() {
return name;
}
#Override
public boolean equals(Object obj) {
if (obj instanceof Endpoint) {
Endpoint other = (Endpoint) obj;
return id.equals(other.id);
}
return false;
}
#Override
public int hashCode() {
return id.hashCode();
}
#Override
public String toString() {
return String.format("Endpoint{id=%s, name=%s}", id, name);
}
}
The ConnectionLifecycleCallback() and EndpointDiscoveryCallback() should look like this:
endpointDiscoveryCallback = new EndpointDiscoveryCallback() {
#Override
public void onEndpointFound(#NonNull String s, #NonNull DiscoveredEndpointInfo discoveredEndpointInfo) {
Endpoint endpoint = new Endpoint(s, discoveredEndpointInfo.getEndpointName());
ConnectionsClient c = Nearby.getConnectionsClient(ctx);
c.requestConnection(endpoint.getName(), endpoint.getId(), connectionLifecycleCallback).addOnSuccessListener(new OnSuccessListener < Void > () {
#Override
public void onSuccess(Void aVoid) {}
});
}
#Override
public void onEndpointLost(#NonNull String s) {}
};
connectionLifecycleCallback = new ConnectionLifecycleCallback() {
#Override
public void onConnectionInitiated(#NonNull String s, #NonNull ConnectionInfo connectionInfo) {
Nearby.getConnectionsClient(ctx).stopAdvertising();
Nearby.getConnectionsClient(ctx).stopDiscovery();
Endpoint endpoint = new Endpoint(s, connectionInfo.getEndpointName());
ConnectionsClient c = Nearby.getConnectionsClient(ctx);
c.acceptConnection(endpoint.getId(), payloadCallback).addOnSuccessListener(new OnSuccessListener < Void > () {
#Override
public void onSuccess(Void aVoid) {}
});
}
#Override
public void onConnectionResult(#NonNull String s, #NonNull ConnectionResolution connectionResolution) {
switch (connectionResolution.getStatus().getStatusCode()) {
case ConnectionsStatusCodes.STATUS_OK:
Nearby.getConnectionsClient(ctx).stopAdvertising();
Nearby.getConnectionsClient(ctx).stopDiscovery();
break;
case ConnectionsStatusCodes.STATUS_CONNECTION_REJECTED:
// The connection was rejected by one or both sides.
break;
case ConnectionsStatusCodes.STATUS_ERROR:
// The connection broke before it was able to be accepted.
break;
}
}
#Override
public void onDisconnected(#NonNull String s) {}
};

NavigationView with useroffroute MapBox Android

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();
}
}
`

ExoPlayer - playing multiple videos

I'm tying to play videos from a Firebase Listadapter. When the user clicks on the list they a video plays, and upon finishing the activity finishes, and they return to the original list.
When the click on the second video it starts the ExoPlayer activity, but won't play the video. If they press back and select the original video it will play fine.
public String mTastingWineID;
public String tastingWineId;
public String mWineVideoID;
public String tastingWineVideoId;
private DataSource.Factory mediaDataSourceFactory;
private boolean isPlaying = false;
public int mVideoResource;
public Uri videoUri;
private static final String TAG = "WineMediaActivity";
private static final DefaultBandwidthMeter BANDWIDTH_METER = new DefaultBandwidthMeter();
private SimpleExoPlayer player;
private SimpleExoPlayerView mVideoView;
private ComponentListener componentListener;
private long playbackPostiion;
private int currentWindow;
private boolean playWhenReady = true;
private BandwidthMeter bandwidthMeter;
public Firebase wineMediaUrl;
public ValueEventListener wineMediaUrlListener;
private MediaControllerCompat mediaControllerCompat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.analytics_media_wine_information);
Bundle bundle = getIntent().getExtras();
mTastingWineID = bundle.getString(Constants.WINE_ID);
tastingWineId = mTastingWineID.toString();
mWineVideoID = bundle.getString(Constants.WINE_VIDEO_ID);
tastingWineVideoId = mWineVideoID.toString();
if (player != null){
player.release();
}
getCurrentVideo();
}
public void getCurrentVideo(){
wineMediaUrl = new Firebase(Constants.FIREBASE_URL).child(FIREBASE_LOCATION_WINE_DETAILS).child(tastingWineId).child(WINE_MEDIA).child(tastingWineVideoId).child("wineVideoUrl");
wineMediaUrlListener = wineMediaUrl.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
componentListener = new ComponentListener();
mVideoView = findViewById(R.id.videoView1);
mVideoView.requestFocus();
Object tempVideoFiles = dataSnapshot.getValue();
String str = tempVideoFiles.toString();
videoUri = Uri.parse(str);
if (videoUri != null) {
initializePlayer();
} else {
Toast.makeText(WineMediaActivity.this, "No Video Found", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
mediaDataSourceFactory = new DefaultDataSourceFactory(this, Util.getUserAgent(this, "mediaPlayerSample"), (TransferListener<? super DataSource>) bandwidthMeter);
}
private class ComponentListener implements ExoPlayer.EventListener, VideoRendererEventListener, AudioRendererEventListener {
#Override
public void onTimelineChanged(Timeline timeline, Object manifest) {
}
#Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
}
#Override
public void onLoadingChanged(boolean isLoading) {
}
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
String stateString;
switch (playbackState) {
case ExoPlayer.STATE_IDLE:
stateString = "ExoPlayer.STATE_IDLE";
break;
case ExoPlayer.STATE_BUFFERING:
stateString = "ExoPlayer.STATE_IDLE";
break;
case ExoPlayer.STATE_READY:
stateString = "ExoPlayer.STATE_IDLE";
break;
case ExoPlayer.STATE_ENDED:
stateString = "ExoPlayer.STATE_IDLE";
releasePlayer();
finish();
break;
default:
stateString = "UNKNOWN_STATE";
break;
}
Log.d(TAG, "changed state to: " + stateString + " play when ready: " + playWhenReady);
}
#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
public void onAudioEnabled(DecoderCounters counters) {
}
#Override
public void onAudioSessionId(int audioSessionId) {
}
#Override
public void onAudioDecoderInitialized(String decoderName, long initializedTimestampMs, long initializationDurationMs) {
}
#Override
public void onAudioInputFormatChanged(Format format) {
}
#Override
public void onAudioSinkUnderrun(int bufferSize, long bufferSizeMs, long elapsedSinceLastFeedMs) {
}
#Override
public void onAudioDisabled(DecoderCounters counters) {
}
#Override
public void onVideoEnabled(DecoderCounters counters) {
}
#Override
public void onVideoDecoderInitialized(String decoderName, long initializedTimestampMs, long initializationDurationMs) {
}
#Override
public void onVideoInputFormatChanged(Format format) {
}
#Override
public void onDroppedFrames(int count, long elapsedMs) {
}
#Override
public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees, float pixelWidthHeightRatio) {
}
#Override
public void onRenderedFirstFrame(Surface surface) {
}
#Override
public void onVideoDisabled(DecoderCounters counters) {
}
}
private void initializePlayer() {
if (player == null) {
TrackSelection.Factory adaptiveTrackSelectionFactory = new AdaptiveTrackSelection.Factory(bandwidthMeter);
player = ExoPlayerFactory.newSimpleInstance(new DefaultRenderersFactory(this), new DefaultTrackSelector(adaptiveTrackSelectionFactory), new DefaultLoadControl());
player.addListener(componentListener);
player.setVideoDebugListener(componentListener);
player.setAudioDebugListener(componentListener);
mVideoView.setPlayer(player);
player.setPlayWhenReady(playWhenReady);
player.seekTo(currentWindow, playbackPostiion);
}
MediaSource mediaSource = new ExtractorMediaSource(videoUri, mediaDataSourceFactory, extractorsFactory, null, null);
player.prepare(mediaSource, true, false);
}
#SuppressLint("InlinedApi")
private void hideSystemUi() {
mVideoView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
}
private void releasePlayer() {
if (player != null) {
playbackPostiion = player.getCurrentPosition();
currentWindow = player.getCurrentWindowIndex();
playWhenReady = player.getPlayWhenReady();
player.removeListener(componentListener);
mVideoView.setPlayer(null);
player.setVideoListener(null);
player.setVideoDebugListener(null);
player.setAudioDebugListener(null);
player.release();
player = null;
if (wineMediaUrlListener != null) {
wineMediaUrl.removeEventListener(wineMediaUrlListener);
wineMediaUrlListener = null;
}
}
}
#Override
protected void onPause() {
super.onPause();
releasePlayer();
}
#Override
public void onStop() {
super.onStop();
releasePlayer();
}
#Override
public void onDestroy() {
super.onDestroy();
releasePlayer();
}
Apologies for the code, I'm newish to coding and hoping someone can help me.
Turns out the code is fine - the error was in the upload of videos, they were overwriting the previous video meaning the previous one wouldn't play.

Override Cordova Log

I need to override the Log in Cordova Plugin because the code I'm using has some other functions i.e. Log.info which are causing a load of errors
In the code I'm using they override as such
public class GridActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize YiCameraPlatform
try {
Platform.initialize(new Logger() {
#Override
public void verbose(String message) {
Log.v("YiCameraPlatform", message);
}
#Override
public void info(String message) {
Log.i("YiCameraPlatform", message);
}
#Override
public void warning(String message) {
Log.w("YiCameraPlatform", message);
}
#Override
public void error(String message) {
Log.e("YiCameraPlatform", message);
}
});
} catch (Exception ex) {
}
I need to do something similar in the plugin initialiser
public class XiaomiYiCordovaPlugin extends CordovaPlugin {
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
Can anyone let me know how to do this?
I'm trying things such as
Log = new Logger() {
#Override
public void verbose(String message) {
Log.v("YiCameraPlatform", message);
}
#Override
public void info(String message) {
Log.i("YiCameraPlatform", message);
}
#Override
public void warning(String message) {
Log.w("YiCameraPlatform", message);
}
#Override
public void error(String message) {
Log.e("YiCameraPlatform", message);
}
};
To no avail..

Android AIDL StartProcess not working

I have an activity in which I call Service on background, I am quite new to AIDL
my codes are as follows:
on Activity
//declaration
private Intent mIntentInvenueService;
private IInvenueService mIInvenueService;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mIntentInvenueService = new Intent(this, InvenueService.class);
startService(mIntentInvenueService);
}
private final ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
mIInvenueService = IInvenueService.Stub.asInterface(service);
try {
mIInvenueService.registerCallback(mCallback);
} catch (RemoteException e) {
e.printStackTrace();
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
mIInvenueService = null;
try {
mIInvenueService.unregisterCallback(mCallback);
} catch (RemoteException e) {
e.printStackTrace();
}
}
};
private final IInvenueServiceCallback.Stub mCallback = new IInvenueServiceCallback.Stub() {
#Override
public void onReceiveResponse() throws RemoteException {
runOnUiThread(new Runnable() {
public void run() {
if (flagChanged){
}
else
{
cAdapter.notifyDataSetChanged();
}
}
});
}
};
public void onResume() {
super.onResume();
bindService(mIntentInvenueService, mServiceConnection, BIND_AUTO_CREATE);
}
#Override
public void onDestroy() {
super.onDestroy();
unbindService(mServiceConnection);
unregisterReceiver(mBroadcastReceiver);
}
ON MY SERVICE:
private final RemoteCallbackList<IInvenueServiceCallback> mCallbacks = new RemoteCallbackList<IInvenueServiceCallback>();
private boolean isUpdated = false;
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private final IInvenueService.Stub mBinder = new IInvenueService.Stub() {
#Override
public void startProcess() throws RemoteException {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
Toast.makeText(......).show()// Toast Here
}
}, 60000, 60000);
}
#Override
public void unregisterCallback(IInvenueServiceCallback callback)
throws RemoteException {
mCallbacks.unregister(callback);
}
#Override
public void registerCallback(IInvenueServiceCallback callback)
throws RemoteException {
mCallbacks.register(callback);
}
};
My AIDL:
interface IInvenueService {
void startProcess();
void registerCallback(IInvenueServiceCallback callback);
void unregisterCallback(IInvenueServiceCallback callback);
}
My Question is why is that the Toast not showing? Am I missing something that start process isnt working?
Any Help?
You should show Toasts from the UIThread, using a TimerTask will cause it to run on a seperate thread.
Try posting a runnable with the Toast to a Handler.

Categories