Chromecast - SIGN_IN_REQUIRED - android

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.

Related

android app permissions is not asking properly

public class EEmployeeApplication extends Application {
public void onCreate() {
super.onCreate();
try {
mContext = getApplicationContext();
dbHandler = new DataBaseModule(this);
dbHandler.getReadableDatabase();
dbHandler.close();
dbHandler = getDbHandler();
curUser = dbHandler.getActiveUserInfo();
eEMPSharedPreference = new eEmployeeSharedPreference();
DataSyncStartAlarm newAlarm = new DataSyncStartAlarm();
newAlarm.startDataSyncAlarm(mContext, null);
} catch (Exception e) {
Log.d("eEmp/Application ", e.toString());
}
}
#Override
public void onTerminate() {
try {
} catch (Exception e) {
Log.d("eEmp/Application ", e.toString());
}
super.onTerminate();
}
public static boolean isNetAvailable() {
try {
ConnectivityManager connectivity = (ConnectivityManager)
mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
{
NetworkInfo netInfo = connectivity.getActiveNetworkInfo();
if (netInfo != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if ((info == null) || (!netInfo.isConnectedOrConnecting())) {
return false;
} else {
return true;
}
}
}
return false;
} catch (Exception e) {
Log.d("eEmp/Application", e.toString());
return false;
}
}
public DataBaseModule getDbHandler() {
return dbHandler;
}
public void checkUserAvailability(Activity activity) {
try {
if (curUser == null) // No Employee registered in local DB
{
activity.finish();
Intent loginScreen = new Intent(mContext, Login_Activity.class);
loginScreen.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
loginScreen.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(loginScreen);
} else {
activity.finish();
List<EmpZonesResponseDTO> empZonesResponseDTOS ;
empZonesResponseDTOS = eEMPSharedPreference.getZones(mContext);
if (empZonesResponseDTOS == null){
Intent dashboardAct = new Intent(mContext, Login_Activity.class);
dashboardAct.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
dashboardAct.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(dashboardAct);
}else {
Intent dashboardAct = new Intent(mContext, NavigationActivity.class);
dashboardAct.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
dashboardAct.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(dashboardAct);
}
}
} catch (Exception except) {
Log.d("eEmp/LoginActivity", except.toString());
}
}
public static Context getContext() {
return mContext;
}
public void SyncMasterData(NavigationActivity NavActivity) {
try{
if (isNetAvailable()) {
Log.d("eEmp/LoginCheck", "Internet is available");
SyncMasterDataDownloadTask SyncTask = new SyncMasterDataDownloadTask();
SyncTask.setContextandActivity(this,NavActivity);
SyncTask.execute();
} else
{
Log.d("eEmp/SyncMasterData", "Internet is not available");
NavActivity.DismissMasterDataDownload();
Snackbar
.make(NavActivity.navigationView,
"No Internet connection, Unable to Sync Account", Snackbar.LENGTH_LONG)
.show();
}
}catch (Exception e){
e.printStackTrace();
}
}
public String getActivityFragmentTag(EmpConstants.WorkType aSelectedWorkType) {
String selectedTag;
switch (aSelectedWorkType) {
case Dashboard:
selectedTag = EmpConstants.DashBoard_Info_Tag;
break;
case Profile:
selectedTag = EmpConstants.Personal_Info_Tag;
break;
case Entry:
selectedTag = EmpConstants.Entry_Info_Tag;
break;
case Plan:
selectedTag = EmpConstants.Plan_Info_Tag;
break;
case Report:
selectedTag = EmpConstants.Report_Info_Tag;
break;
case QR:
selectedTag = EmpConstants.QR_Info_Tag;
break;
case Miscellaneous:
selectedTag = EmpConstants.Miscellaneous_Info_Tag;
break;
case Nothing:
selectedTag = "";
break;
default:
selectedTag = "";
break;
}
return selectedTag;
}
// Location Method
public GpsLocationListener getGpsLocationListener() {
try {
if (gpsLocationListener == null) {
gpsLocationListener = new GpsLocationListener();
gpsLocationListener.getGPSCordinates();
//Log.d("eEmp/getGPSLocationList","Location Listener Created");
}
} catch (Exception gpsLocationExp) {
Log.d("eEmp/getGPSLocationList", "Error raised due to " + gpsLocationExp.toString());
}
return gpsLocationListener;
}
public String getEmpImageDirPath() {
try {
return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString()
+ EmpConstants.appDir;
} catch (Exception e) {
Log.d("eEmp/ImgDir", e.toString());
return "";
}
}
public String getEmpThumbImageDirPath() {
try {
return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString()
+ EmpConstants.thumbnailDir;
} catch (Exception e) {
Log.d("eEmp/ThumbImgDir", e.toString());
return "";
}
}
public Bitmap loadFromFile(String filename) {
try {
File f = new File(filename);
if (!f.exists()) {
return null;
}
final int width = EmpConstants.DisplayWidth;//mDisplay.widthPixels;
final int height = EmpConstants.DisplayHeight;//mDisplay.heightPixels;
Bitmap tmp = decodeSampledBitmapFromResource(filename, width, height);
return tmp;
} catch (Exception e) {
return null;
}
}
public static Bitmap decodeSampledBitmapFromResource(String imgFile,
int reqWidth, int reqHeight) {
try {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imgFile, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(imgFile, options);
} catch (Exception sampleBitmapConvExp) {
Log.d("eEmp/sampleBMPConv", "Error raised due to " + sampleBitmapConvExp.toString());
return null;
}
}
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public void checkImageDirectories() {
try {
File eEmpPhotosDir = new File(getEmpImageDirPath());
if (!eEmpPhotosDir.exists()) {
eEmpPhotosDir.mkdir();
}
File eEmpThumbPhotosDir = new File(getEmpThumbImageDirPath());
if (!eEmpThumbPhotosDir.exists())
eEmpThumbPhotosDir.mkdir();
} catch (Exception e) {
Log.d("eEmp/CheckDir", e.toString());
}
}
public void showFullImage(Context context, String curImgFile) {
try {
if (curImgFile.length() != 0) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
final Dialog nagDialog = new Dialog(context, android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
nagDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
nagDialog.setCancelable(false);
nagDialog.setContentView(R.layout.preview_image);
Button btnClose = (Button) nagDialog.findViewById(R.id.btnIvClose);
ImageView ivPreview = (ImageView) nagDialog.findViewById(R.id.iv_preview_image);
TextView tvLoading = (TextView) nagDialog.findViewById(R.id.tvImgLoading);
ivPreview.setTag(tvLoading);
ImageRequest imgOrgReq = new ImageRequest();
imgOrgReq.imgView = ivPreview;
imgOrgReq.ImgType = EmpConstants.ImageLoadingType.OriginalImage;
imgOrgReq.context = (EEmployeeApplication) mContext;
BitmapWorkerTask statusImg = new BitmapWorkerTask(imgOrgReq);
statusImg.execute(curImgFile);
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
nagDialog.dismiss();
}
});
nagDialog.show();
}
} catch (Exception e) {
Log.d("eEmp/ShowFullImg", e.getLocalizedMessage());
}
}
// delete selected image from external storage
public void deleteSelImgFromStorage(String imgPath, Context context) {
try {
File imgFile = new File(imgPath);
if (imgPath.contains(EmpConstants.appName)) {
if (imgFile.exists()) {
imgFile.delete();
}
MediaScannerConnection.scanFile(context, new String[]{imgPath}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
}
} catch (Exception e) {
Log.i("Delete image", e.toString());
}
}
// For Marshmallow
// To Check permissions for Marshmallow
public List<String> askPermissions(ArrayList<EmpConstants.PermissionsList> ReqPermnsList) {
List<String> permissionsNeeded = new ArrayList<String>();
for (EmpConstants.PermissionsList perm : ReqPermnsList) {
switch (perm) {
case PhonePerm:
if (addPermission(Manifest.permission.READ_PHONE_STATE))
permissionsNeeded.add(Manifest.permission.READ_PHONE_STATE);
break;
case External_StoragePerm:
if (addPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE))
permissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (addPermission(Manifest.permission.READ_EXTERNAL_STORAGE))
permissionsNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE);
break;
case LocationPerm:
if (addPermission(Manifest.permission.ACCESS_COARSE_LOCATION))
permissionsNeeded.add(Manifest.permission.ACCESS_COARSE_LOCATION);
if (addPermission(Manifest.permission.ACCESS_FINE_LOCATION))
permissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
break;
case CameraPerm:
if (addPermission(Manifest.permission.CAMERA))
permissionsNeeded.add(Manifest.permission.CAMERA);
break;
}
}
return permissionsNeeded;
}
public boolean addPermission(String permission) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
return true;
}
}
return false;
}
public boolean isAnyPermissionRequired(ArrayList<EmpConstants.PermissionsList> ReqPermnsList) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
if (ReqPermnsList.size() == 0) {
return false;
} else {
for (EmpConstants.PermissionsList perm : ReqPermnsList) {
switch (perm) {
case PhonePerm:
if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_DENIED) {
return true;
}
break;
case External_StoragePerm:
if ((checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED)
|| (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED)) {
return true;
}
break;
case LocationPerm:
if ((checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_DENIED)
|| (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_DENIED)) {
return true;
}
break;
case CameraPerm:
if ((checkSelfPermission(Manifest.permission.CAMERA)== PackageManager.PERMISSION_DENIED)){
return true;
}
break;
default:
return false;
}
}
return false;
}
} catch (Exception checkPermExpt) {
Log.d("eEmp/CheckPerms", "Exception due to " + checkPermExpt.toString());
}
}
return false;
}
public void getNetworkProvideLocation() {
try {
if (longitude_Value == 0 || latitude_Value == 0) {
LocationManager locationManager = (LocationManager) EEmployeeApplication.getContext().getSystemService(Context.LOCATION_SERVICE);
boolean isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isNetworkEnable) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location lastLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (lastLocation != null) {
longitude_Value = lastLocation.getLongitude();
latitude_Value = lastLocation.getLatitude();
Log.d("eEmp/getNwValues", "Network Coordinates Updated" );
}
} else {
return;
}
}
} catch (Exception networkLocExp) {
Log.d("eEmp/getNwValues", "Exception due to " + networkLocExp.toString());
}
public int isValidUser() {
try {
if (isNetAvailable()) {
HTTPCommunication loginHTTPRequest;
EEmployeeHTTPResponse result;
if (curUser != null) {
Log.d("eEmp/ValLogin", "Validating User in Background");
loginHTTPRequest = new HTTPCommunication();
EmployeeInfoDTO loginInfo = new EmployeeInfoDTO();
loginHTTPRequest.setRequestType(EmpConstants.HTTPRequestType.NewUser);
loginInfo.EMPID = curUser.getEMPID();
loginInfo.Password = curUser.getPassword();
result = loginHTTPRequest.SendHTTPRequest(loginInfo);
if (result != null) {
if (result.HTTPStatusCode == 200) {
if (result.Data != null) {
return result.Data.ResponseCode;
}
}
}
}
}
return 0; // Invalid User
} catch (Exception e) {
Log.d("eEmp/ValLoginError", e.toString());
return 0;
}
}
#Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
}
LaunchingActivity.java
public class LaunchingActivity extends Activity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, OnTaskStateChange {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.activity_launching);
context = (EEmployeeApplication) EEmployeeApplication.getContext();
if (EEmployeeApplication.isNetAvailable()){
// Read IMEI Number
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ArrayList<EmpConstants.PermissionsList> reqPermissionsList = new ArrayList<>();
if ((context.eEMPSharedPreference != null) && (context.eEMPSharedPreference.getIMEI().isEmpty())) {
reqPermissionsList.add(EmpConstants.PermissionsList.PhonePerm);
}
reqPermissionsList.add(EmpConstants.PermissionsList.External_StoragePerm);
reqPermissionsList.add(EmpConstants.PermissionsList.LocationPerm);
reqPermissionsList.add(EmpConstants.PermissionsList.CameraPerm);
// Check All Permissions
if (context.isAnyPermissionRequired(reqPermissionsList)) {
requestPermission(context.askPermissions(reqPermissionsList));
} else {
readIMEINumber();
}
} else {
readIMEINumber();
}
int x = BuildConfig.VERSION_CODE;
AppVersionTask mTask = new AppVersionTask();
mTask.setListener(this);
APPVERREQ aRequest = new APPVERREQ();
aRequest.requestType = EmpConstants.HTTPRequestType.App_Ver;
APP_VERSION loginInfo = new APP_VERSION();
loginInfo.APP_VER = BuildConfig.VERSION_NAME;
aRequest.RequestObj = loginInfo;
mTask.execute(aRequest);
}
try {
Log.d("eEmp/Test", "MasterdataTaskStarted");
MasterDataLoadTask masterDataLoadTask = new MasterDataLoadTask();
masterDataLoadTask.setContextandActivity(context, this);
masterDataLoadTask.execute();
} catch (Exception MasterDataExcept) {
Log.d("eEmp/MstrDataTask", "Exception Occurred due to " + MasterDataExcept.toString());
context.checkUserAvailability(this);
}
Log.d("eEmp/LaunchCreate", "Launching Created");
} catch (Exception e) {
Log.d("eEmp/LaunchActvty", e.toString());
}
}
#Override
protected void onStart() {
super.onStart();
if ((mGoogleApiClient != null) && (!mGoogleApiClient.isConnected())) {
mGoogleApiClient.connect();
}
Log.d("eEMP/LaunchOnStart", "Launch OnStart");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
// For Marshmallow
// To Check permissions for Marshmallow
public void requestPermission(List<String> permissionsNeeded) {
if (permissionsNeeded.size() > 0) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(permissionsNeeded.toArray(new String[permissionsNeeded.size()]),
EmpConstants.REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
readIMEINumber();
}
// The callback for the management of the user settings regarding location
private ResultCallback<LocationSettingsResult> mResultCallbackFromSettings = new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// GPS is already in On State
initiateLocationRequest();
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult(
LaunchingActivity.this,
REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
default:
context.checkUserAvailability(LaunchingActivity.this);
Log.e("eEmp/Location", "Settings change unavailable. We have no way to fix the settings so we won't show the dialog.");
break;
}
}
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
try {
switch (requestCode) {
case REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK:
if (mGoogleApiClient.isConnected()) {
initiateLocationRequest();
}
break;
case Activity.RESULT_CANCELED:
context.checkUserAvailability(this);
break;
default:
break;
}
break;
}
} catch (Exception expt) {
Log.d("eEmp/AcvtResult", "Exception occurred due to " + expt.toString());
}
}
public void readIMEINumber() {
try {
if ((context.eEMPSharedPreference != null) && (context.eEMPSharedPreference.getIMEI().isEmpty())) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
context.eEMPSharedPreference.setIMEI(telephonyManager.getDeviceId());
}
} else {
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
context.eEMPSharedPreference.setIMEI(telephonyManager.getDeviceId());
}
}
if (!checkGPSStatus()) {
LocationRequest mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (checkPlayServices()) {
LocationSettingsRequest.Builder locationSettingsRequestBuilder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
locationSettingsRequestBuilder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, locationSettingsRequestBuilder.build());
result.setResultCallback(mResultCallbackFromSettings);
} else {
context.checkUserAvailability(this);
}
} else {
initiateLocationRequest();
}
} catch (Exception IMEIExp) {
Log.d("eEmp/IMEIGet", "Unable to get IMEI number due to " + IMEIExp.toString());
}
}
private boolean checkGPSStatus() {
try {
locationManager = (LocationManager) EEmployeeApplication.getContext().getSystemService(Context.LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
return true;
} else {
return false;
}
} catch (Exception chkGPSExpt) {
Log.d("eEmp/chkGPS", " Exception Raised due to " + chkGPSExpt.toString());
return false;
}
}
#Override
protected void onDestroy() {
Log.d("eEmp/Launching", "onDestroy Called");
super.onDestroy();
}
#Override
public void onTaskStateChange(EmpConstants.TaskState State, String Msg, EEmployeeHTTPResponse result) {
switch (State){
case RequestStarted:
break;
case ResponseRecvd:
break;
case ResponseProcessing:
break;
case ResponseProcessed:
if (result != null) {
if (result.HTTPStatusCode == 200) {
if (result.Data != null) {
APP_VERSION_RESPONSE aResponse = (APP_VERSION_RESPONSE) result.Data.ActionResult;
if (aResponse!= null){
if (aResponse.APP_VER.equals(BuildConfig.VERSION_NAME)){
try{
System.out.print("Yes");
}catch (Exception e){
Log.d("/eEmp","/Excp due to"+e.toString());
}
}
}
}
}
}
}
}
}
In my android app, I am asking for permissions at launching of application.
Actually What I want is after launching application, it should ask for permissions and take user input whether accepted or denied then only should move to login page.
But after launching, it is asked for permissions and it is not waiting for user input means permissions dialog is opening and after 5 to 10 seconds login page is opening even though user not responding to permissions dialog.
Why it is happening like this?
Any help would be appreciated.
Your assumption that the android framework should take care of the permission handling process and should hold on to loading the UI components until the user has interacted with the permission is wrong. You need to handle to permission interaction with the user yourself.
Here's how your flow should be :
Ask the user for permission.
Wait for the user to interact with the dialog box.
Read the interaction response and evaluate if the permission was granted.
If the permission was granted, load the UI components.
In other words, you need to make sure that you hold on to doing anything that requires the permissions until the permissions are actually there.

