How to get play and stop event callback from chromecast android - java

I want to get callback event and perform some function when chromecast audio change there playback mode(play/stop)
How can I get the play/stop event to the application so I will do my work on that event.
Please check below logic I have implemented.
private void setupCastListener() {
mSessionManagerListener = new SessionManagerListener<CastSession>() {
#Override
public void onSessionEnded(CastSession session, int error) {
onApplicationDisconnected();
}
#Override
public void onSessionResumed(CastSession session, boolean wasSuspended) {
onApplicationConnected(session);
}
#Override
public void onSessionResumeFailed(CastSession session, int error) {
onApplicationDisconnected();
}
#Override
public void onSessionStarted(CastSession session, String sessionId) {
onApplicationConnected(session);
}
#Override
public void onSessionStartFailed(CastSession session, int error) {
onApplicationDisconnected();
}
#Override
public void onSessionStarting(CastSession session) {
}
#Override
public void onSessionEnding(CastSession session) {
}
#Override
public void onSessionResuming(CastSession session, String sessionId) {
if(mCastSession!=null && isChromeCastConnected){
try {
if (session.isMute()) {
mStopPlayButton.setImageResource(R.drawable.ic_play);
isChromeCastPlay = false;
//mCastSession.setMute(!mCastSession.isMute());
} else {
mStopPlayButton.setImageResource(R.drawable.ic_stop);
isChromeCastPlay = true;
//mCastSession.setMute(!mCastSession.isMute());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void onSessionSuspended(CastSession session, int reason) {
}
};
}
Please let me know. thanks

You need to read this documentation, and focus on RemoteMediaClient and the Listener interface there. The callback onStatusUpdated() will be called when there is a change in the playback status. Tutorials available on the first link above is very informative, so make sure you read about things there.

Finally I found the remote media play and pause mode call back by below MediaControlIntent.
Remote Playback Routes
mMediaRouter = MediaRouter.getInstance(this);
mSelector = new MediaRouteSelector.Builder()
.addControlCategory(MediaControlIntent.CATEGORY_REMOTE_PLAYBACK)
.build();

Related

How can I refresh the listview after I delete my draft when it automatically re-presses?

How can i refresh listview after I delete my draft when it automatically back pressed?
public void deleteDraft() {
((LoaderActivity) getActivity()).getLoader().show();
ApiHelper.get().itrDeleteDraft(new ItrDeleteDraftApi.Request(userID, projectID, itrRaisedID)).enqueue(new ApiRequest.Callback<ItrDeleteDraftApi.Response>() {
#Override
public void onSuccess(ItrDeleteDraftApi.Response response) {
((LoaderActivity) requireActivity()).getLoader().hide();
requireActivity().onBackPressed();
}
#Override
public void onFailure(String e) {
((LoaderActivity) getActivity()).getLoader().hide();
ErrorManager.promptError(getActivity(), e);
}
});
}
#OnClick(R.id.buttons_itr_delete) public void onDeleteButtonClick(){
new AlertDialog.Builder(getContext()).setCancelable(false).setTitle("").setMessage(R.string.confirm_delete_itr).setNegativeButton(R.string.cancel, (d,e)->d.dismiss()).setPositiveButton(R.string.ok, (d,e)-> {
itrDetailFragment.deleteDraft();
}).create().show();
}
It will refresh or else it will disappear in the list

How to get current duration of video in exo player?

I'm using the ExoPlayer library for playing some videos from the online data sources. Everything is working fine.
Now I want to get current video duration/position on every second. I can't get any option in the default event listener. Anyone have any reference, I've searched about it but can't get anything. Please help me to get this.
Here's the event listener functions I'm getting,
#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 onPlaybackSuppressionReasonChanged(int playbackSuppressionReason) {
}
#Override
public void onIsPlayingChanged(boolean isPlaying) {
}
If you want to get current video position at every second , then run handler for every second and get the current position in seconds as shown below.
long videoWatchedTime =0;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//Do your work
videoWatchedTime= player.getCurrentPosition()/1000;
}
},1000);

Firebase ML kit's QR Code Scanner Scans each QR Code Multiple Times

