I am using the quick start example supplied in the Android developer guide (rfid-sdk-for-android-dg-en.pdf) and although it does work and scans RFID TAGS there seems to be a problem with the reliability of the scanning. I have tracked the problem down to the EventHandler Class, that the reader.Actions.getReadTags method sometimes returns null this is even if the RFID tags are next to the scanner.
Any help would be much appreciated
I have included the code that I am using:
package uk.co.assettrac.rfd2000_tc20_example;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.zebra.rfid.api3.*;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private static Readers readers;
private static ArrayList<ReaderDevice> availableRFIDReaderList;
private static ReaderDevice readerDevice;
private static RFIDReader reader;
private static String TAG = "DEMO";
TextView textView;
private EventHandler eventHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// UI
textView = (TextView) findViewById(R.id.TagText);
// SDK
if (readers == null) {
readers = new Readers(this, ENUM_TRANSPORT.SERVICE_SERIAL);
}
new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... voids) {
try {
if (readers != null) {
if (readers.GetAvailableRFIDReaderList() != null) {
availableRFIDReaderList =
readers.GetAvailableRFIDReaderList();
if (availableRFIDReaderList.size() != 0) {
// get first reader from list
readerDevice = availableRFIDReaderList.get(0);
reader = readerDevice.getRFIDReader();
if (!reader.isConnected()) {
// Establish connection to the RFID Reader
reader.connect();
ConfigureReader();
return true;
}
}
}
}
} catch (InvalidUsageException e) {
e.printStackTrace();
} catch (OperationFailureException e) {
e.printStackTrace();
Log.d(TAG, "OperationFailureException " + e.getVendorMessage());
}
return false;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
if (aBoolean) {
Toast.makeText(getApplicationContext(), "Reader Connected",
Toast.LENGTH_LONG).show();
//textView.setText("Reader connected");
}
}
}.execute();
}
private void ConfigureReader() {
if (reader.isConnected()) {
TriggerInfo triggerInfo = new TriggerInfo();
triggerInfo.StartTrigger.setTriggerType(START_TRIGGER_TYPE.START_TRIGGER_TYPE_IMMEDIATE);
triggerInfo.StopTrigger.setTriggerType(STOP_TRIGGER_TYPE.STOP_TRIGGER_TYPE_IMMEDIATE);
try {
// receive events from reader
if (eventHandler == null)
eventHandler = new EventHandler();
reader.Events.addEventsListener(eventHandler);
// HH event
reader.Events.setHandheldEvent(true);
// tag event with tag data
reader.Events.setTagReadEvent(true);
reader.Events.setAttachTagDataWithReadEvent(true);
// set trigger mode as rfid so scanner beam will not come
reader.Config.setTriggerMode(ENUM_TRIGGER_MODE.RFID_MODE, true);
// set start and stop triggers
reader.Config.setStartTrigger(triggerInfo.StartTrigger);
reader.Config.setStopTrigger(triggerInfo.StopTrigger);
} catch (InvalidUsageException e) {
e.printStackTrace();
} catch (OperationFailureException e) {
e.printStackTrace();
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
if (reader != null) {
reader.Events.removeEventsListener(eventHandler);
reader.disconnect();
Toast.makeText(getApplicationContext(), "Disconnecting reader",
Toast.LENGTH_LONG).show();
reader = null;
readers.Dispose();
readers = null;
}
} catch (InvalidUsageException e) {
e.printStackTrace();
} catch (OperationFailureException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// Read/Status Notify handler
// Implement the RfidEventsLister class to receive event notifications
public class EventHandler implements RfidEventsListener {
// Read Event Notification
public void eventReadNotify(RfidReadEvents e) {
// Recommended to use new method getReadTagsEx for better performance in case of large tag population
TagData[] myTags = reader.Actions.getReadTags(100);
if (myTags != null) {
for (int index = 0; index < myTags.length; index++) {
Log.d(TAG, "Tag ID " + myTags[index].getTagID());
if (myTags[index].getOpCode() ==
ACCESS_OPERATION_CODE.ACCESS_OPERATION_READ &&
myTags[index].getOpStatus() ==
ACCESS_OPERATION_STATUS.ACCESS_SUCCESS) {
if (myTags[index].getMemoryBankData().length() > 0) {
Log.d(TAG, " Mem Bank Data " + myTags[index].getMemoryBankData());
}
}
}
} else {
Log.d(TAG, "TagData Array Null");
}
}
// Status Event Notification
public void eventStatusNotify(RfidStatusEvents rfidStatusEvents) {
Log.d(TAG, "Status Notification: " +
rfidStatusEvents.StatusEventData.getStatusEventType());
if (rfidStatusEvents.StatusEventData.getStatusEventType() ==
STATUS_EVENT_TYPE.HANDHELD_TRIGGER_EVENT) {
if
(rfidStatusEvents.StatusEventData.HandheldTriggerEventData.getHandheldEvent() ==
HANDHELD_TRIGGER_EVENT_TYPE.HANDHELD_TRIGGER_PRESSED) {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... voids) {
try {
reader.Actions.Inventory.perform();
} catch (InvalidUsageException e) {
e.printStackTrace();
} catch (OperationFailureException e) {
e.printStackTrace();
}
return null;
}
}.execute();
}
if (rfidStatusEvents.StatusEventData.HandheldTriggerEventData.getHandheldEvent() ==
HANDHELD_TRIGGER_EVENT_TYPE.HANDHELD_TRIGGER_RELEASED) {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... voids) {
try {
reader.Actions.Inventory.stop();
} catch (InvalidUsageException e) {
e.printStackTrace();
} catch (OperationFailureException e) {
e.printStackTrace();
}
return null;
}
}.execute();
}
}
}
}
}
After reading the docs for a long time I found that the line
reader.Events.setAttachTagDataWithReadEvent(true);
was causing the problem.
Description:
In my app, I need to print data using Bluetooth printer.
The UI thread has to wait until the other thread dealing with printing
completes its task
The printing thread sets a value whether it is able to print or not
problem: The UI thread in the app is not waiting and its immediately getting the default status false
Where I am doing mistake in the following code?
UI thread:
private void printingStatus()
{
if(printData.isPrintFinished())
// do something
else
// do something
}
// PrintData class that executes printing in a different thread
private boolean printFinished = false;
// UI thread asks this method whether printing is success or failure
public boolean isPrintFinished() {
return printed;
}
public void setPrintFinished(boolean printed) {
this.printed = printed;
}
public static interface IPrintFinished {
public void onPrintFinished(boolean success);
}
public void printData() {
sendDataToPrinter(context, contentToPrint, new IPrintFinished() {
#Override
public void setPrintFinished(boolean success) {
if (success) {
setPrintFinished(true);
Logger.e("inside if success - printed"+printed);
}
setPrintFinished(false);
Logger.e("printed outside if" + printed);
}
});
}
public static void sendDataToPrinter(final Context context, final contentDefinition contentToPrint, final IPrintFinished listener) {
new Thread(new Runnable() {
#Override
public void run() {
Looper.prepare();
// starts here the actual printing and gets a result
int tmpResult;
try {
DataPrinter.getInstance().print(contentToPrint);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Logger.e("exceptpion:" + e);
}
tmpResult = STATUS_PRINTED;
} catch (TechnicalException e) {
Logger.e("exceptpion:" + e);
if (e.getMessage() != null && DataPrinter.ERROR_BLUETOOH_IS_DISABLED.equals(e.getMessage()))
tmpResult = STATUS_BLUETOOTH_DISABLED;
else
tmpResult = STATUS_ERROR;
}
final int result = tmpResult;
Logger.e("print result:"+result);
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
if(result == STATUS_PRINTED) {
if (listener != null) {
Logger.e("inside the listener status printed");
listener.onPrintFinished(true);
}
} else if (result == STATUS_BLUETOOTH_DISABLED) {
SimpleToast.showToast("bluetooth disabled");
if (listener != null) {
listener.onPrintFinished(false);
}
} else {
SimpleToast.showToast("cannot connect to printer");
if (listener != null) {
listener.onPrintFinished(false);
}
}
}
});
Looper.loop();
}
}).start();
}
You cannot hold your UI thread for sometime. That will result in ANR state. Its the main thread which handles UI components.
My goal is to create a method that gets the data from broadcast receiver and sends it trough a socket. I know how to send it, but how can i get a data from BroadcastReceiver ? I want to receive data in this class:
public class ClientThread implements Runnable{
Socket socket;
public final String TAG = "CLIENT";
ObjectOutputStream os;
TextView text;
Handler handler;
AppHelper helperClass;
Activity mActivity;
Context mContext;
public ClientThread(Activity mActivity,TextView text,Context context) {
// TODO Auto-generated constructor stub
this.text=text;
this.mContext=context;;
helperClass = new AppHelper(context, mActivity);
handler = new Handler();
}
#Override
public void run() {
// TODO Auto-generated method stub
try {
while (true) {
socket = new Socket("192.168.1.10", 9000);
handler.post(new Runnable() {
#Override
public void run() {
text.setText("Connected.");
try {
os = new ObjectOutputStream(socket
.getOutputStream());
} catch (Exception e) {
text.setText("Output stream. smth wrong");
Log.i(TAG, "Output stream. smth wrong");
}
}
});
try {
ObjectInputStream in = new ObjectInputStream(
socket.getInputStream());
String line = null;
while ((line = in.readUTF().toString()) != null) {
Log.d("ServerActivity", line);
final String mesg = line;
handler.post(new Runnable() {
#Override
public void run() {
if (mesg.contains("getcontacts")) {
try {
sendContacts();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (mesg.contains("getmsg")) {
getMessages();
} else if (mesg.contains("sendmsg")) {
sendMessage(mesg);
} else {
// DO WHATEVER YOU WANT TO THE FRONT END
// THIS IS WHERE YOU CAN BE CREATIVE
text.append(mesg + "\n");
}
}
});
}
break;
} catch (Exception e) {
handler.post(new Runnable() {
#Override
public void run() {
text.setText("Oops. Connection interrupted. Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
} catch (Exception x) {
}
}
public void receivedMessage(String sender, String message) {
}
private void sendMessage(String s) {
String[] x = s.split(" ");
int lenght = x.length;
String message = x[2];
for (int i = 3; i < x.length; i++) {
message = message + " " + x[i];
}
System.out.println(message);
SmsManager smsManager = SmsManager.getDefault();
System.out.println("sending message");
smsManager.sendTextMessage(x[1], null, message, null, null);
System.out.println("message send");
}
private void sendContacts() throws IOException {
final List<Person> list = helperClass.getContacts();
final String json = new Gson().toJson(list);
Log.i(TAG, "lenght " + json.length());
handler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
os.writeObject(json);
os.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "Sending Contact list has failed");
e.printStackTrace();
}
}
});
}
private void getMessages() {
// TODO Auto-generated method stub
ProgressTask task = new ProgressTask();
ProgressTask.execute(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
List<Sms> sms = helperClass.getAllSms();
final String json = new Gson().toJson(sms);
os.writeObject(json);
os.flush();
System.out.println("List of messages send");
} catch (Exception e) {
Log.e(TAG, "Sending Contact list has failed");
}
}
});
}
}
You may use an interface as listener to this runnable.
Create a Listener interface
Declare Interface Variable in Application Context.
Instantiate and implement interface in Runnable class.
In BroadcastReciever, call method of that interface.
Ex:
Class A extends Application{
public Listener listener;
}`
interface Listener{
public void yourmethod();
}
In Your clientthread method instantiate listener as follows:
((A)context.getApplication()).listener = new Listener(){
#override
public void yourmethod(){
// your implementation goes here
}
}
In your broadcast reciever.
((A)context.getApplication()).listener.yourmethod();
Only a small portion of my users are getting this error and I can't for the life of me figure it out. I use GooglePlayServicesUtil.isGooglePlayServicesAvailable(downloadService) to test whether or not Play Services is available, and it always returns SUCCESS. I setup the channel to connect to the Chromecast, and everything works fine up until the point where I try to use RemoteMediaPlayer.load. The result is always SIGN_IN_REQUIRED for some users, with resolution: null. The status.toString() is Failed to load: Status{statusCode=SIGN_IN_REQUIRED, resolution=null}. I'm really not sure what I am supposed to with this or how to get rid of the error for my few users who are getting this.
I don't know what portion is related, so I am just posting my entire controller class:
public class ChromeCastController extends RemoteController {
private static final String TAG = ChromeCastController.class.getSimpleName();
private CastDevice castDevice;
private GoogleApiClient apiClient;
private ConnectionCallbacks connectionCallbacks;
private ConnectionFailedListener connectionFailedListener;
private Cast.Listener castClientListener;
private boolean applicationStarted = false;
private boolean waitingForReconnect = false;
private boolean error = false;
private boolean ignoreNextPaused = false;
private String sessionId;
private FileProxy proxy;
private String rootLocation;
private RemoteMediaPlayer mediaPlayer;
private double gain = 0.5;
public ChromeCastController(DownloadService downloadService, CastDevice castDevice) {
this.downloadService = downloadService;
this.castDevice = castDevice;
SharedPreferences prefs = Util.getPreferences(downloadService);
rootLocation = prefs.getString(Constants.PREFERENCES_KEY_CACHE_LOCATION, null);
}
#Override
public void create(boolean playing, int seconds) {
downloadService.setPlayerState(PlayerState.PREPARING);
connectionCallbacks = new ConnectionCallbacks(playing, seconds);
connectionFailedListener = new ConnectionFailedListener();
castClientListener = new Cast.Listener() {
#Override
public void onApplicationStatusChanged() {
if (apiClient != null && apiClient.isConnected()) {
Log.i(TAG, "onApplicationStatusChanged: " + Cast.CastApi.getApplicationStatus(apiClient));
}
}
#Override
public void onVolumeChanged() {
if (apiClient != null && applicationStarted) {
try {
gain = Cast.CastApi.getVolume(apiClient);
} catch(Exception e) {
Log.w(TAG, "Failed to get volume");
}
}
}
#Override
public void onApplicationDisconnected(int errorCode) {
shutdownInternal();
}
};
Cast.CastOptions.Builder apiOptionsBuilder = Cast.CastOptions.builder(castDevice, castClientListener);
apiClient = new GoogleApiClient.Builder(downloadService)
.addApi(Cast.API, apiOptionsBuilder.build())
.addConnectionCallbacks(connectionCallbacks)
.addOnConnectionFailedListener(connectionFailedListener)
.build();
apiClient.connect();
}
#Override
public void start() {
if(error) {
error = false;
Log.w(TAG, "Attempting to restart song");
startSong(downloadService.getCurrentPlaying(), true, 0);
return;
}
try {
mediaPlayer.play(apiClient);
} catch(Exception e) {
Log.e(TAG, "Failed to start");
}
}
#Override
public void stop() {
try {
mediaPlayer.pause(apiClient);
} catch(Exception e) {
Log.e(TAG, "Failed to pause");
}
}
#Override
public void shutdown() {
try {
if(mediaPlayer != null && !error) {
mediaPlayer.stop(apiClient);
}
} catch(Exception e) {
Log.e(TAG, "Failed to stop mediaPlayer", e);
}
try {
if(apiClient != null) {
Cast.CastApi.stopApplication(apiClient);
Cast.CastApi.removeMessageReceivedCallbacks(apiClient, mediaPlayer.getNamespace());
mediaPlayer = null;
applicationStarted = false;
}
} catch(Exception e) {
Log.e(TAG, "Failed to shutdown application", e);
}
if(apiClient != null && apiClient.isConnected()) {
apiClient.disconnect();
}
apiClient = null;
if(proxy != null) {
proxy.stop();
proxy = null;
}
}
private void shutdownInternal() {
// This will call this.shutdown() indirectly
downloadService.setRemoteEnabled(RemoteControlState.LOCAL, null);
}
#Override
public void updatePlaylist() {
if(downloadService.getCurrentPlaying() == null) {
startSong(null, false, 0);
}
}
#Override
public void changePosition(int seconds) {
try {
mediaPlayer.seek(apiClient, seconds * 1000L);
} catch(Exception e) {
Log.e(TAG, "FAiled to seek to " + seconds);
}
}
#Override
public void changeTrack(int index, DownloadFile song) {
startSong(song, true, 0);
}
#Override
public void setVolume(boolean up) {
double delta = up ? 0.1 : -0.1;
gain += delta;
gain = Math.max(gain, 0.0);
gain = Math.min(gain, 1.0);
getVolumeToast().setVolume((float) gain);
try {
Cast.CastApi.setVolume(apiClient, gain);
} catch(Exception e) {
Log.e(TAG, "Failed to the volume");
}
}
#Override
public int getRemotePosition() {
if(mediaPlayer != null) {
return (int) (mediaPlayer.getApproximateStreamPosition() / 1000L);
} else {
return 0;
}
}
#Override
public int getRemoteDuration() {
if(mediaPlayer != null) {
return (int) (mediaPlayer.getStreamDuration() / 1000L);
} else {
return 0;
}
}
void startSong(DownloadFile currentPlaying, boolean autoStart, int position) {
if(currentPlaying == null) {
try {
if (mediaPlayer != null && !error) {
mediaPlayer.stop(apiClient);
}
} catch(Exception e) {
// Just means it didn't need to be stopped
}
downloadService.setPlayerState(PlayerState.IDLE);
return;
}
downloadService.setPlayerState(PlayerState.PREPARING);
MusicDirectory.Entry song = currentPlaying.getSong();
try {
MusicService musicService = MusicServiceFactory.getMusicService(downloadService);
String url;
// Offline, use file proxy
if(Util.isOffline(downloadService) || song.getId().indexOf(rootLocation) != -1) {
if(proxy == null) {
proxy = new FileProxy(downloadService);
proxy.start();
}
url = proxy.getPublicAddress(song.getId());
} else {
if(proxy != null) {
proxy.stop();
proxy = null;
}
if(song.isVideo()) {
url = musicService.getHlsUrl(song.getId(), currentPlaying.getBitRate(), downloadService);
} else {
url = musicService.getMusicUrl(downloadService, song, currentPlaying.getBitRate());
}
url = fixURLs(url);
}
// Setup song/video information
MediaMetadata meta = new MediaMetadata(song.isVideo() ? MediaMetadata.MEDIA_TYPE_MOVIE : MediaMetadata.MEDIA_TYPE_MUSIC_TRACK);
meta.putString(MediaMetadata.KEY_TITLE, song.getTitle());
if(song.getTrack() != null) {
meta.putInt(MediaMetadata.KEY_TRACK_NUMBER, song.getTrack());
}
if(!song.isVideo()) {
meta.putString(MediaMetadata.KEY_ARTIST, song.getArtist());
meta.putString(MediaMetadata.KEY_ALBUM_ARTIST, song.getArtist());
meta.putString(MediaMetadata.KEY_ALBUM_TITLE, song.getAlbum());
String coverArt = "";
if(proxy == null) {
coverArt = musicService.getCoverArtUrl(downloadService, song);
coverArt = fixURLs(coverArt);
meta.addImage(new WebImage(Uri.parse(coverArt)));
} else {
File coverArtFile = FileUtil.getAlbumArtFile(downloadService, song);
if(coverArtFile != null && coverArtFile.exists()) {
coverArt = proxy.getPublicAddress(coverArtFile.getPath());
meta.addImage(new WebImage(Uri.parse(coverArt)));
}
}
}
String contentType;
if(song.isVideo()) {
contentType = "application/x-mpegURL";
}
else if(song.getTranscodedContentType() != null) {
contentType = song.getTranscodedContentType();
} else if(song.getContentType() != null) {
contentType = song.getContentType();
} else {
contentType = "audio/mpeg";
}
// Load it into a MediaInfo wrapper
MediaInfo mediaInfo = new MediaInfo.Builder(url)
.setContentType(contentType)
.setStreamType(MediaInfo.STREAM_TYPE_BUFFERED)
.setMetadata(meta)
.build();
if(autoStart) {
ignoreNextPaused = true;
}
mediaPlayer.load(apiClient, mediaInfo, autoStart, position * 1000L).setResultCallback(new ResultCallback<RemoteMediaPlayer.MediaChannelResult>() {
#Override
public void onResult(RemoteMediaPlayer.MediaChannelResult result) {
if (result.getStatus().isSuccess()) {
// Handled in other handler
} else if(result.getStatus().getStatusCode() != ConnectionResult.SIGN_IN_REQUIRED) {
Log.e(TAG, "Failed to load: " + result.getStatus().toString());
failedLoad();
}
}
});
} catch (IllegalStateException e) {
Log.e(TAG, "Problem occurred with media during loading", e);
failedLoad();
} catch (Exception e) {
Log.e(TAG, "Problem opening media during loading", e);
failedLoad();
}
}
private String fixURLs(String url) {
// Only change to internal when using https
if(url.indexOf("https") != -1) {
SharedPreferences prefs = Util.getPreferences(downloadService);
int instance = prefs.getInt(Constants.PREFERENCES_KEY_SERVER_INSTANCE, 1);
String externalUrl = prefs.getString(Constants.PREFERENCES_KEY_SERVER_URL + instance, null);
String internalUrl = prefs.getString(Constants.PREFERENCES_KEY_SERVER_INTERNAL_URL + instance, null);
url = url.replace(internalUrl, externalUrl);
}
// Use separate profile for Chromecast so users can do ogg on phone, mp3 for CC
return url.replace(Constants.REST_CLIENT_ID, Constants.CHROMECAST_CLIENT_ID);
}
private void failedLoad() {
Util.toast(downloadService, downloadService.getResources().getString(R.string.download_failed_to_load));
downloadService.setPlayerState(PlayerState.STOPPED);
error = true;
}
private class ConnectionCallbacks implements GoogleApiClient.ConnectionCallbacks {
private boolean isPlaying;
private int position;
private ResultCallback<Cast.ApplicationConnectionResult> resultCallback;
ConnectionCallbacks(boolean isPlaying, int position) {
this.isPlaying = isPlaying;
this.position = position;
resultCallback = new ResultCallback<Cast.ApplicationConnectionResult>() {
#Override
public void onResult(Cast.ApplicationConnectionResult result) {
Status status = result.getStatus();
if (status.isSuccess()) {
ApplicationMetadata applicationMetadata = result.getApplicationMetadata();
sessionId = result.getSessionId();
String applicationStatus = result.getApplicationStatus();
boolean wasLaunched = result.getWasLaunched();
applicationStarted = true;
setupChannel();
} else {
shutdownInternal();
}
}
};
}
#Override
public void onConnected(Bundle connectionHint) {
if (waitingForReconnect) {
Log.i(TAG, "Reconnecting");
reconnectApplication();
} else {
launchApplication();
}
}
#Override
public void onConnectionSuspended(int cause) {
Log.w(TAG, "Connection suspended");
isPlaying = downloadService.getPlayerState() == PlayerState.STARTED;
position = getRemotePosition();
waitingForReconnect = true;
}
void launchApplication() {
try {
Cast.CastApi.launchApplication(apiClient, CastCompat.APPLICATION_ID, false).setResultCallback(resultCallback);
} catch (Exception e) {
Log.e(TAG, "Failed to launch application", e);
}
}
void reconnectApplication() {
try {
Cast.CastApi.joinApplication(apiClient, CastCompat.APPLICATION_ID, sessionId).setResultCallback(resultCallback);
} catch (Exception e) {
Log.e(TAG, "Failed to reconnect application", e);
}
}
void setupChannel() {
if(!waitingForReconnect) {
mediaPlayer = new RemoteMediaPlayer();
mediaPlayer.setOnStatusUpdatedListener(new RemoteMediaPlayer.OnStatusUpdatedListener() {
#Override
public void onStatusUpdated() {
MediaStatus mediaStatus = mediaPlayer.getMediaStatus();
if (mediaStatus == null) {
return;
}
switch (mediaStatus.getPlayerState()) {
case MediaStatus.PLAYER_STATE_PLAYING:
if (ignoreNextPaused) {
ignoreNextPaused = false;
}
downloadService.setPlayerState(PlayerState.STARTED);
break;
case MediaStatus.PLAYER_STATE_PAUSED:
if (!ignoreNextPaused) {
downloadService.setPlayerState(PlayerState.PAUSED);
}
break;
case MediaStatus.PLAYER_STATE_BUFFERING:
downloadService.setPlayerState(PlayerState.PREPARING);
break;
case MediaStatus.PLAYER_STATE_IDLE:
if (mediaStatus.getIdleReason() == MediaStatus.IDLE_REASON_FINISHED) {
downloadService.setPlayerState(PlayerState.COMPLETED);
downloadService.onSongCompleted();
} else if (mediaStatus.getIdleReason() == MediaStatus.IDLE_REASON_INTERRUPTED) {
if (downloadService.getPlayerState() != PlayerState.PREPARING) {
downloadService.setPlayerState(PlayerState.PREPARING);
}
} else if (mediaStatus.getIdleReason() == MediaStatus.IDLE_REASON_ERROR) {
Log.e(TAG, "Idle due to unknown error");
downloadService.setPlayerState(PlayerState.COMPLETED);
downloadService.next();
} else {
Log.w(TAG, "Idle reason: " + mediaStatus.getIdleReason());
downloadService.setPlayerState(PlayerState.IDLE);
}
break;
}
}
});
}
try {
Cast.CastApi.setMessageReceivedCallbacks(apiClient, mediaPlayer.getNamespace(), mediaPlayer);
} catch (IOException e) {
Log.e(TAG, "Exception while creating channel", e);
}
if(!waitingForReconnect) {
DownloadFile currentPlaying = downloadService.getCurrentPlaying();
startSong(currentPlaying, isPlaying, position);
}
if(waitingForReconnect) {
waitingForReconnect = false;
}
}
}
private class ConnectionFailedListener implements GoogleApiClient.OnConnectionFailedListener {
#Override
public void onConnectionFailed(ConnectionResult result) {
shutdownInternal();
}
}
}
Edit for logs:
03-28 19:04:49.757 6305-6305/github.daneren2005.dsub I/ChromeCastController﹕ onApplicationStatusChanged: Chromecast Home Screen
03-28 19:04:52.280 6305-6305/github.daneren2005.dsub I/ChromeCastController﹕ onApplicationStatusChanged: null
03-28 19:04:54.162 6305-6305/github.daneren2005.dsub I/ChromeCastController﹕ onApplicationStatusChanged: Ready To Cast
03-28 19:05:05.194 6305-6305/github.daneren2005.dsub E/ChromeCastController﹕ Failed to load: Status{statusCode=SIGN_IN_REQUIRED, resolution=null}
It is strange that you are getting such status code at that time. What comes to mind is that the user may have not logged into his/her gmail account or something along those lines. Do you have the log file for us to take a look at to see if we can get more from the context? Also, to be sure, such user sees the application launched on the TV and only when it comes to loading a media that error is thrown?
The issue is due to using a Self Signed Certificate. I didn't realize the issue on my old phone because I had changed hosts and bought a normal certificate after switching phones. It would be nice if the SDK would through a useful error though. The one thrown makes you think that it is a problem with connecting to the Play Services SDK, and not a problem with the actual URL being used.
My code have more than one thread and Runnable. My problem is i change the value of a certain variable in the thread that the Runnable calling .
After the calling i make a check on that variable value but the value was not retrieved yet.
How can i retrieve the value after the processing? Here is the Runnable and the Thread code:
final Runnable r = new Runnable()
{
public void run()
{
if(flag==true)
onSwipe();
if(SwipeAgain==true)
handler.postDelayed(this, 1000);
}
};
private void onSwipe() {
new Thread() {
public void run() {
String data = null;
decryption_data = null;
encryption_data = null;
SwipeAgain=false;
handler.post(clear_encryption);
try {
data = sreader.ReadCard(15000);
} catch (Exception ex) {
if (ex instanceof TimeoutException) {
return;
} else
CloseSinWave();
}
if (data == null) {
SwipeAgain=true;
encryption_data = sreader.GetErrorString();
if (encryption_data.equalsIgnoreCase("cancel all"))
return;
handler.post(display_encryptiondata);
} else {
encryption_data = "\n" + data;
handler.post(display_encryptiondata);
}.start();
}
SwipeAgain is the value i want after processing
You have to use Callable, Runnable interface do not pass values to the parent method.
See this example.
You may require to use Generic Objects
Use a MONITOR final Object to wait and notify it when processing is done.
private final MONITOR Object[] = new Object[0];
private AtomicBoolean ready = new AtomicBoolean(false);
final Runnable r = new Runnable() {
public void run()
{
if(flag==true){
ready.set(false);
onSwipe();
synchronized(MONITOR){
if(!ready.get()){
try{
MONITOR.wait(); //will block until it get notified
}catch(InteruptedException e){}
}
}
}
if(SwipeAgain==true)
handler.postDelayed(this, 1000);
}
};
private void onSwipe() {
new Thread() {
public void run() {
try{
String data = null;
decryption_data = null;
encryption_data = null;
SwipeAgain=false;
handler.post(clear_encryption);
try {
data = sreader.ReadCard(15000);
} catch (Exception ex) {
if (ex instanceof TimeoutException) {
return;
} else
CloseSinWave();
}
if (data == null) {
SwipeAgain=true;
encryption_data = sreader.GetErrorString();
if (encryption_data.equalsIgnoreCase("cancel all"))
return;
handler.post(display_encryptiondata);
} else {
encryption_data = "\n" + data;
handler.post(display_encryptiondata);
}finally{
synchronized(MONITOR){
ready.set(true);
MONITOR.notifyAll(); //notify (and so unblock r.run())
}
}
}.start();
}