NullPointerException in `BluetoothAdapter` when startService() is invoked [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Error I'm getting null point exception in Bluetooth when I'm starting a service.
LiveFragment.class
public class LiveFragment extends Fragment {
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
private static final int REQUEST_ENABLE_BT = 3;
private BluetoothAdapter mBluetoothAdapter =null;
public BluetoothChatService mChatService = null;
private PowerManager.WakeLock wakeLock = null;
private PowerManager powerManager = null;
private String mConnectedDeviceName = null;
private boolean isServiceBound;
private boolean preRequisites = true;
private SharedPreferences prefs;
private BroadcastReceiver broadcastReceiver;
private Context c;
private AbstractGatewayService ab;
protected ImageView blue_onoffBut, gps_Button, obd_inidca, ss_button, bluetooth_indicator, gps_indicator,obd_connectButt;
protected TextView ss_Status,btStatusTextView,obdStatusTextView,gpsStatusTextView;
private LinearLayout vv;
protected BluetoothSocket sock = null;
public LiveFragment() {
// Required empty public constructor
}
private final Runnable mQueueCommands = new Runnable() {
public void run() {
Log.d(TAG, "Runnable mQueueCommands ()");
if (ab != null && ab.isRunning() && ab.queueEmpty()) {
queueCommands();
}
// run again in period defined in preferences
new Handler().postDelayed(mQueueCommands, 4000);
}
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view = inflater.inflate(R.layout.fragment_live, container, false);
blue_onoffBut = (ImageView) view.findViewById(R.id.blutooth_butoon);
gps_Button = (ImageView) view.findViewById(R.id.gps_button);
obd_inidca = (ImageView) view.findViewById(R.id.obd_Indicator);
ss_button = (ImageView) view.findViewById(ssButton);
gps_indicator = (ImageView) view.findViewById(R.id.gps_indicator);
bluetooth_indicator = (ImageView) view.findViewById(R.id.bluetooth_indicator);
obd_connectButt = (ImageView) view.findViewById(R.id.Obd_Connect_Button);
ss_Status = (TextView) view.findViewById(R.id.statusTx);
btStatusTextView = (TextView) view.findViewById(R.id.blue);
obdStatusTextView = (TextView) view.findViewById(R.id.obd);
gpsStatusTextView = (TextView) view.findViewById(R.id.gps);
vv = (LinearLayout) view.findViewById(R.id.fragment_live_layout);
ss_Status.setTextColor(getResources().getColor(R.color.colorGreen));
if (mBluetoothAdapter.isEnabled()) {
bluetooth_indicator.setImageResource(R.drawable.green_circle);
} else {
bluetooth_indicator.setImageResource(R.drawable.red_circle);
}
gps_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final LocationManager manager = (LocationManager) getActivity().getSystemService( Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
buildAlertMessageNoGps();
}
else {
showToast("Already GPS is ON");
}
}
});
blue_onoffBut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.enable();
showToast("Bluetooth Turned ON"+"\n"+"Connect Your OBD now");
bluetooth_indicator.setImageResource(R.drawable.green_circle);
mChatService = new BluetoothChatService(getActivity(), mHandler);
if (mChatService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
// Start the Bluetooth chat services
mChatService.start();
}
}
} else if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
mBluetoothAdapter.cancelDiscovery();
obd_inidca.setImageResource(R.drawable.red_circle);
showToast("Bluetooth Turned OFF");
bluetooth_indicator.setImageResource(R.drawable.red_circle);
}
}
});
ss_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mBluetoothAdapter.isEnabled() && mChatService.getState() == BluetoothChatService.STATE_CONNECTED) {
startLiveData();
} else if (!mBluetoothAdapter.isEnabled()) {
showToast("Turn ON Bluetooth to Continue");
}
else if (!(mChatService.getState() == BluetoothChatService.STATE_CONNECTED)){
showToast("Select your OBD to Start ");
}
}
});
obd_connectButt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mBluetoothAdapter.isEnabled()) {
Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
}
else if (!mBluetoothAdapter.isEnabled()){
showToast("Turn ON Bluetooth to Connect OBD");
}
}
});
return view;
}
private ServiceConnection serviceConn = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder binder) {
Log.d(TAG, className.toString() + " service is bound");
isServiceBound = true;
ab = ((AbstractGatewayService.AbstractGatewayServiceBinder) binder).getService();
ab.setContext(getActivity());
Log.d(TAG, "Starting live data");
try {
ab.startService();
if (preRequisites)
btStatusTextView.setText("Connected");
} catch (IOException ioe) {
Log.e(TAG, "Failure Starting live data");
btStatusTextView.setText("Connection failed");
doUnbindService();
}
}
#Override
protected Object clone() throws CloneNotSupportedException {
Log.d(TAG, "CloneNotSupportedException ");
return super.clone();
}
#Override
public void onServiceDisconnected(ComponentName className) {
Log.d(TAG, className.toString() + " service is unbound");
isServiceBound = false;
}
};
public static String LookUpCommand(String txt) {
Log.d(TAG, "LookUpCommand() ");
for (AvailableCommandNames item : AvailableCommandNames.values()) {
if (item.getValue().equals(txt)) return item.name();
}
return txt;
}
public void updateTextView(final TextView view, final String txt) {
Log.d(TAG, "updateTextView() ");
new Handler().post(new Runnable() {
public void run() {
view.setText(txt);
}
});
}
#Subscribe(threadMode = ThreadMode.MAIN)
public void stateUpdate(ObdCommandJob job) {
final String cmdName = job.getCommand().getName();
String cmdResult = "";
final String cmdID = LookUpCommand(cmdName);
Log.d(TAG, "stateUpdate() ");
if (job.getState().equals(ObdCommandJob.ObdCommandJobState.EXECUTION_ERROR)) {
cmdResult = job.getCommand().getResult();
if (cmdResult != null && isServiceBound) {
obdStatusTextView.setText(cmdResult.toLowerCase());
}
} else if (job.getState().equals(ObdCommandJob.ObdCommandJobState.BROKEN_PIPE)) {
if (isServiceBound)
stopLiveData();
} else if (job.getState().equals(ObdCommandJob.ObdCommandJobState.NOT_SUPPORTED)) {
cmdResult = "NA";
} else {
cmdResult = job.getCommand().getFormattedResult();
if (isServiceBound)
obdStatusTextView.setText("Receiving data...");
}
cmdResult.replace("NODATA", "0");
if (vv.findViewWithTag(cmdID) != null) {
TextView existingTV = (TextView) vv.findViewWithTag(cmdID);
existingTV.setText(cmdResult);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
FragmentActivity activity = getActivity();
Toast.makeText(activity, "No Bluetooth Feature in Device", Toast.LENGTH_LONG).show();
activity.finish();
}
}
#Override
public void onStart() {
super.onStart();
final LocationManager manager = (LocationManager) getActivity().getSystemService( Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
gps_indicator.setImageResource(R.drawable.red_circle);
}
if(mBluetoothAdapter.isEnabled()){
mBluetoothAdapter.disable();
bluetooth_indicator.setImageResource(R.drawable.red_circle);
}
}
#Override
public void onResume() {
super.onResume();
powerManager = (PowerManager) getActivity().getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "ObdReader");
final LocationManager manager = (LocationManager) getActivity().getSystemService( Context.LOCATION_SERVICE );
if ( manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
gps_indicator.setImageResource(R.drawable.green_circle);
} else {
gps_indicator.setImageResource(R.drawable.red_circle);
}
EventBus.getDefault().register(this);
if(mBluetoothAdapter.isEnabled()) {
if (mChatService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
// Start the Bluetooth chat services
mChatService.start();
}
}
}
}
#Override
public void onPause() {
super.onPause();
Log.d(TAG, "Pausing..");
releaseWakeLockIfHeld();
EventBus.getDefault().unregister(this);
}
private void showToast(String message) {
final Toast toast = Toast.makeText(getContext(), message, Toast.LENGTH_SHORT);
toast.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
toast.cancel();
}
}, 500);
}
#Override
public void onDestroy() {
/* unregisterReceiver(mReceiver);*/
super.onDestroy();
releaseWakeLockIfHeld();
if (mChatService != null) {
mChatService.stop();
}
if (isServiceBound) {
doUnbindService();
}
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
}
showToast("Take Care!");
}
private void startLiveData() {
if (mChatService.getState() == BluetoothChatService.STATE_CONNECTED) {
Log.d(TAG, "Starting live data..");
ss_Status.setText("Stop");
ss_Status.setTextColor(getResources().getColor(R.color.colorRed));
wakeLock.acquire();
ss_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ss_Status.setText("Go Live");
ss_Status.setTextColor(getResources().getColor(R.color.colorGreen));
stopLiveData();
}
});
doBindService();
LocalBroadcastManager.getInstance(getActivity()).registerReceiver((broadcastReceiver), new IntentFilter(OBD_GATEWAY_SERVICE));
new Handler().post(mQueueCommands);
}
}
private void stopLiveData() {
Log.d(TAG, "Stopping live data..");
releaseWakeLockIfHeld();
new Handler().removeCallbacks(mQueueCommands);
ss_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ss_Status.setText("Go Live");
ss_Status.setTextColor(getResources().getColor(R.color.colorGreen));
startLiveData();
}
});
doUnbindService();
LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(broadcastReceiver);
}
private void queueCommands() {
Log.d(TAG, "LiveFragment queueCommands() ");
if (isServiceBound) {
for (ObdCommand Command : ObdConfig.getCommands()) {
if (prefs.getBoolean(Command.getName(), true))
ab.queueJob(new ObdCommandJob(Command));
}
}
}
private void doBindService() {
if (!isServiceBound) {
Log.d(TAG, "Binding OBD service..");
if (preRequisites) {
btStatusTextView.setText("Connecting.....");
Intent serviceIntent = new Intent(getActivity(),ObdGatewayService.class);
getActivity().bindService(serviceIntent, serviceConn, Context.BIND_AUTO_CREATE);
}
}
}
private void doUnbindService() {
if (isServiceBound) {
if (ab.isRunning()) {
ab.stopService();
if (preRequisites)
btStatusTextView.setText("Ready...");
}
Log.d(TAG, "Unbinding OBD service..");
getActivity().unbindService(serviceConn);
isServiceBound = false;
obdStatusTextView.setText("Disconnected");
}
}
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
FragmentActivity activity = getActivity();
switch (msg.what) {
case Constants.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
obd_inidca.setImageResource(R.drawable.green_circle);
break;
case BluetoothChatService.STATE_CONNECTING:
obd_inidca.setImageResource(R.drawable.orange_circle);
break;
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
obd_inidca.setImageResource(R.drawable.red_circle);
break;
}
break;
case Constants.MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(Constants.DEVICE_NAME);
if (null != activity) {
Toast.makeText(activity, "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
obd_inidca.setImageResource(R.drawable.green_circle);
}
break;
case Constants.MESSAGE_TOAST:
if (null != activity) {
Toast.makeText(activity, msg.getData().getString(Constants.TOAST),
Toast.LENGTH_SHORT).show();
}
break;
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
try {
connectDevice(data, true);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void connectDevice(Intent data, boolean secure) throws IOException {
// Get the device MAC address
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BluetoothDevice object
BluetoothDevice dev = mBluetoothAdapter.getRemoteDevice(address);
// Attempt to connect to the device
mChatService.connect(dev, secure);
}.
This is ObdGateway service class:
public class ObdGatewayService extends AbstractGatewayService {
private static final String TAG = ObdGatewayService.class.getName();
#Inject
SharedPreferences prefs;
private BluetoothDevice dev = null;
private BluetoothSocket sock = null;
private BluetoothChatService mChatservice = null;
private BluetoothAdapter bluetoothAdapter =null;
public final static String JOB_NAME_STAMP = "Name";
public final static String JOB_STATE_STAMP = "State";
public final static String JOB_RESULT_STAMP = "Result";
public final static String JOB_FORMATED_RESULT_STAMP = "Formated REsult";
public final static String OBD_GATEWAY_SERVICE = "com.samplersoft.saz.Obd.ObdGatewayService";
public void startService() throws IOException {
Log.d(TAG, "Starting service..");
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// get the remote Bluetooth device
if(mChatservice.getState() != BluetoothChatService.STATE_CONNECTED){
Toast.makeText(ctx, "No Bluetooth device selected", Toast.LENGTH_LONG).show();
// log error
Log.e(TAG, "No Bluetooth device has been selected.");
stopService();
throw new IOException();
}
else
{
Log.d(TAG, "Stopping Bluetooth discovery.");
bluetoothAdapter.cancelDiscovery();
try {
startObdConnection();
} catch (Exception e) {
Log.e(
TAG,
"There was an error while establishing connection. -> "
+ e.getMessage()
);
// in case of failure, stop this service.
stopService();
throw new IOException();
}
}
}
private void startObdConnection() throws IOException {
Log.d(TAG, "Starting OBD connection..");
isRunning = true;
if(mChatservice.getState() == BluetoothChatService.STATE_CONNECTED){
// Let's configure the connection.
Log.d(TAG, "Queueing jobs for connection configuration..");
queueJob(new ObdCommandJob(new ObdResetCommand()));
try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); }
queueJob(new ObdCommandJob(new EchoOffCommand()));
queueJob(new ObdCommandJob(new EchoOffCommand()));
queueJob(new ObdCommandJob(new LineFeedOffCommand()));
queueJob(new ObdCommandJob(new TimeoutCommand(62)));
// Get protocol from preferences
queueJob(new ObdCommandJob(new SelectProtocolCommand(ObdProtocols.valueOf("AUTO"))));
// Job for returning dummy data
queueJob(new ObdCommandJob(new AmbientAirTemperatureCommand()));
queueCounter = 0L;
Log.d(TAG, "Initialization jobs queued.");
}
else {
stopService();
throw new IOException();
}
}
#Override
public void queueJob(ObdCommandJob job) {
// This is a good place to enforce the imperial units option
//job.getCommand().useImperialUnits(prefs.getBoolean(ConfigActivity.IMPERIAL_UNITS_KEY, false));
// Now we can pass it along
super.queueJob(job);
}
protected void executeQueue() throws InterruptedException {
Log.d(TAG, "Executing queue..");
while (!Thread.currentThread().isInterrupted()) {
ObdCommandJob job = null;
try {
job = jobsQueue.take();
// log job
Log.d(TAG, "Taking job[" + job.getId() + "] from queue..");
if (job.getState().equals(ObdCommandJob.ObdCommandJobState.NEW)) {
Log.d(TAG, "Job state is NEW. Run it..");
job.setState(ObdCommandJob.ObdCommandJobState.RUNNING);
if (sock.isConnected()) {
job.getCommand().run(sock.getInputStream(), sock.getOutputStream());
} else {
job.setState(ObdCommandJob.ObdCommandJobState.EXECUTION_ERROR);
Log.e(TAG, "Can't run command on a closed socket.");
}
} else
// log not new job
Log.e(TAG,
"Job state was not new, so it shouldn't be in queue. BUG ALERT!");
} catch (InterruptedException i) {
Thread.currentThread().interrupt();
} catch (UnsupportedCommandException u) {
if (job != null) {
job.setState(ObdCommandJob.ObdCommandJobState.NOT_SUPPORTED);
}
Log.d(TAG, "Command not supported. -> " + u.getMessage());
} catch (IOException io) {
if (job != null) {
if(io.getMessage().contains("Broken pipe"))
job.setState(ObdCommandJob.ObdCommandJobState.BROKEN_PIPE);
else
job.setState(ObdCommandJob.ObdCommandJobState.EXECUTION_ERROR);
}
Log.e(TAG, "IO error. -> " + io.getMessage());
} catch (Exception e) {
if (job != null) {
job.setState(ObdCommandJob.ObdCommandJobState.EXECUTION_ERROR);
}
Log.e(TAG, "Failed to run command. -> " + e.getMessage());
}
ObdCommandJob job2 = job;
if(job2 !=null)
EventBus.getDefault().post(job2);
}
}
public void stopService() {
Log.d(TAG, "Stopping service..");
jobsQueue.clear();
isRunning = false;
if (sock != null)
// close socket
try {
sock.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
// kill service
stopSelf();
}
public boolean isRunning() {
return isRunning;
}
}.
This is Abstract Class where service method gets called from from Livefragment Class from serivceConnection().
public abstract class AbstractGatewayService extends RoboService {
private static final String TAG = AbstractGatewayService.class.getName();
private final IBinder binder = new AbstractGatewayServiceBinder();
protected Context ctx;
protected boolean isRunning = false;
protected Long queueCounter = 0L;
protected BlockingQueue<ObdCommandJob> jobsQueue = new LinkedBlockingQueue<>();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
executeQueue();
} catch (InterruptedException e) {
t.interrupt();
}
}
});
protected LocalBroadcastManager broadcastManager;
#Override
public IBinder onBind(Intent intent) {
return binder;
}
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "Creating service..");
final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
t.start();
Log.d(TAG, "Service created.");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "Destroying service...");
t.interrupt();
broadcastManager = LocalBroadcastManager.getInstance(this);
Log.d(TAG, "Service destroyed.");
}
public boolean isRunning() {
return isRunning;
}
public boolean queueEmpty() {
return jobsQueue.isEmpty();
}
public void queueJob(ObdCommandJob job) {
queueCounter++;
Log.d(TAG, "Adding job[" + queueCounter + "] to queue..");
job.setId(queueCounter);
try {
jobsQueue.put(job);
Log.d(TAG, "Job queued successfully.");
} catch (InterruptedException e) {
job.setState(ObdCommandJob.ObdCommandJobState.QUEUE_ERROR);
Log.e(TAG, "Failed to queue job.");
}
}
public void setContext(Context c) {
ctx = c;
}
abstract protected void executeQueue() throws InterruptedException;
abstract public void startService() throws IOException;
abstract public void stopService();
public class AbstractGatewayServiceBinder extends Binder {
public AbstractGatewayService getService() {
return AbstractGatewayService.this;
}
}
}.
You are getting the exception because in class ObdGatewayService your class member mChatservice is not the same as mChatservice in class LiveFragment
They are just different member variables
mChatservice gets assigned like this in your Fragment
mChatService = new BluetoothChatService(getActivity(), mHandler);
You need to pass this reference to ObdGatewayService 's startService() like this where ever you are instantiating/invoking it:-
ObdGatewayService ogs;
....
ogs.startservice(mChatservice); // This is fragment's member reference
And in ObdGatewayService you have to assign it accordingly:-
public void startService(BluetoothChatService _mChatservice) throws IOException {
Log.d(TAG, "Starting service..");
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mChatservice = _mChatservice //Assignment YOU ARE MISSING THIS
.......
.......
}