My scanner scans single QR Code multiple times thats why my createDialog method runs multiple time where i get the info regarding QR code and the user who is using it and the agent who posted it and store data into users node in Db and because it run multiple time my Db cant keep track of the no. of times the qr code scanned for each user..
private void setupCamera() {
startAgain.setEnabled(isDetected);
startAgain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isDetected = !isDetected;
}
});
cameraView.setLifecycleOwner(this);
cameraView.addFrameProcessor(new FrameProcessor() {
#Override
public void process(#NonNull Frame frame) {
processorImage((FirebaseVisionImage) getVisionImageFromFrame(frame));
}
});
options = new FirebaseVisionBarcodeDetectorOptions.Builder()
.setBarcodeFormats(FirebaseVisionBarcode.FORMAT_QR_CODE)
.build();
detector = FirebaseVision.getInstance().getVisionBarcodeDetector(options);
}
private Object getVisionImageFromFrame(Frame frame) {
byte[] data = frame.getData();
FirebaseVisionImageMetadata metadata = new FirebaseVisionImageMetadata.Builder()
.setFormat(FirebaseVisionImageMetadata.IMAGE_FORMAT_NV21)
.setHeight(frame.getSize().getHeight())
.setWidth(frame.getSize().getWidth())
.build();
return FirebaseVisionImage.fromByteArray(data, metadata);
}
private void processorImage(FirebaseVisionImage image) {
if (!isDetected) {
detector.detectInImage(image)
.addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionBarcode>>() {
#Override
public void onSuccess(List<FirebaseVisionBarcode> firebaseVisionBarcodes) {
processResult(firebaseVisionBarcodes);
}
}).addOnCompleteListener(new OnCompleteListener<List<FirebaseVisionBarcode>>() {
#Override
public void onComplete(#NonNull Task<List<FirebaseVisionBarcode>> task) {
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(StoreScanQR.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
private void processResult(List<FirebaseVisionBarcode> firebaseVisionBarcodes) {
if (firebaseVisionBarcodes.size() > 0) {
isDetected = true;
startAgain.setEnabled(isDetected);
for (FirebaseVisionBarcode item : firebaseVisionBarcodes) {
try {
createDialog(item.getRawValue());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Detection is an asynchronous call, so it may be triggered multiple times with different inputs before you can get the first result. If you only care about the first detected result, you can check your isDetected flag at the result processing side (i.e. in #onSuccess callback) rather than detection triggering side.
#Override
public void onSuccess(List<FirebaseVisionBarcode> firebaseVisionBarcodes) {
if (!isDetected) {
processResult(firebaseVisionBarcodes);
}
}

Android Volley RxJava - Multiple Requests

I have something like that:
public void function sendPhotosAndSave (ArrayList<Photo> photos) {
// Iterate through all photos
// Send a POST request using volley for each photo
// Alert when all photos sended
// ????
.subscribe(new Subscriber<Boolean>() {
#Override
public void onCompleted() {
// Save
}
#Override
public void onError(Throwable e) {
}
#Override
public void onNext(Boolean aBoolean) {
}
});
}
I need to send all photos (Multipart/POST) and then send a save request.
How do i iterate the photos requests using RxJava and known when it's done?
You can do something like this:
public void sendPhotosAndSave(List<Photo> photos) {
Observable.from(photos)
.flatMap(photo -> sendRequest(photo).subscribeOn(Schedulers.io()))
.subscribe(new Subscriber<Boolean>() {
#Override
public void onCompleted() {
// Save
}
#Override
public void onError(Throwable e) {
}
#Override
public void onNext(Boolean aBoolean) {
}
});
}
private Observable<Boolean> sendRequest(Photo photo) {
return Observable.just(/*your request logic*/);
}

QuickBlox chat messages listener

I use 2.1.1 Android SDK and want to notify user about new incoming messages received by application.
Here is the issue. I would like to notify user as he launches application, thus i would like to add listener at the stage of "user login" as it's shown in the snippet:
QBAuth.createSession(user, new QBEntityCallbackImpl<QBSession>() {
#Override
public void onSuccess(QBSession session, Bundle args) {
// login to Chat
chatService.login(user, new QBEntityCallbackImpl() {
#Override
public void onSuccess() {
HERE I WOULD LIKE A CODE TO START LISTEN FOR ALL INCOMING MESSAGES
As per http://sdk.quickblox.com/android/com/quickblox/chat/listeners/QBMessageListenerImpl.html
listener needs chat QBChat to initiate. But I would like to listen for all of the messages, not only within particular chat.
Long story short, how to implement a message listener to catch all messages addressed to logged in user?
#Naveen Kumar
In my start activity i launch listener to catch XMPP connection.
private void XMPPConnectionListener() {
XMPPConnection.addConnectionCreationListener(new ConnectionCreationListener() {
#Override
public void connectionCreated(XMPPConnection connection) {
GlobalVar.XMPPConn = connection;
ChatHelper.idleMessageListener(StartActivity.this);
}
});
}
Then I use GlobalVar.XMPPConn to catch packets and parse them:
public static void idleMessageListener(final Activity activity) {
PacketListener myListener = new PacketListener() {
public void processPacket(final Packet packet) {
final Integer userID = Integer.parseInt(returnIDFromPacket(packet.getFrom()));
final String body = returnBodyFromPacket(packet.toString());
if (!GlobalVar.currentOpponent.equals(userID) && !body.isEmpty()) {
activity.runOnUiThread(new Runnable() {
public void run() {
QBUsers.getUser(userID, new QBEntityCallbackImpl<QBUser>() {
#Override
public void onSuccess(final QBUser user, Bundle args) {
sendNotification(activity, user, body);
}
#Override
public void onError(List<String> errors) {
Log.d(TAG, errors.toString());
}
});
}
});
}
}
};
PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
if (GlobalVar.XMPPConn != null) {
GlobalVar.XMPPConn.addPacketListener(myListener, filter);
}
}
So logic is to catch the connection fired by QuickBlox and then attach a packet listener to it.

Categories