For retrieve location i have used GoogleAPIClient with FusedLocationProvider API.
These functions are in onCreate() method.
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
gpsChecker();
Full Code
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
public void gpsChecker() {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can initialize location
// requests here.
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the user
// a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(
AddVisitActivity.this, 1000);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
break;
}
}
});
}
For run time permissions i did this.
protected void startLocationUpdates() {
if (ActivityCompat.shouldShowRequestPermissionRationale
(AddVisitActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
Snackbar.make(findViewById(android.R.id.content),
"Please Grant Permissions",
Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(AddVisitActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(AddVisitActivity.this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE_LOCATION);
} else {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, AddVisitActivity.this);
Log.d(TAG, "Location update started ...: ");
}
}
}).show();
} else {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_CODE_LOCATION);
} else {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Location update started ...: ");
}
}
}
For checking if the GPS enabled or not in setting screen using gpsChecker() with request code 1000 and in onActivityResult() i have done this.
if (requestCode == 1000) {
switch (resultCode) {
case Activity.RESULT_OK:
Log.i(TAG, "User agreed to make required location settings changes.");
startLocationUpdates();
break;
case Activity.RESULT_CANCELED:
Log.i(TAG, "User chose not to make required location settings changes.");
finish();
break;
}
}
While i execute this code in some devices its working and in some device the location request automatically set to Device Only or Battery Saving though i have set mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
Note : Mi Note 4, Vivo V9 Pro, Mi Note 5 Pro and some other device getting the issue
So what should i need to change in my code so will it work proper with the High Accuracy?
Finally solved by changing
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
to
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
and change
private static final long INTERVAL = 1000 * 60 * 60;
private static final long FASTEST_INTERVAL = 1000 * 5;
interval time to 30 minutes and fastest interval to 5 seconds means once get location in 5 seconds after then new location will be get in 30 minutes.
Try this solutin with GPS Provider and make sure that your GPS service is ON.
static final int LOCATION_INTERVAL = 1000;
static final float LOCATION_DISTANCE = 10f;
//put this in onCreate();
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
mprovider = locationManager.getBestProvider(criteria, false);
if (mprovider != null && !mprovider.equals("")) {
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 location = locationManager.getLastKnownLocation(mprovider);
locationManager.requestLocationUpdates(mprovider, LOCATION_INTERVAL, LOCATION_DISTANCE, this);
if (location != null)
onLocationChanged(location);
else
Toast.makeText(getBaseContext(), "No Location Provider Found Check Your Code", Toast.LENGTH_SHORT).show();
}
//put this LocationListener after onCreate();
public LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.e(String.format("%f, %f", location.getLatitude(), location.getLongitude()), "");
Log.e("Location available", "Location available");
locationManager.removeUpdates(mLocationListener);
} else {
Log.e("Location is null", "Location is null");
}
current_latitude = location.getLatitude();
current_longitude = location.getLongitude();
/* LatLng latLng = new LatLng(current_latitude, current_longitude);
points.add(latLng);
redrawLine();*/
Log.e("current_latitude", String.valueOf(current_latitude));
Log.e("current_longitude", String.valueOf(current_longitude));
if (location.hasSpeed()) {
//progressBarCircularIndeterminate.setVisibility(View.GONE);
String speed = String.format(Locale.ENGLISH, "%.0f", location.getSpeed() * 3.6) + "km/h";
SpannableString s = new SpannableString(speed);
s.setSpan(new RelativeSizeSpan(0.25f), s.length() - 4, s.length(), 0);
txt_current_speed.setText(s);
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
Related
I'm stucked for a while trying to use zkemkeeper sdk to use on a Windows Service that uses a InBios(Controller) for fingerprint.
i first connect to the device and then i add the event OnAttTransactionEx, someone can point me what i'm doing wrong.
Here is the code snippet
`
protected override void OnStart(string[] args)
{
Thread TT = new Thread(new ThreadStart(WorkedThread));
TT.IsBackground = true;
TT.SetApartmentState(ApartmentState.STA);
this.isServiceStarted = true;
TT.Start();
}
private void WorkedThread()
{
WriteToFile("Worker Thread Started.");
ZKemClient objZkeeper = new ZKemClient(filepath);
this.isDeviceConnected = objZkeeper.Connect_Net("19x.x.x.24x", 4370);
if (this.isDeviceConnected)
{
WriteToFile("Device connected.");
WriteToFile("While loop execution starting.");
while (true)
{
WriteToFile(filepath, "While loop execution started.");
}
}
else
{
WriteToFile("Failed to connect to Device.");
}
}
// ZMClient class
public bool Connect_Net(string IPAdd, int Port)
{
bool bResult = false;
try
{
// Actual SDK class
CZKEM objCZKEM = new CZKEM();
if (objCZKEM.Connect_Net(IPAdd, Port))
{
if (objCZKEM.RegEvent(1, 32767))
{
// [ Register your events here ]
objCZKEM.OnAttTransactionEx += new _IZKEMEvents_OnAttTransactionExEventHandler(zkemClient_OnAttTransactionEx);
}
bResult = true;
}
}
catch (Exception ex)
{
WriteToFile("Connect_Net() Exception->" + ex.Message);
}
return bResult;
}
`
After playing a lot with threading, found a solution.
For windows service - Add reference to System.Windows.Forms
Thread TT1 = new Thread(() =>
{
this.objCZKEM = new CZKEM();
Application.Run();
});
TT1.IsBackground = true;
TT1.SetApartmentState(ApartmentState.STA);
TT1.Start();
Simply continue with current thread
if (this.objCZKEM.Connect_Net(IP, 4370))
{
this.WriteToFile("ZKEM device connected");
if (this.objCZKEM.RegEvent(1, 32767))
{
this.WriteToFile("ZKEM device events registration started");
// [ Register your events here ]
this.objCZKEM.OnAttTransactionEx += new _IZKEMEvents_OnAttTransactionExEventHandler(zkemClient_OnAttTransactionEx);
this.WriteToFile("Done with ZKEM device events registration.");
}
You should not able to receive finger events from device.
I'm using camera2basic, when I change flash parameter on runtime it not working and load first parameter when app loading.
example : when I set auto-flash in hardcode it worked when I change it to Off in my app it not work and flash parameter is auto-flash yet.
I want to set flash parameter in application not hardcode. How can i do it?
**//Camera2BasicFragment.cs**
public void CaptureStillPicture()
{
try
{
var activity = Activity;
if (null == activity || null == mCameraDevice)
{
return;
}
// This is the CaptureRequest.Builder that we use to take a picture.
if (stillCaptureBuilder == null)
stillCaptureBuilder = mCameraDevice.CreateCaptureRequest(CameraTemplate.StillCapture);
stillCaptureBuilder.AddTarget(mImageReader.Surface);
SetFlash(stillCaptureBuilder);
// Orientation
int rotation = (int)activity.WindowManager.DefaultDisplay.Rotation;
stillCaptureBuilder.Set(CaptureRequest.JpegOrientation, GetOrientation(rotation));
mCaptureSession.StopRepeating();
mCaptureSession.Capture(stillCaptureBuilder.Build(), new CameraCaptureStillPictureSessionCallback(this), null);
}
catch (CameraAccessException e)
{
e.PrintStackTrace();
}
}
ControlAEMode AeFlashMode = ControlAEMode.Off;
public void SetFlash(CaptureRequest.Builder requestBuilder)
{
if (mFlashSupported)
{
requestBuilder.Set(CaptureRequest.ControlAeMode, (int)AeFlashMode);
}
}
-------------------------------
**//CameraCaptureSessionCallback.cs**
public override void OnConfigured(CameraCaptureSession session)
{
// The camera is already closed
if (null == owner.mCameraDevice)
{
return;
}
// When the session is ready, we start displaying the preview.
owner.mCaptureSession = session;
try
{
// Auto focus should be continuous for camera preview.
owner.SetFocus(owner.mPreviewRequestBuilder);
// Flash is automatically enabled when necessary.
owner.SetFlash(owner.mPreviewRequestBuilder);
// Finally, we start displaying the camera preview.
owner.mPreviewRequest = owner.mPreviewRequestBuilder.Build();
owner.mCaptureSession.SetRepeatingRequest(owner.mPreviewRequest,
owner.mCaptureCallback, owner.mBackgroundHandler);
}
catch (CameraAccessException e)
{
e.PrintStackTrace();
}
}
You can add following code to your CameraCaptureSessionCallback.cs
public void ISFlashOpenOrClose(bool isTorchOn)
{
owner.mCaptureSession = this.session;
if (isTorchOn)
{
owner.mPreviewRequestBuilder.Set(CaptureRequest.FlashMode, (int)ControlAEMode.On);
// owner.mPreviewRequestBuilder.Set(CaptureRequest.FlashMode, (int)FlashMode.Off);
// mPreviewSession.SetRepeatingRequest(mPreviewBuilder.build(), null, null);
owner.mPreviewRequest = owner.mPreviewRequestBuilder.Build();
owner.mCaptureSession.SetRepeatingRequest(owner.mPreviewRequest,
owner.mCaptureCallback, owner.mBackgroundHandler);
// isTorchOn = false;
}
else
{
owner.mPreviewRequestBuilder.Set(CaptureRequest.ControlAeMode, (int)ControlAEMode.Off);
owner.mPreviewRequest = owner.mPreviewRequestBuilder.Build();
owner.mCaptureSession.SetRepeatingRequest(owner.mPreviewRequest,
owner.mCaptureCallback, owner.mBackgroundHandler);
}
}
Here is all of code about CameraCaptureSessionCallback.cs
public class CameraCaptureSessionCallback : CameraCaptureSession.StateCallback
{
private readonly Camera2BasicFragment owner;
CameraCaptureSession session;
public CameraCaptureSessionCallback(Camera2BasicFragment owner)
{
if (owner == null)
throw new System.ArgumentNullException("owner");
this.owner = owner;
}
public override void OnConfigureFailed(CameraCaptureSession session)
{
owner.ShowToast("Failed");
}
private bool isTorchOn;
public override void OnConfigured(CameraCaptureSession session)
{
// The camera is already closed
if (null == owner.mCameraDevice)
{
return;
}
this.session = session;
// When the session is ready, we start displaying the preview.
owner.mCaptureSession = session;
try
{
// Auto focus should be continuous for camera preview.
owner.mPreviewRequestBuilder.Set(CaptureRequest.ControlAfMode, (int)ControlAFMode.ContinuousPicture);
// Flash is automatically enabled when necessary.
owner.SetAutoFlash(owner.mPreviewRequestBuilder);
// Flash is automatically enabled when necessary.
// owner.SetFlash(owner.mPreviewRequestBuilder);
// Finally, we start displaying the camera preview.
owner.mPreviewRequest = owner.mPreviewRequestBuilder.Build();
owner.mCaptureSession.SetRepeatingRequest(owner.mPreviewRequest,
owner.mCaptureCallback, owner.mBackgroundHandler);
}
catch (CameraAccessException e)
{
e.PrintStackTrace();
}
}
public void ISFlashOpenOrClose(bool isTorchOn)
{
owner.mCaptureSession = this.session;
if (isTorchOn)
{
owner.mPreviewRequestBuilder.Set(CaptureRequest.FlashMode, (int)ControlAEMode.On);
// owner.mPreviewRequestBuilder.Set(CaptureRequest.FlashMode, (int)FlashMode.Off);
// mPreviewSession.SetRepeatingRequest(mPreviewBuilder.build(), null, null);
owner.mPreviewRequest = owner.mPreviewRequestBuilder.Build();
owner.mCaptureSession.SetRepeatingRequest(owner.mPreviewRequest,
owner.mCaptureCallback, owner.mBackgroundHandler);
// isTorchOn = false;
}
else
{
owner.mPreviewRequestBuilder.Set(CaptureRequest.ControlAeMode, (int)ControlAEMode.Off);
owner.mPreviewRequest = owner.mPreviewRequestBuilder.Build();
owner.mCaptureSession.SetRepeatingRequest(owner.mPreviewRequest,
owner.mCaptureCallback, owner.mBackgroundHandler);
}
}
}
}
You can change it by ISFlashOpenOrClose method at runtime.
we have implement file chooser for web view. it works successfully when attachment is selected, but fails when cancelled without file specification. The file chooser just stops to react on click
any help is appreciated. Thanks
we use chrome client. it works fine if in all cases, file selection is listed. but even from the first file selection is cancelled, no longer file chooser will work. It is Xamarin.Android app based fully on webview
Our code is:
protected override void OnActivityResult(int requestCode, Result resultCode, Intent intent)
{
if (requestCode == FILECHOOSER_RESULTCODE)
{
if (null == _mUploadMessage)
return;
// Check that the response is a good one
if (resultCode == Result.Ok)
{
Android.Net.Uri[] results = null;
if (intent == null)
{
// If there is not data, then we may have taken a photo
if (mCameraPhotoPath != null)
{
results = new Android.Net.Uri[] { Android.Net.Uri.Parse(mCameraPhotoPath) };
}
}
else
{
if (intent.DataString != null)
{
results = new Android.Net.Uri[] { Android.Net.Uri.Parse(intent.DataString) };
}
}
_mUploadMessage.OnReceiveValue(results);
_mUploadMessage = null;
}
}
}
Chrome client:
var chrome = new FileChooserWebChromeClient((uploadMsg) =>
{
_mUploadMessage = uploadMsg;
mCameraPhotoPath = null;
Intent takePictureIntent = new Intent(Android.Provider.MediaStore.ActionImageCapture);
//Create the File where the photo should go
File photoFile = null;
try
{
string folder = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
photoFile = new File(folder, "image" + DateTime.Now.Millisecond + ".png");
takePictureIntent.PutExtra("PhotoPath", mCameraPhotoPath);
}
catch (IOException ex)
{
// Error occurred while creating the File
System.Console.WriteLine("" + ex.ToString());
}
// Continue only if the File was successfully created
if (photoFile != null)
{
mCameraPhotoPath = "file:" + photoFile.AbsolutePath;
takePictureIntent.PutExtra(Android.Provider.MediaStore.ExtraOutput,
Android.Net.Uri.FromFile(photoFile));
}
else
{
takePictureIntent = null;
}
Intent contentSelectionIntent = new Intent(Intent.ActionGetContent);
contentSelectionIntent.AddCategory(Intent.CategoryOpenable);
contentSelectionIntent.SetType("image/*");
Intent[] intentArray;
if (takePictureIntent != null)
{
intentArray = new Intent[] { takePictureIntent };
}
else
{
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ActionChooser);
chooserIntent.PutExtra(Intent.ExtraIntent, contentSelectionIntent);
chooserIntent.PutExtra(Intent.ExtraTitle, this.GetStringFromResource(Resource.String.chose_photo));
chooserIntent.PutExtra(Intent.ExtraInitialIntents, intentArray);
base.StartActivityForResult(chooserIntent, HarmonyAndroid.AndroidMainActivity.FILECHOOSER_RESULTCODE);
});
return chrome;
Part 2
class FileChooserWebChromeClient : WebChromeClient
{
Action<IValueCallback> callback;
public FileChooserWebChromeClient(Action<IValueCallback> callback)
{
this.callback = callback;
}
public override bool OnShowFileChooser(WebView webView, IValueCallback filePathCallback, FileChooserParams fileChooserParams)
{
callback(filePathCallback);
return true;
}
public override void OnCloseWindow(WebView window)
{
base.OnCloseWindow(window);
}
}
Part 3
webView.ImprovePerformance();
webView.SetWebViewClient(new HomeWebViewClient(customWebViewClientListener, clientId));
webView.SetWebChromeClient(chrome);
webView.Settings.JavaScriptEnabled = true;
webView.Settings.DomStorageEnabled = true;
webView.SetDownloadListener(new CustomDownloadListener(activity, customDownloadListener));
webView.AddJavascriptInterface(new JavaScriptToCSharpCommunication(activity, javaScriptToCSharpCommunicationListener), Constants.JS_CSHARP_COMMUNICATOR_NAME);
Try to give a null object to the uri callback, when the resultCode is not RESULT_OK.
add in your OnActivityResult method:
if (resultCode != Result.Ok)
{
_mUploadMessage.OnReceiveValue(null);
_mUploadMessage = null;
return;
}
I learning Xamarin Android, and i want to implement Google SignIn... But i'm not to be able to do that. I just need to use Client ID? i catch some examples in Internet but nothing works... Can someone give a example? or step by step how i can do this in Xamarin?
Thank you!
My Code:
using Android.App;
using Android.Widget;
using Android.OS;
using Android.Gms.Common.Apis;
using Android.Gms.Common;
using System;
using Android.Gms.Plus;
using Android.Content;
using Android.Runtime;
using Android.Gms.Plus.Model.People;
namespace LoginGoogle
{
[Activity(Label = "LoginGoogle", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity, GoogleApiClient.IConnectionCallbacks,
GoogleApiClient.IOnConnectionFailedListener
{
private GoogleApiClient googleApiClient;
private SignInButton btnGooglePlus;
private ConnectionResult connectionResult;
private bool intentProgress;
private bool signInClick;
private bool infoPopulated;
private TextView lblName;
private TextView lblTagLine;
private TextView lblBraggingRights;
private TextView lblGender;
private TextView lblRelationship;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
btnGooglePlus = FindViewById<SignInButton>(Resource.Id.btnGooglePlus);
btnGooglePlus.Click += btnGooglePlus_Click;
lblName = FindViewById<TextView>(Resource.Id.lblName);
lblTagLine = FindViewById<TextView>(Resource.Id.lblTagLine);
lblBraggingRights = FindViewById<TextView>(Resource.Id.lblBraggingRights);
lblGender = FindViewById<TextView>(Resource.Id.lblGender);
lblRelationship = FindViewById<TextView>(Resource.Id.lblRelationship);
GoogleApiClient.Builder builder = new GoogleApiClient.Builder(this);
builder.AddConnectionCallbacks(this);
builder.AddOnConnectionFailedListener(this);
builder.AddApi(PlusClass.API);
builder.AddScope(PlusClass.ScopePlusProfile);
builder.AddScope(PlusClass.ScopePlusLogin);
//Build our GoogleApiClient
googleApiClient = builder.Build();
}
void btnGooglePlus_Click(object sender, EventArgs e)
{
if (!googleApiClient.IsConnecting)
{
signInClick = true;
resolveSigInError();
}
}
private void resolveSigInError()
{
if (!googleApiClient.IsConnected)
{
//No need to resolve errors
return;
}
if (connectionResult.HasResolution)
{
try
{
intentProgress = true;
StartIntentSenderForResult(connectionResult.Resolution.IntentSender, 0, null,
0, 0, 0);
} catch (Android.Content.IntentSender.SendIntentException e)
{
intentProgress = false;
googleApiClient.Connect();
}
}
}
protected override void OnActivityResult(int requestCode,
[GeneratedEnum] Result resultCode, Intent data)
{
if(requestCode == 0)
{
if(resultCode != Result.Ok)
{
signInClick = false;
}
intentProgress = false;
if (googleApiClient.IsConnecting)
{
googleApiClient.Connect();
}
}
}
protected override void OnStart()
{
base.OnStart();
googleApiClient.Connect();
}
protected override void OnStop()
{
base.OnStop();
if (googleApiClient.IsConnected)
{
googleApiClient.Disconnect();
}
}
public void OnConnected(Bundle connectionHint)
{
//Successful login
signInClick = false;
if (PlusClass.PeopleApi.GetCurrentPerson(googleApiClient) != null)
{
IPerson plusUser = PlusClass.PeopleApi.GetCurrentPerson(googleApiClient);
if (plusUser.HasDisplayName)
{
lblName.Text += plusUser.DisplayName;
}
if (plusUser.HasTagline)
{
lblTagLine.Text += plusUser.Tagline;
}
if (plusUser.HasBraggingRights)
{
lblBraggingRights.Text += plusUser.BraggingRights;
}
{
switch (plusUser.RelationshipStatus)
{
case 0:
lblRelationship.Text += "Single";
break;
case 1:
lblRelationship.Text += "In a relationship";
break;
case 2:
lblRelationship.Text += "Engaged";
break;
case 3:
lblRelationship.Text += "Married";
break;
case 4:
lblRelationship.Text += "It's complicated";
break;
case 5:
lblRelationship.Text += "In an open relationship";
break;
case 6:
lblRelationship.Text += "Widowed";
break;
case 7:
lblRelationship.Text += "In a domestic partnership";
break;
case 8:
lblRelationship.Text += "In a civil union";
break;
default:
lblRelationship.Text += "Unknown";
break;
}
}
if (plusUser.HasGender)
{
switch (plusUser.Gender)
{
case 0:
lblGender.Text += "Male";
break;
case 1:
lblGender.Text += "Female";
break;
case 2:
lblGender.Text += "Other";
break;
default:
lblGender.Text += "Unknown";
break;
}
infoPopulated = true;
}
}
}
public void OnConnectionSuspended(int cause)
{
throw new NotImplementedException();
}
public void OnConnectionFailed(ConnectionResult result)
{
if (intentProgress)
{
//Store the ConnectionResult so that we can use it later when the user
//clicks 'sign in'
connectionResult = result;
if (signInClick)
{
//The user has already clicked 'signin' so we attempt to resolve all
//errors until the user is signed in
resolveSigInError();
}
}
}
}
}
enter code here
Please refer to the xamarin sample for google sign in. In this sample you do not need Client ID. For more google sign in information please check the google development document.
I catch some examples in Internet but nothing works...
I think you may not authorized the app.
Download the sample and make sure you've authorized the app in the Google Developers Console before use.
Authorized the app
Open the link.
Create your project name(whatever you write) and add the package name for it. In this sample the package name is com.xamarin.signinquickstart.
Get your SHA-1 please refer to this link.
Build and deploy the demo app and sign in with google account.
Screen shot:
But i'm not to be able to do that. I just need to use Client ID?
How to use the Client ID login on
According to google document. I think you can try to login with client id by:
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DefaultSignIn)
.RequestIdToken("YOUR_CLIENT_ID")
.RequestEmail()
.Build();
mGoogleApiClient = new GoogleApiClient.Builder (this)
.EnableAutoManage(mLoginFragment, failedHandler)
.AddApi (Auth.GOOGLE_SIGN_IN_API,gso)
.Build ()
I have a very similar problem like
Seekbar 'unhooking' from media player on orientation change, I get the correct output onSaveInstanceState and onCreateView of my progress bar.
I have implemented a media player in a fragment, on device rotation the song is is working fine but the seekbar progress is getting set to 0. I have done the following.
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
//NOTE: When navigating from one fragment to the next
// Bundle/savedInstanceState is always null
// Implemented it using Shared Preferences.
// Always call the superclass so it can save the view hierarchy state
savedInstanceState.putInt(SEEKBAR_PROGRESS, utils.getProgressPercentage(getCurrentPosition(), getDuration()));
Log.i(LOG_TAG, ">>>>> onSaveInstanceState : " + savedInstanceState.getInt(SEEKBAR_PROGRESS));
}
and onCreateView I am checking the savedInstanceState if it is not null and > 0 I am setting the seekbar progress, but it is not working, can someone please tell me why?
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
Bundle arguments = getArguments();
if (arguments != null) {
mUri = arguments.getParcelable(TrackPlayerActivityFragment.DETAIL_URI);
}
final View rootView = inflater.inflate(R.layout.fragment_track_player, container, false);
currentTimeTextView = (TextView) rootView.findViewById(R.id.current_time);
totalTimeView = (TextView) rootView.findViewById(R.id.total_time);
playButtonView = (ToggleButton) rootView.findViewById(R.id.media_play);
Cursor cur = getActivity().getContentResolver().query(mUri,null, null, null, null);
mTrackPlayerAdapter = new TrackPlayerAdapter(getActivity(), cur, 0, this);
mListView = (ListView) rootView.findViewById(R.id.listview_player);
mListView.setAdapter(mTrackPlayerAdapter);
//initialize the play button
playButtonView = (ToggleButton) rootView.findViewById(R.id.media_play);
if(savedInstanceState != null && savedInstanceState.getInt(SEEKBAR_PROGRESS) > 0) {
Log.i(LOG_TAG, ">>>>> onCreateView savedInstance : " + savedInstanceState.getInt(SEEKBAR_PROGRESS));
mSpotifyMusicSeekBar.setProgress(savedInstanceState.getInt(SEEKBAR_PROGRESS));
}
return rootView;
}
the play song is a runnable thread which is working till the completion even on device rotation.
public void playSong(String songUrl, String songTitle) {
Log.i(LOG_TAG, ">>>>> Song URL fragment - " + songUrl);
mSpotifyMusicService.setSongURL(songUrl);
mSpotifyMusicService.setSongTitle(songTitle);
mSpotifyMusicService.playSong();
View v = getActivity().findViewById(R.id.listview_player);
mSpotifyMusicSeekBar = (SeekBar) v.findViewById(R.id.musicSeekBar);
new Thread(new Runnable() {
#Override
public void run() {
try {
int progress = 0;
if(startingPoint > 0) {
progress = startingPoint;
}
while (progress <= 100) {
Thread.sleep(100);
final long totalDuration = getDuration();
progress = utils.getProgressPercentage(getCurrentPosition(), totalDuration);
//set the seekbar position, will be used in saved instance later on
mSpotifyMusicSeekBar.setProgress(progress);
}
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
}
}).start();
//implement the OnSeekBarChangeListener interface methods
mSpotifyMusicSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
Log.i(LOG_TAG, ">>>>> User Progress change" + progress);
mSpotifyMusicService.seek(progress);
} else {
updateMediaPlayerControls(
utils.milliSecondsToTimer(getCurrentPosition()),
utils.milliSecondsToTimer(getDuration())
);
//Log.i(LOG_TAG, ">>>>> System progress %age - " + progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
Log.i("onStartTrackingTouch - ",
"" + seekBar.getProgress());
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
Log.i("onStopTrackingTouch - ",
"" + seekBar.getProgress());
startingPoint = seekBar.getProgress();
mSpotifyMusicService.seek(startingPoint);
}
});
}
The way I solved it was to have the seekbar outside of the custom adapter and made it part of the fragment, and then used onSaveInstanceState to get the percentage and used it onCreateView after checking if the saved instance bundle is not null.