Detecting incoming call [duplicate]

This question already has answers here:
How to detect incoming calls, in an Android device?
(13 answers)
Closed 6 years ago.
Here, I'm creating a application to start flash when an sms is recieved and an incoming call is recieved. The flash is working on recieving sms but not on call, why? Can anyone help? I'm stuck on this since many days. Thanks in advance, my code is given below. Flash only performs on recieving sms but not on recieving calls. Expecting your guidence. When I searched regarding this I am getting only the Classes and methods to create my own app. Requesting for the explanation
public class SMSReceiver extends BroadcastReceiver {
Boolean call;
private Camera camera;
int count;
long delaytime;
Editor editor;
String flashtype;
private boolean hasFlash;
private boolean isFlashOn;
private boolean isFlashblinking;
private boolean mActive;
private Handler mHander;
private final Runnable mRunnable;
private boolean mSwap;
private Context mcontext;
AudioManager myAudioManager;
String noofblinks;
int numbofblink;
Parameters params;
SharedPreferences pref;
StringBuilder result;
Boolean ring;
Boolean silent;
Boolean sms;
String timetoblink;
Boolean vibrate;
public class PhoneListener extends PhoneStateListener {
private Context context;
public PhoneListener(Context c) {
Log.i("CallRecorder", "PhoneListener constructor");
this.context = c;
}
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case 0:
try {
SMSReceiver.this.mHander
.removeCallbacks(SMSReceiver.this.mRunnable);
if (SMSReceiver.this.camera != null) {
SMSReceiver.this.camera.release();
}
} catch (Exception e) {
try {
SMSReceiver.this.camera.release();
} catch (Exception e2) {
}
}
case 1:
try {
if (SMSReceiver.this.call.booleanValue()) {
if (SMSReceiver.this.myAudioManager.getRingerMode() == 0
&& SMSReceiver.this.silent.booleanValue()) {
SMSReceiver.this.flash();
}
if (SMSReceiver.this.myAudioManager.getRingerMode() == 1
&& SMSReceiver.this.vibrate.booleanValue()) {
SMSReceiver.this.flash();
}
if (SMSReceiver.this.myAudioManager.getRingerMode() == 2
&& SMSReceiver.this.ring.booleanValue()) {
SMSReceiver.this.flash();
}
}
} catch (Exception e3) {
}
case 2:
try {
SMSReceiver.this.mHander
.removeCallbacks(SMSReceiver.this.mRunnable);
if (SMSReceiver.this.camera != null) {
SMSReceiver.this.camera.release();
}
} catch (Exception e4) {
try {
SMSReceiver.this.camera.release();
} catch (Exception e5) {
}
}
default:
}
}
}
public SMSReceiver() {
this.mHander = new Handler();
this.mActive = false;
this.mSwap = true;
this.isFlashblinking = true;
this.count = 0;
this.mRunnable = new Runnable() {
#Override
// TODO Auto-generated method stub
public void run() {
try {
SMSReceiver sMSReceiver = SMSReceiver.this;
sMSReceiver.count++;
} catch (Exception e) {
}
if (SMSReceiver.this.mActive) {
if (SMSReceiver.this.count >= SMSReceiver.this.numbofblink * 2) {
try {
SMSReceiver.this.mHander
.removeCallbacks(SMSReceiver.this.mRunnable);
SMSReceiver.this.camera.release();
} catch (Exception e2) {
}
}
if (SMSReceiver.this.isFlashOn) {
SMSReceiver.this.turnOffFlash();
} else {
SMSReceiver.this.turnOnFlash();
}
try {
SMSReceiver.this.mHander.postDelayed(
SMSReceiver.this.mRunnable,
SMSReceiver.this.delaytime);
} catch (Exception e3) {
}
}
}
};
}
public void onReceive(Context context, Intent intent) {
try {
this.mcontext = context;
this.count = 0;
try {
this.pref = PreferenceManager
.getDefaultSharedPreferences(this.mcontext);
this.editor = this.pref.edit();
this.call = Boolean.valueOf(this.pref.getBoolean("call", true));
this.sms = Boolean.valueOf(this.pref.getBoolean("sms", true));
this.timetoblink = this.pref.getString("blinktime", "200");
this.noofblinks = this.pref.getString("noofblinks", "5");
this.ring = Boolean.valueOf(this.pref.getBoolean("ring", true));
this.vibrate = Boolean.valueOf(this.pref.getBoolean("vibrate",
true));
this.silent = Boolean.valueOf(this.pref.getBoolean("silent",
true));
this.flashtype = this.pref.getString("flashtype", "1");
this.delaytime = Long.parseLong(this.timetoblink);
this.numbofblink = Integer.parseInt(this.noofblinks);
this.myAudioManager = (AudioManager) this.mcontext
.getSystemService("audio");
} catch (Exception e) {
}
((TelephonyManager) this.mcontext.getSystemService("phone"))
.listen(new PhoneListener(context), 32);
} catch (Exception e2) {
}
}
public void flash() {
try {
this.hasFlash = this.mcontext.getPackageManager().hasSystemFeature(
"android.hardware.camera.flash");
if (this.hasFlash) {
getCamera();
startStrobe();
return;
}
AlertDialog alert = new Builder(this.mcontext).create();
alert.setTitle("Error");
alert.setMessage("Sorry, your device doesn't support flash light!");
alert.setButton("OK", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
alert.show();
} catch (Exception e) {
}
}
private void getCamera() {
if (this.camera == null) {
try {
this.camera = Camera.open();
this.params = this.camera.getParameters();
} catch (Exception e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
}
}
private void turnOnFlash() {
try {
if (!this.isFlashOn && this.camera != null && this.params != null) {
this.params = this.camera.getParameters();
if (this.flashtype.equals("2")) {
this.params.setFlashMode("torch");
} else if (this.flashtype.equals("3")) {
this.params.setFlashMode("torch");
} else {
this.params.setFlashMode("torch");
}
this.camera.setParameters(this.params);
this.camera.startPreview();
this.isFlashOn = true;
}
} catch (Exception e) {
}
}
private void turnOffFlash() {
try {
if (this.isFlashOn && this.camera != null && this.params != null) {
this.params = this.camera.getParameters();
this.params.setFlashMode("off");
this.camera.setParameters(this.params);
this.camera.stopPreview();
this.isFlashOn = false;
}
} catch (Exception e) {
}
}
private void startStrobe() {
try {
this.mActive = true;
this.mHander.post(this.mRunnable);
} catch (Exception e) {
}
}
}
This is doable
follow this link for the same
http://androidexample.com/Incomming_Phone_Call_Broadcast_Receiver__-_Android_Example/index.php?view=article_discription&aid=61
Make a broadcast receiver to know about incoming call
write that code in AndroidManifes.xml
<receiver android:name=".ServiceReceiver" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
and make a new a class like that.
public class ServiceReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(new PhoneStateListener(){
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if(state.equals(TelephonyManager.EXTRA_STATE_RINGING)){
// Run the flash in that line
}
}
},PhoneStateListener.LISTEN_CALL_STATE);
}
}

How to Print a PDF in thermal Printer? PDF from URL/Local to Printer

I followed Epson SDK and used sample code... To print Receipts
So over there from samples I got that I can print Text, Image and both Ways...
By using this... to print Text and Images..
public class MainActivity extends Activity implements View.OnClickListener, ReceiveListener {
private Context mContext = null;
private EditText mEditTarget = null;
private Spinner mSpnSeries = null;
private Spinner mSpnLang = null;
private Printer mPrinter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
int[] target = {
R.id.btnDiscovery,
R.id.btnSampleReceipt,
};
for (int i = 0; i < target.length; i++) {
Button button = (Button)findViewById(target[i]);
button.setOnClickListener(this);
}
mSpnSeries = (Spinner)findViewById(R.id.spnModel);
ArrayAdapter<SpnModelsItem> seriesAdapter = new ArrayAdapter<SpnModelsItem>(this, android.R.layout.simple_spinner_item);
seriesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
seriesAdapter.add(new SpnModelsItem(getString(R.string.printerseries_t20), Printer.TM_T20));
mSpnSeries.setAdapter(seriesAdapter);
mSpnSeries.setSelection(0);
try {
Log.setLogSettings(mContext, Log.PERIOD_TEMPORARY, Log.OUTPUT_STORAGE, null, 0, 1, Log.LOGLEVEL_LOW);
}
catch (Exception e) {
ShowMsg.showException(e, "setLogSettings", mContext);
}
mEditTarget = (EditText)findViewById(R.id.edtTarget);
}
#Override
protected void onActivityResult(int requestCode, final int resultCode, final Intent data) {
if (data != null && resultCode == RESULT_OK) {
String target = data.getStringExtra(getString(R.string.title_target));
if (target != null) {
EditText mEdtTarget = (EditText)findViewById(R.id.edtTarget);
mEdtTarget.setText(target);
}
}
}
#Override
public void onClick(View v) {
Intent intent = null;
switch (v.getId()) {
case R.id.btnDiscovery:
intent = new Intent(this, DiscoveryActivity.class);
startActivityForResult(intent, 0);
break;
case R.id.btnSampleReceipt:
updateButtonState(false);
if (!runPrintReceiptSequence()) {
updateButtonState(true);
}
break;
case R.id.btnSampleCoupon:
updateButtonState(false);
if (!runPrintCouponSequence()) {
updateButtonState(true);
}
break;
default:
// Do nothing
break;
}
}
private boolean runPrintReceiptSequence() {
if (!initializeObject()) {
return false;
}
if (!createReceiptData()) {
finalizeObject();
return false;
}
if (!printData()) {
finalizeObject();
return false;
}
return true;
}
private boolean createReceiptData() {
String method = "";
Bitmap logoData = BitmapFactory.decodeResource(getResources(), R.drawable.store);
StringBuilder textData = new StringBuilder();
final int barcodeWidth = 2;
final int barcodeHeight = 100;
if (mPrinter == null) {
return false;
}
try {
method = "addTextAlign";
mPrinter.addTextAlign(Printer.ALIGN_CENTER);
method = "addImage";
mPrinter.addImage(logoData, 0, 0,
logoData.getWidth(),
logoData.getHeight(),
Printer.COLOR_1,
Printer.MODE_MONO,
Printer.HALFTONE_DITHER,
Printer.PARAM_DEFAULT,
Printer.COMPRESS_AUTO);
method = "addFeedLine";
mPrinter.addFeedLine(1);
textData.append("EPSON PRINT DEMO TEST - \n");
textData.append("STORE DIRECTOR – XYZ\n");
textData.append("\n");
textData.append("28/06/16 05:15 012 0154 0225\n");
textData.append("ST# 21 OP# 001 TE# 01 TR# 747\n");
textData.append("------------------------------\n");
method = "addText";
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
textData.append("524 5 GREEN TEA 19.99 R\n");
textData.append("003 2 LEMON TEA 59.99 R\n");
textData.append("------------------------------\n");
method = "addText";
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
textData.append("SUBTOTAL 79.98\n");
textData.append("TAX 15.00\n");
method = "addText";
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
method = "addTextSize";
mPrinter.addTextSize(2, 2);
method = "addText";
mPrinter.addText("TOTAL 94.98.41\n");
method = "addTextSize";
mPrinter.addTextSize(1, 1);
method = "addFeedLine";
mPrinter.addFeedLine(1);
textData.append("CASH 100.00\n");
textData.append("CHANGE 5.02\n");
textData.append("------------------------------\n");
method = "addText";
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
textData.append("Purchased item total number\n");
textData.append("Sign Up and Save !\n");
textData.append("With Preferred Saving Card\n");
method = "addText";
mPrinter.addText(textData.toString());
textData.delete(0, textData.length());
method = "addFeedLine";
mPrinter.addFeedLine(2);
method = "addCut";
mPrinter.addCut(Printer.CUT_FEED);
}
catch (Exception e) {
ShowMsg.showException(e, method, mContext);
return false;
}
textData = null;
return true;
}
private boolean runPrintCouponSequence() {
if (!initializeObject()) {
return false;
}
if (!createCouponData()) {
finalizeObject();
return false;
}
if (!printData()) {
finalizeObject();
return false;
}
return true;
}
private boolean printData() {
if (mPrinter == null) {
return false;
}
if (!connectPrinter()) {
return false;
}
PrinterStatusInfo status = mPrinter.getStatus();
dispPrinterWarnings(status);
if (!isPrintable(status)) {
ShowMsg.showMsg(makeErrorMessage(status), mContext);
try {
mPrinter.disconnect();
}
catch (Exception ex) {
// Do nothing
}
return false;
}
try {
mPrinter.sendData(Printer.PARAM_DEFAULT);
}
catch (Exception e) {
ShowMsg.showException(e, "sendData", mContext);
try {
mPrinter.disconnect();
}
catch (Exception ex) {
// Do nothing
}
return false;
}
return true;
}
private boolean initializeObject() {
try {
mPrinter = new Printer(((SpnModelsItem) mSpnSeries.getSelectedItem()).getModelConstant(),
((SpnModelsItem) mSpnLang.getSelectedItem()).getModelConstant(),
mContext);
}
catch (Exception e) {
ShowMsg.showException(e, "Printer", mContext);
return false;
}
mPrinter.setReceiveEventListener(this);
return true;
}
private void finalizeObject() {
if (mPrinter == null) {
return;
}
mPrinter.clearCommandBuffer();
mPrinter.setReceiveEventListener(null);
mPrinter = null;
}
private boolean connectPrinter() {
boolean isBeginTransaction = false;
if (mPrinter == null) {
return false;
}
try {
mPrinter.connect(mEditTarget.getText().toString(), Printer.PARAM_DEFAULT);
}
catch (Exception e) {
ShowMsg.showException(e, "connect", mContext);
return false;
}
try {
mPrinter.beginTransaction();
isBeginTransaction = true;
}
catch (Exception e) {
ShowMsg.showException(e, "beginTransaction", mContext);
}
if (isBeginTransaction == false) {
try {
mPrinter.disconnect();
}
catch (Epos2Exception e) {
// Do nothing
return false;
}
}
return true;
}
private void disconnectPrinter() {
if (mPrinter == null) {
return;
}
try {
mPrinter.endTransaction();
}
catch (final Exception e) {
runOnUiThread(new Runnable() {
#Override
public synchronized void run() {
ShowMsg.showException(e, "endTransaction", mContext);
}
});
}
try {
mPrinter.disconnect();
}
catch (final Exception e) {
runOnUiThread(new Runnable() {
#Override
public synchronized void run() {
ShowMsg.showException(e, "disconnect", mContext);
}
});
}
finalizeObject();
}
private boolean isPrintable(PrinterStatusInfo status) {
if (status == null) {
return false;
}
if (status.getConnection() == Printer.FALSE) {
return false;
}
else if (status.getOnline() == Printer.FALSE) {
return false;
}
else {
;//print available
}
return true;
}
private String makeErrorMessage(PrinterStatusInfo status) {
String msg = "";
if (status.getBatteryLevel() == Printer.BATTERY_LEVEL_0) {
msg += getString(R.string.handlingmsg_err_battery_real_end);
}
return msg;
}
private void dispPrinterWarnings(PrinterStatusInfo status) {
EditText edtWarnings = (EditText)findViewById(R.id.edtWarnings);
String warningsMsg = "";
if (status == null) {
return;
}
if (status.getPaper() == Printer.PAPER_NEAR_END) {
warningsMsg += getString(R.string.handlingmsg_warn_receipt_near_end);
}
if (status.getBatteryLevel() == Printer.BATTERY_LEVEL_1) {
warningsMsg += getString(R.string.handlingmsg_warn_battery_near_end);
}
edtWarnings.setText(warningsMsg);
}
private void updateButtonState(boolean state) {
Button btnReceipt = (Button)findViewById(R.id.btnSampleReceipt);
Button btnCoupon = (Button)findViewById(R.id.btnSampleCoupon);
btnReceipt.setEnabled(state);
btnCoupon.setEnabled(state);
}
#Override
public void onPtrReceive(final Printer printerObj, final int code, final PrinterStatusInfo status, final String printJobId) {
runOnUiThread(new Runnable() {
#Override
public synchronized void run() {
ShowMsg.showResult(code, makeErrorMessage(status), mContext);
dispPrinterWarnings(status);
updateButtonState(true);
new Thread(new Runnable() {
#Override
public void run() {
disconnectPrinter();
}
}).start();
}
});
}
}
In the same way I want to print PDF. Is this Possible without any library?
Or else is it possible to print PDF in thermal Printer?
Can anyone suggest me how to print PDF in a thermal printer?
Here I have this to print a Image/bitmap
Bitmap logoData = BitmapFactory.decodeResource(getResources(), R.drawable.store);
StringBuilder textData = new StringBuilder();
final int barcodeWidth = 2;
final int barcodeHeight = 100;
with addimage.. and for text I am giving plain text... with addtext....
Can Any one suggest Me How to add a PDF to this...
I followed May tutorials,... But Nothing Found related to PDF in thermal Printer(EPSON) Printer..

Google Play Games API returns RESULT_RECONNECT_REQUIRED when submit user score

I am creating a game using the API of Google Play Games. I have read the documentation on the leaderboards. I have used the same code to update the user's score, but it always returns the code RESULT_RECONNECT_REQUIRED. I've used the logcat to display the results of the call:
E/GameProgress: Result score CgkIoY-5lt0DEAIQEA: ScoreSubmissionData{PlayerId=128090785697, StatusCode=2, TimesSpan=DAILY, Result=null, TimesSpan=WEEKLY, Result=null, TimesSpan=ALL_TIME, Result=null}
Here is the code:
public class GameActivity extends AppCompatActivity {
private GameHelper mHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
...
mHelper = new GameHelper(this, 1);
mHelper.enableDebugLog(true);
mHelper.setup(new GameHelper.GameHelperListener() {
#Override
public void onSignInFailed() {
Log.e(TAG, "Sign in failed");
}
#Override
public void onSignInSucceeded() {
Log.e(TAG, "Sign in Succeded");
addScores(GameId.LEADERBOARDS.TEN_THOUSAND);
}
});
}
private void addScores(String leaderBoard) {
PendingResult<Leaderboards.SubmitScoreResult> result = Games.Leaderboards.submitScoreImmediate(mGoogleApiClient, leaderBoard, 5);
result.setResultCallback(new ResultCallback<Leaderboards.SubmitScoreResult>() {
#Override
public void onResult(#NonNull Leaderboards.SubmitScoreResult submitScoreResult) {
Log.e(TAG, "Result score " + leaderBoard + ": " + submitScoreResult.getScoreData().toString());
}
});
}
}
GameHelperClass:
public class GameHelper implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
static final String TAG = "GameHelper";
public interface GameHelperListener {
void onSignInFailed();
void onSignInSucceeded();
}
private boolean mSetupDone = false;
private boolean mConnecting = false;
boolean mExpectingResolution = false;
boolean mSignInCancelled = false;
Activity mActivity = null;
Context mAppContext = null;
public final static int RC_RESOLVE = 9001;
final static int RC_UNUSED = 9002;
GoogleApiClient.Builder mGoogleApiClientBuilder = null;
GamesOptions mGamesApiOptions = GamesOptions.builder().build();
PlusOptions mPlusApiOptions = null;
GoogleApiClient mGoogleApiClient = null;
// Client request flags
public final static int CLIENT_NONE = 0x00;
public final static int CLIENT_GAMES = 0x01;
public final static int CLIENT_PLUS = 0x02;
public final static int CLIENT_SNAPSHOT = 0x08;
public final static int CLIENT_ALL = CLIENT_GAMES | CLIENT_PLUS
| CLIENT_SNAPSHOT;
int mRequestedClients = CLIENT_NONE;
boolean mConnectOnStart = true;
boolean mUserInitiatedSignIn = false;
ConnectionResult mConnectionResult = null;
SignInFailureReason mSignInFailureReason = null;
boolean mShowErrorDialogs = true;
boolean mDebugLog = false;
Handler mHandler;
Invitation mInvitation;
TurnBasedMatch mTurnBasedMatch;
ArrayList<GameRequest> mRequests;
// Listener
GameHelperListener mListener = null;
static final int DEFAULT_MAX_SIGN_IN_ATTEMPTS = 3;
int mMaxAutoSignInAttempts = DEFAULT_MAX_SIGN_IN_ATTEMPTS;
private GameErrorHandler mGameErrorHandler;
public GameHelper(Activity activity, int clientsToUse) {
mActivity = activity;
mAppContext = activity.getApplicationContext();
mRequestedClients = clientsToUse;
mHandler = new Handler();
}
public void setMaxAutoSignInAttempts(int max) {
mMaxAutoSignInAttempts = max;
}
public void setGameErrorHandler(GameErrorHandler mGameErrorHandler) {
this.mGameErrorHandler = mGameErrorHandler;
}
void assertConfigured(String operation) {
if (!mSetupDone) {
String error = "GameHelper error: Operation attempted without setup: "
+ operation
+ ". The setup() method must be called before attempting any other operation.";
logError(error);
throw new IllegalStateException(error);
}
}
private void doApiOptionsPreCheck() {
if (mGoogleApiClientBuilder != null) {
String error = "GameHelper: you cannot call set*ApiOptions after the client "
+ "builder has been created. Call it before calling createApiClientBuilder() "
+ "or setup().";
logError(error);
throw new IllegalStateException(error);
}
}
public void setGamesApiOptions(GamesOptions options) {
doApiOptionsPreCheck();
mGamesApiOptions = options;
}
public void setPlusApiOptions(PlusOptions options) {
doApiOptionsPreCheck();
mPlusApiOptions = options;
}
public GoogleApiClient.Builder createApiClientBuilder() {
if (mSetupDone) {
String error = "GameHelper: you called GameHelper.createApiClientBuilder() after "
+ "calling setup. You can only get a client builder BEFORE performing setup.";
logError(error);
throw new IllegalStateException(error);
}
GoogleApiClient.Builder builder = new GoogleApiClient.Builder(
mActivity, this, this);
if (0 != (mRequestedClients & CLIENT_GAMES)) {
builder.addApi(Games.API, mGamesApiOptions);
builder.addScope(Games.SCOPE_GAMES);
}
if (0 != (mRequestedClients & CLIENT_PLUS)) {
builder.addApi(Plus.API);
builder.addScope(Plus.SCOPE_PLUS_LOGIN);
}
if (0 != (mRequestedClients & CLIENT_SNAPSHOT)) {
builder.addScope(Drive.SCOPE_APPFOLDER);
builder.addApi(Drive.API);
}
mGoogleApiClientBuilder = builder;
return builder;
}
public void setup(GameHelperListener listener) {
if (mSetupDone) {
String error = "GameHelper: you cannot call GameHelper.setup() more than once!";
logError(error);
throw new IllegalStateException(error);
}
mListener = listener;
debugLog("Setup: requested clients: " + mRequestedClients);
if (mGoogleApiClientBuilder == null) {
// we don't have a builder yet, so create one
createApiClientBuilder();
}
mGoogleApiClient = mGoogleApiClientBuilder.build();
mGoogleApiClientBuilder = null;
mSetupDone = true;
}
public GoogleApiClient getApiClient() {
if (mGoogleApiClient == null) {
throw new IllegalStateException(
"No GoogleApiClient. Did you call setup()?");
}
return mGoogleApiClient;
}
public boolean isSignedIn() {
return mGoogleApiClient != null && mGoogleApiClient.isConnected();
}
public boolean isConnecting() {
return mConnecting;
}
public boolean hasSignInError() {
return mSignInFailureReason != null;
}
public SignInFailureReason getSignInError() {
return mSignInFailureReason;
}
public void setShowErrorDialogs(boolean show) {
mShowErrorDialogs = show;
}
public void onStart(Activity act) {
mActivity = act;
mAppContext = act.getApplicationContext();
debugLog("onStart");
assertConfigured("onStart");
if (mConnectOnStart) {
if (mGoogleApiClient.isConnected()) {
Log.w(TAG,
"GameHelper: client was already connected on onStart()");
} else {
debugLog("Connecting client.");
mConnecting = true;
mGoogleApiClient.connect();
}
} else {
debugLog("Not attempting to connect becase mConnectOnStart=false");
debugLog("Instead, reporting a sign-in failure.");
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
notifyListener(false);
}
}, 1000);
}
}
public void onStop() {
debugLog("onStop");
assertConfigured("onStop");
if (mGoogleApiClient.isConnected()) {
debugLog("Disconnecting client due to onStop");
mGoogleApiClient.disconnect();
} else {
debugLog("Client already disconnected when we got onStop.");
}
mConnecting = false;
mExpectingResolution = false;
// let go of the Activity reference
mActivity = null;
}
public String getInvitationId() {
if (!mGoogleApiClient.isConnected()) {
Log.w(TAG,
"Warning: getInvitationId() should only be called when signed in, "
+ "that is, after getting onSignInSuceeded()");
}
return mInvitation == null ? null : mInvitation.getInvitationId();
}
public Invitation getInvitation() {
if (!mGoogleApiClient.isConnected()) {
Log.w(TAG,
"Warning: getInvitation() should only be called when signed in, "
+ "that is, after getting onSignInSuceeded()");
}
return mInvitation;
}
public boolean hasInvitation() {
return mInvitation != null;
}
public boolean hasTurnBasedMatch() {
return mTurnBasedMatch != null;
}
public boolean hasRequests() {
return mRequests != null;
}
public void clearInvitation() {
mInvitation = null;
}
public void clearTurnBasedMatch() {
mTurnBasedMatch = null;
}
public void clearRequests() {
mRequests = null;
}
public TurnBasedMatch getTurnBasedMatch() {
if (!mGoogleApiClient.isConnected()) {
Log.w(TAG,
"Warning: getTurnBasedMatch() should only be called when signed in, "
+ "that is, after getting onSignInSuceeded()");
}
return mTurnBasedMatch;
}
public ArrayList<GameRequest> getRequests() {
if (!mGoogleApiClient.isConnected()) {
Log.w(TAG, "Warning: getRequests() should only be called "
+ "when signed in, "
+ "that is, after getting onSignInSuceeded()");
}
return mRequests;
}
public void enableDebugLog(boolean enabled) {
mDebugLog = enabled;
if (enabled) {
debugLog("Debug log enabled.");
}
}
#Deprecated
public void enableDebugLog(boolean enabled, String tag) {
Log.w(TAG, "GameHelper.enableDebugLog(boolean,String) is deprecated. "
+ "Use GameHelper.enableDebugLog(boolean)");
enableDebugLog(enabled);
}
public void signOut() {
if (!mGoogleApiClient.isConnected()) {
// nothing to do
debugLog("signOut: was already disconnected, ignoring.");
return;
}
// for Plus, "signing out" means clearing the default account and
// then disconnecting
if (0 != (mRequestedClients & CLIENT_PLUS)) {
debugLog("Clearing default account on PlusClient.");
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
}
// For the games client, signing out means calling signOut and
// disconnecting
if (0 != (mRequestedClients & CLIENT_GAMES)) {
debugLog("Signing out from the Google API Client.");
Games.signOut(mGoogleApiClient);
}
// Ready to disconnect
debugLog("Disconnecting client.");
mConnectOnStart = false;
mConnecting = false;
mGoogleApiClient.disconnect();
}
public void onActivityResult(int requestCode, int responseCode,
Intent intent) {
debugLog("onActivityResult: req="
+ (requestCode == RC_RESOLVE ? "RC_RESOLVE" : String
.valueOf(requestCode)) + ", resp="
+ GameHelperUtils.activityResponseCodeToString(responseCode));
if (requestCode != RC_RESOLVE) {
debugLog("onActivityResult: request code not meant for us. Ignoring.");
return;
}
// no longer expecting a resolution
mExpectingResolution = false;
/* if (!mConnecting) {
debugLog("onActivityResult: ignoring because we are not connecting.");
return;
}*/
if (responseCode == Activity.RESULT_OK) {
// Ready to try to connect again.
debugLog("onAR: Resolution was RESULT_OK, so connecting current client again.");
connect();
} else if (responseCode == GamesActivityResultCodes.RESULT_RECONNECT_REQUIRED) {
debugLog("onAR: Resolution was RECONNECT_REQUIRED, so reconnecting.");
connect();
fireOnReconectRequired();
} else if (responseCode == Activity.RESULT_CANCELED) {
// User cancelled.
debugLog("onAR: Got a cancellation result, so disconnecting.");
mSignInCancelled = true;
mConnectOnStart = false;
mUserInitiatedSignIn = false;
mSignInFailureReason = null; // cancelling is not a failure!
mConnecting = false;
mGoogleApiClient.disconnect();
// increment # of cancellations
int prevCancellations = getSignInCancellations();
int newCancellations = incrementSignInCancellations();
debugLog("onAR: # of cancellations " + prevCancellations + " --> "
+ newCancellations + ", max " + mMaxAutoSignInAttempts);
notifyListener(false);
} else {
// Whatever the problem we were trying to solve, it was not
// solved. So give up and show an error message.
debugLog("onAR: responseCode="
+ GameHelperUtils
.activityResponseCodeToString(responseCode)
+ ", so giving up.");
giveUp(new SignInFailureReason(mConnectionResult.getErrorCode(),
responseCode));
}
}
void notifyListener(boolean success) {
debugLog("Notifying LISTENER of sign-in "
+ (success ? "SUCCESS"
: mSignInFailureReason != null ? "FAILURE (error)"
: "FAILURE (no error)"));
if (mListener != null) {
if (success) {
mListener.onSignInSucceeded();
} else {
mListener.onSignInFailed();
}
}
}
public void beginUserInitiatedSignIn() {
debugLog("beginUserInitiatedSignIn: resetting attempt count.");
resetSignInCancellations();
mSignInCancelled = false;
mConnectOnStart = true;
if (mGoogleApiClient.isConnected()) {
// nothing to do
logWarn("beginUserInitiatedSignIn() called when already connected. "
+ "Calling listener directly to notify of success.");
notifyListener(true);
return;
} else if (mConnecting) {
logWarn("beginUserInitiatedSignIn() called when already connecting. "
+ "Be patient! You can only call this method after you get an "
+ "onSignInSucceeded() or onSignInFailed() callback. Suggestion: disable "
+ "the sign-in button on startup and also when it's clicked, and re-enable "
+ "when you get the callback.");
// ignore call (listener will get a callback when the connection
// process finishes)
return;
}
debugLog("Starting USER-INITIATED sign-in flow.");
mUserInitiatedSignIn = true;
if (mConnectionResult != null) {
debugLog("beginUserInitiatedSignIn: continuing pending sign-in flow.");
mConnecting = true;
resolveConnectionResult();
} else {
// We don't have a pending connection result, so start anew.
debugLog("beginUserInitiatedSignIn: starting new sign-in flow.");
mConnecting = true;
connect();
}
}
void connect() {
if (mGoogleApiClient.isConnected()) {
debugLog("Already connected.");
return;
}
debugLog("Starting connection.");
mConnecting = true;
mInvitation = null;
mTurnBasedMatch = null;
mGoogleApiClient.connect();
}
public void reconnectClient() {
if (!mGoogleApiClient.isConnected()) {
Log.w(TAG, "reconnectClient() called when client is not connected.");
// interpret it as a request to connect
connect();
} else {
debugLog("Reconnecting client.");
mGoogleApiClient.reconnect();
}
}
#Override
public void onConnected(Bundle connectionHint) {
debugLog("onConnected: connected!");
if (connectionHint != null) {
debugLog("onConnected: connection hint provided. Checking for invite.");
Invitation inv = connectionHint
.getParcelable(Multiplayer.EXTRA_INVITATION);
if (inv != null && inv.getInvitationId() != null) {
// retrieve and cache the invitation ID
debugLog("onConnected: connection hint has a room invite!");
mInvitation = inv;
debugLog("Invitation ID: " + mInvitation.getInvitationId());
}
// Do we have any requests pending?
mRequests = Games.Requests
.getGameRequestsFromBundle(connectionHint);
if (!mRequests.isEmpty()) {
// We have requests in onConnected's connectionHint.
debugLog("onConnected: connection hint has " + mRequests.size()
+ " request(s)");
}
debugLog("onConnected: connection hint provided. Checking for TBMP game.");
mTurnBasedMatch = connectionHint
.getParcelable(Multiplayer.EXTRA_TURN_BASED_MATCH);
}
// we're good to go
succeedSignIn();
}
void succeedSignIn() {
debugLog("succeedSignIn");
mSignInFailureReason = null;
mConnectOnStart = true;
mUserInitiatedSignIn = false;
mConnecting = false;
notifyListener(true);
}
private final String GAMEHELPER_SHARED_PREFS = "GAMEHELPER_SHARED_PREFS";
private final String KEY_SIGN_IN_CANCELLATIONS = "KEY_SIGN_IN_CANCELLATIONS";
// Return the number of times the user has cancelled the sign-in flow in the
// life of the app
int getSignInCancellations() {
SharedPreferences sp = mAppContext.getSharedPreferences(
GAMEHELPER_SHARED_PREFS, Context.MODE_PRIVATE);
return sp.getInt(KEY_SIGN_IN_CANCELLATIONS, 0);
}
int incrementSignInCancellations() {
int cancellations = getSignInCancellations();
SharedPreferences.Editor editor = mAppContext.getSharedPreferences(
GAMEHELPER_SHARED_PREFS, Context.MODE_PRIVATE).edit();
editor.putInt(KEY_SIGN_IN_CANCELLATIONS, cancellations + 1);
editor.commit();
return cancellations + 1;
}
void resetSignInCancellations() {
SharedPreferences.Editor editor = mAppContext.getSharedPreferences(
GAMEHELPER_SHARED_PREFS, Context.MODE_PRIVATE).edit();
editor.putInt(KEY_SIGN_IN_CANCELLATIONS, 0);
editor.commit();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// save connection result for later reference
debugLog("onConnectionFailed");
mConnectionResult = result;
debugLog("Connection failure:");
debugLog(" - code: "
+ GameHelperUtils.errorCodeToString(mConnectionResult
.getErrorCode()));
debugLog(" - resolvable: " + mConnectionResult.hasResolution());
debugLog(" - details: " + mConnectionResult.toString());
int cancellations = getSignInCancellations();
boolean shouldResolve = false;
if (mUserInitiatedSignIn) {
debugLog("onConnectionFailed: WILL resolve because user initiated sign-in.");
shouldResolve = true;
} else if (mSignInCancelled) {
debugLog("onConnectionFailed WILL NOT resolve (user already cancelled once).");
shouldResolve = false;
} else if (cancellations < mMaxAutoSignInAttempts) {
debugLog("onConnectionFailed: WILL resolve because we have below the max# of "
+ "attempts, "
+ cancellations
+ " < "
+ mMaxAutoSignInAttempts);
shouldResolve = true;
} else {
shouldResolve = false;
debugLog("onConnectionFailed: Will NOT resolve; not user-initiated and max attempts "
+ "reached: "
+ cancellations
+ " >= "
+ mMaxAutoSignInAttempts);
}
if (!shouldResolve) {
// Fail and wait for the user to want to sign in.
debugLog("onConnectionFailed: since we won't resolve, failing now.");
mConnectionResult = result;
mConnecting = false;
notifyListener(false);
return;
}
debugLog("onConnectionFailed: resolving problem...");
resolveConnectionResult();
}
void resolveConnectionResult() {
// Try to resolve the problem
if (mExpectingResolution) {
debugLog("We're already expecting the result of a previous resolution.");
return;
}
if (mActivity == null) {
debugLog("No need to resolve issue, activity does not exist anymore");
return;
}
debugLog("resolveConnectionResult: trying to resolve result: "
+ mConnectionResult);
if (mConnectionResult.hasResolution()) {
// This problem can be fixed. So let's try to fix it.
debugLog("Result has resolution. Starting it.");
try {
// launch appropriate UI flow (which might, for example, be the
// sign-in flow)
mExpectingResolution = true;
mConnectionResult.startResolutionForResult(mActivity,
RC_RESOLVE);
} catch (SendIntentException e) {
// Try connecting again
debugLog("SendIntentException, so connecting again.");
connect();
}
} else {
// It's not a problem what we can solve, so give up and show an
// error.
debugLog("resolveConnectionResult: result has no resolution. Giving up.");
giveUp(new SignInFailureReason(mConnectionResult.getErrorCode()));
mConnectionResult = null;
}
}
public void disconnect() {
if (mGoogleApiClient.isConnected()) {
debugLog("Disconnecting client.");
mGoogleApiClient.disconnect();
} else {
Log.w(TAG,
"disconnect() called when client was already disconnected.");
}
}
void giveUp(SignInFailureReason reason) {
mConnectOnStart = false;
disconnect();
mSignInFailureReason = reason;
if (reason.mActivityResultCode == GamesActivityResultCodes.RESULT_APP_MISCONFIGURED) {
// print debug info for the developer
GameHelperUtils.printMisconfiguredDebugInfo(mAppContext);
}
showFailureDialog();
mConnecting = false;
notifyListener(false);
}
#Override
public void onConnectionSuspended(int cause) {
debugLog("onConnectionSuspended, cause=" + cause);
disconnect();
mSignInFailureReason = null;
debugLog("Making extraordinary call to onSignInFailed callback");
mConnecting = false;
notifyListener(false);
}
. . .
void debugLog(String message) {
if (mDebugLog) {
Log.d(TAG, message);
}
}
void logWarn(String message) {
Log.w(TAG, "!!! GameHelper WARNING: " + message);
}
void logError(String message) {
Log.e(TAG, "*** GameHelper ERROR: " + message);
}
// Represents the reason for a sign-in failure
public static class SignInFailureReason {
public static final int NO_ACTIVITY_RESULT_CODE = -100;
int mServiceErrorCode = 0;
int mActivityResultCode = NO_ACTIVITY_RESULT_CODE;
public int getServiceErrorCode() {
return mServiceErrorCode;
}
public int getActivityResultCode() {
return mActivityResultCode;
}
public SignInFailureReason(int serviceErrorCode, int activityResultCode) {
mServiceErrorCode = serviceErrorCode;
mActivityResultCode = activityResultCode;
}
public SignInFailureReason(int serviceErrorCode) {
this(serviceErrorCode, NO_ACTIVITY_RESULT_CODE);
}
public void setConnectOnStart(boolean connectOnStart) {
debugLog("Forcing mConnectOnStart=" + connectOnStart);
mConnectOnStart = connectOnStart;
}
}
I've tried to change the score, but there is nothing, I have also checked that the leaderboard is set up correctly.

Categories

Resources