Service not starting in Android Nexus Player? - nexus-player

I am developing app for Android Nexus Player(TV). I am trying to start a service on button click, but service is not starting. Am i missing anything? This service is working on android tablet perfectly. But not on Nexus Player( TV Box).
Code on Button click:
Intent serviceIntent = new Intent(this, MyService.class);
ComponentName componentName = startService(serviceIntent);
if(componentName == null)
showLogText("Service does not start");
Manifest declaration
<service android:name="com.hdmi.MyService"/>
onStartCommand was implemented like this
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
systemAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(acceptThread != null && acceptThread.isAlive())
acceptThread.cancel();
else {
acceptThread = new AcceptThread();
acceptThread.start();
Log.i("Server", "Starting");
}
return super.onStartCommand(intent, flags, startId);
}

Try this
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
systemAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(acceptThread != null && acceptThread.isAlive())
acceptThread.cancel();
else {
acceptThread = new AcceptThread();
acceptThread.start();
Log.i("Server", "Starting");
}
//return super.onStartCommand(intent, flags, startId);
return Service.START_STICKY;
}

Related

How to switch desktop to the next one like { win+ctrl+ ->} in win10? [duplicate]

I love that Windows 10 now has support for virtual desktops built in, but I have some features that I'd like to add/modify (e.g., force a window to appear on all desktops, launch the task view with a hotkey, have per-monitor desktops, etc.)
I have searched for applications and developer references to help me customize my desktops, but I have had no luck.
Where should I start? I am looking for Windows API functions (ideally, that are callable from a C# application) that will give me programmatic access to manipulate virtual desktops and the windows therein.
The Windows SDK Support Team Blog posted a C# demo to switch Desktops via IVirtualDesktopManager:
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("a5cd92ff-29be-454c-8d04-d82879fb3f1b")]
[System.Security.SuppressUnmanagedCodeSecurity]
public interface IVirtualDesktopManager
{
[PreserveSig]
int IsWindowOnCurrentVirtualDesktop(
[In] IntPtr TopLevelWindow,
[Out] out int OnCurrentDesktop
);
[PreserveSig]
int GetWindowDesktopId(
[In] IntPtr TopLevelWindow,
[Out] out Guid CurrentDesktop
);
[PreserveSig]
int MoveWindowToDesktop(
[In] IntPtr TopLevelWindow,
[MarshalAs(UnmanagedType.LPStruct)]
[In]Guid CurrentDesktop
);
}
[ComImport, Guid("aa509086-5ca9-4c25-8f95-589d3c07b48a")]
public class CVirtualDesktopManager
{
}
public class VirtualDesktopManager
{
public VirtualDesktopManager()
{
cmanager = new CVirtualDesktopManager();
manager = (IVirtualDesktopManager)cmanager;
}
~VirtualDesktopManager()
{
manager = null;
cmanager = null;
}
private CVirtualDesktopManager cmanager = null;
private IVirtualDesktopManager manager;
public bool IsWindowOnCurrentVirtualDesktop(IntPtr TopLevelWindow)
{
int result;
int hr;
if ((hr = manager.IsWindowOnCurrentVirtualDesktop(TopLevelWindow, out result)) != 0)
{
Marshal.ThrowExceptionForHR(hr);
}
return result != 0;
}
public Guid GetWindowDesktopId(IntPtr TopLevelWindow)
{
Guid result;
int hr;
if ((hr = manager.GetWindowDesktopId(TopLevelWindow, out result)) != 0)
{
Marshal.ThrowExceptionForHR(hr);
}
return result;
}
public void MoveWindowToDesktop(IntPtr TopLevelWindow, Guid CurrentDesktop)
{
int hr;
if ((hr = manager.MoveWindowToDesktop(TopLevelWindow, CurrentDesktop)) != 0)
{
Marshal.ThrowExceptionForHR(hr);
}
}
}
it includes the API to detect on which desktop the Window is shown and it can switch and move a Windows the a Desktop.
Programmatic access to the virtual desktop feature is very limited, as Microsoft has only exposed the IVirtualDesktopManager COM interface. It does provide two key functions:
IVirtualDesktopManager::GetWindowDesktopId allows you to retrieve the ID of a virtual desktop, based on a window that is already assigned to that desktop.
IVirtualDesktopManager::MoveWindowToDesktop allows you to move a window to a specific virtual desktop.
Unfortunately, this is not nearly enough to accomplish anything useful. I've written some C# code based on the reverse-engineering work done by NickoTin. I can't read much of the Russian in his blog post, but his C++ code was pretty accurate.
I do need to emphasize that this code is not something you want to commit to in a product. Microsoft always feels free to change undocumented APIs whenever they feel like it. And there is a runtime risk as well: this code does not necessarily interact well when the user is tinkering with the virtual desktops. Always keep in mind that a virtual desktop can appear and disappear at any time, completely out of sync with your code.
To use the code, create a new C# class library project. I'll first post ComInterop.cs, it contains the COM interface declarations that match NickoTin's C++ declarations:
using System;
using System.Runtime.InteropServices;
namespace Windows10Interop {
internal static class Guids {
public static readonly Guid CLSID_ImmersiveShell =
new Guid(0xC2F03A33, 0x21F5, 0x47FA, 0xB4, 0xBB, 0x15, 0x63, 0x62, 0xA2, 0xF2, 0x39);
public static readonly Guid CLSID_VirtualDesktopManagerInternal =
new Guid(0xC5E0CDCA, 0x7B6E, 0x41B2, 0x9F, 0xC4, 0xD9, 0x39, 0x75, 0xCC, 0x46, 0x7B);
public static readonly Guid CLSID_VirtualDesktopManager =
new Guid("AA509086-5CA9-4C25-8F95-589D3C07B48A");
public static readonly Guid IID_IVirtualDesktopManagerInternal =
new Guid("AF8DA486-95BB-4460-B3B7-6E7A6B2962B5");
public static readonly Guid IID_IVirtualDesktop =
new Guid("FF72FFDD-BE7E-43FC-9C03-AD81681E88E4");
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("FF72FFDD-BE7E-43FC-9C03-AD81681E88E4")]
internal interface IVirtualDesktop {
void notimpl1(); // void IsViewVisible(IApplicationView view, out int visible);
Guid GetId();
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("AF8DA486-95BB-4460-B3B7-6E7A6B2962B5")]
internal interface IVirtualDesktopManagerInternal {
int GetCount();
void notimpl1(); // void MoveViewToDesktop(IApplicationView view, IVirtualDesktop desktop);
void notimpl2(); // void CanViewMoveDesktops(IApplicationView view, out int itcan);
IVirtualDesktop GetCurrentDesktop();
void GetDesktops(out IObjectArray desktops);
[PreserveSig]
int GetAdjacentDesktop(IVirtualDesktop from, int direction, out IVirtualDesktop desktop);
void SwitchDesktop(IVirtualDesktop desktop);
IVirtualDesktop CreateDesktop();
void RemoveDesktop(IVirtualDesktop desktop, IVirtualDesktop fallback);
IVirtualDesktop FindDesktop(ref Guid desktopid);
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("a5cd92ff-29be-454c-8d04-d82879fb3f1b")]
internal interface IVirtualDesktopManager {
int IsWindowOnCurrentVirtualDesktop(IntPtr topLevelWindow);
Guid GetWindowDesktopId(IntPtr topLevelWindow);
void MoveWindowToDesktop(IntPtr topLevelWindow, ref Guid desktopId);
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("92CA9DCD-5622-4bba-A805-5E9F541BD8C9")]
internal interface IObjectArray {
void GetCount(out int count);
void GetAt(int index, ref Guid iid, [MarshalAs(UnmanagedType.Interface)]out object obj);
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("6D5140C1-7436-11CE-8034-00AA006009FA")]
internal interface IServiceProvider10 {
[return: MarshalAs(UnmanagedType.IUnknown)]
object QueryService(ref Guid service, ref Guid riid);
}
}
Next is Desktop.cs. It contains the friendly C# classes that you can use in your code:
using System;
using System.Runtime.InteropServices;
namespace Windows10Interop
{
public class Desktop {
public static int Count {
// Returns the number of desktops
get { return DesktopManager.Manager.GetCount(); }
}
public static Desktop Current {
// Returns current desktop
get { return new Desktop(DesktopManager.Manager.GetCurrentDesktop()); }
}
public static Desktop FromIndex(int index) {
// Create desktop object from index 0..Count-1
return new Desktop(DesktopManager.GetDesktop(index));
}
public static Desktop FromWindow(IntPtr hWnd) {
// Creates desktop object on which window <hWnd> is displayed
Guid id = DesktopManager.WManager.GetWindowDesktopId(hWnd);
return new Desktop(DesktopManager.Manager.FindDesktop(ref id));
}
public static Desktop Create() {
// Create a new desktop
return new Desktop(DesktopManager.Manager.CreateDesktop());
}
public void Remove(Desktop fallback = null) {
// Destroy desktop and switch to <fallback>
var back = fallback == null ? DesktopManager.GetDesktop(0) : fallback.itf;
DesktopManager.Manager.RemoveDesktop(itf, back);
}
public bool IsVisible {
// Returns <true> if this desktop is the current displayed one
get { return object.ReferenceEquals(itf, DesktopManager.Manager.GetCurrentDesktop()); }
}
public void MakeVisible() {
// Make this desktop visible
DesktopManager.Manager.SwitchDesktop(itf);
}
public Desktop Left {
// Returns desktop at the left of this one, null if none
get {
IVirtualDesktop desktop;
int hr = DesktopManager.Manager.GetAdjacentDesktop(itf, 3, out desktop);
if (hr == 0) return new Desktop(desktop);
else return null;
}
}
public Desktop Right {
// Returns desktop at the right of this one, null if none
get {
IVirtualDesktop desktop;
int hr = DesktopManager.Manager.GetAdjacentDesktop(itf, 4, out desktop);
if (hr == 0) return new Desktop(desktop);
else return null;
}
}
public void MoveWindow(IntPtr handle) {
// Move window <handle> to this desktop
DesktopManager.WManager.MoveWindowToDesktop(handle, itf.GetId());
}
public bool HasWindow(IntPtr handle) {
// Returns true if window <handle> is on this desktop
return itf.GetId() == DesktopManager.WManager.GetWindowDesktopId(handle);
}
public override int GetHashCode() {
return itf.GetHashCode();
}
public override bool Equals(object obj) {
var desk = obj as Desktop;
return desk != null && object.ReferenceEquals(this.itf, desk.itf);
}
private IVirtualDesktop itf;
private Desktop(IVirtualDesktop itf) { this.itf = itf; }
}
internal static class DesktopManager {
static DesktopManager() {
var shell = (IServiceProvider10)Activator.CreateInstance(Type.GetTypeFromCLSID(Guids.CLSID_ImmersiveShell));
Manager = (IVirtualDesktopManagerInternal)shell.QueryService(Guids.CLSID_VirtualDesktopManagerInternal, Guids.IID_IVirtualDesktopManagerInternal);
WManager = (IVirtualDesktopManager)Activator.CreateInstance(Type.GetTypeFromCLSID(Guids.CLSID_VirtualDesktopManager));
}
internal static IVirtualDesktop GetDesktop(int index) {
int count = Manager.GetCount();
if (index < 0 || index >= count) throw new ArgumentOutOfRangeException("index");
IObjectArray desktops;
Manager.GetDesktops(out desktops);
object objdesk;
desktops.GetAt(index, Guids.IID_IVirtualDesktop, out objdesk);
Marshal.ReleaseComObject(desktops);
return (IVirtualDesktop)objdesk;
}
internal static IVirtualDesktopManagerInternal Manager;
internal static IVirtualDesktopManager WManager;
}
}
And finally a little test WinForms project that I used to test the code. Just drop 4 buttons on a form and name them buttonLeft/Right/Create/Destroy:
using Windows10Interop;
using System.Diagnostics;
...
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void buttonRight_Click(object sender, EventArgs e) {
var curr = Desktop.FromWindow(this.Handle);
Debug.Assert(curr.Equals(Desktop.Current));
var right = curr.Right;
if (right == null) right = Desktop.FromIndex(0);
if (right != null) {
right.MoveWindow(this.Handle);
right.MakeVisible();
this.BringToFront();
Debug.Assert(right.IsVisible);
}
}
private void buttonLeft_Click(object sender, EventArgs e) {
var curr = Desktop.FromWindow(this.Handle);
Debug.Assert(curr.Equals(Desktop.Current));
var left = curr.Left;
if (left == null) left = Desktop.FromIndex(Desktop.Count - 1);
if (left != null) {
left.MoveWindow(this.Handle);
left.MakeVisible();
this.BringToFront();
Debug.Assert(left.IsVisible);
}
}
private void buttonCreate_Click(object sender, EventArgs e) {
var desk = Desktop.Create();
desk.MoveWindow(this.Handle);
desk.MakeVisible();
Debug.Assert(desk.IsVisible);
Debug.Assert(desk.Equals(Desktop.Current));
}
private void buttonDestroy_Click(object sender, EventArgs e) {
var curr = Desktop.FromWindow(this.Handle);
var next = curr.Left;
if (next == null) next = curr.Right;
if (next != null && next != curr) {
next.MoveWindow(this.Handle);
curr.Remove(next);
Debug.Assert(next.IsVisible);
}
}
}
The only real quirk I noticed while testing this is that moving a window from one desktop to another can move it to the bottom of the Z-order when you first switch the desktop, then move the window. No such problem if you do it the other way around.
There is this guy that made a application to map keyboard shorcut to move a window between virtual desktop.
https://github.com/Grabacr07/SylphyHorn
(I use it every day )
He has a blog where he explain what he did
http://grabacr.net/archives/5701 ( you can use google translate it is in japanese)
He in fact used the same api mantionned in the Alberto Tostado response.
http://www.cyberforum.ru/blogs/105416/blog3671.html
and the api can be found on his github https://github.com/Grabacr07/VirtualDesktop
The api is really simple to use BUT it seems impossible to move a window from another process.
public static bool MoveToDesktop(IntPtr hWnd, VirtualDesktop virtualDesktop)
{
ThrowIfNotSupported();
int processId;
NativeMethods.GetWindowThreadProcessId(hWnd, out processId);
if (Process.GetCurrentProcess().Id == processId) // THAT LINE
{
var guid = virtualDesktop.Id;
VirtualDesktop.ComManager.MoveWindowToDesktop(hWnd, ref guid);
return true;
}
return false;
}
To workaround this problem they made another implementation that they use alongside the one in the russian blog
if (VirtualDesktopHelper.MoveToDesktop(hWnd, right) //<- the one in the russian blog
|| this.helper.MoveWindowToDesktop(hWnd, right.Id)) <- the second implementation
The second implementation can be found here: https://github.com/tmyt/VDMHelper
This one can move a window from another process to another desktop. BUT it is buggy right now. For exemple when i try to move some window like google chrome it crash.
So this is the result of my research. I m rigth now trying to make a StickyWindow feature with these api.
I fear that all about "Virtual desktops" in Windows 10 is undocumented, but in a Russian page I've seen documented the interfaces. I don't speak Russian but seems that they have used reversed engineering. Anyway, the code is very clear (Thanks to them!).
Keep an eye here:
http://www.cyberforum.ru/blogs/105416/blog3671.html
I've been trying to see if the old API's CreateDesktop, OpenDesktop, etc... is linked to the new Virtual-Desktops, but no way...
The interfaces work with the final production release of Windows 10 (2015-05-08), but you shouldn't use them in a real wide distributed application until Microsoft documents them. Too much risk.
Regards.

Get and Display path of Chosen photo from gallery in Xamarin forms

I am using a Dependency service to pick a photo from the gallery. and I want to show the path when the user selects an image from their phone in a Label.
I have read too many logs but not getting the proper results.
I want it like this:
Now the selected image is displayed properly but what I don't get is how to display the path of the selected image.
Please suggest me how to do it for both android and ios.
Note: I'm using Dependency service for it so I don't want third-party plugins.
I hope I will get a better solution for this.
Thanks in advance.
Creating the interface in forms
namespace xxx
{
public interface IPhotoPickerService
{
Task<Dictionary<string,Stream>> GetImageStreamAsync();
}
}
in iOS
[assembly: Dependency (typeof (PhotoPickerService))]
namespace xxx.iOS
{
public class PhotoPickerService : IPhotoPickerService
{
TaskCompletionSource<Dictionary<string, Stream>> taskCompletionSource;
UIImagePickerController imagePicker;
Task<Dictionary<string, Stream>> IPhotoPickerService.GetImageStreamAsync()
{
// Create and define UIImagePickerController
imagePicker = new UIImagePickerController
{
SourceType = UIImagePickerControllerSourceType.PhotoLibrary,
MediaTypes = UIImagePickerController.AvailableMediaTypes(UIImagePickerControllerSourceType.PhotoLibrary)
};
// Set event handlers
imagePicker.FinishedPickingMedia += OnImagePickerFinishedPickingMedia;
imagePicker.Canceled += OnImagePickerCancelled;
// Present UIImagePickerController;
UIWindow window = UIApplication.SharedApplication.KeyWindow;
var viewController = window.RootViewController;
viewController.PresentModalViewController(imagePicker, true);
// Return Task object
taskCompletionSource = new TaskCompletionSource<Dictionary<string, Stream>>();
return taskCompletionSource.Task;
}
void OnImagePickerFinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs args)
{
UIImage image = args.EditedImage ?? args.OriginalImage;
if (image != null)
{
// Convert UIImage to .NET Stream object
NSData data;
if (args.ReferenceUrl.PathExtension.Equals("PNG") || args.ReferenceUrl.PathExtension.Equals("png"))
{
data = image.AsPNG();
}
else
{
data = image.AsJPEG(1);
}
Stream stream = data.AsStream();
UnregisterEventHandlers();
Dictionary<string, Stream> dic = new Dictionary<string, Stream>();
dic.Add(args.ImageUrl.ToString(), stream);
// Set the Stream as the completion of the Task
taskCompletionSource.SetResult(dic);
}
else
{
UnregisterEventHandlers();
taskCompletionSource.SetResult(null);
}
imagePicker.DismissModalViewController(true);
}
void OnImagePickerCancelled(object sender, EventArgs args)
{
UnregisterEventHandlers();
taskCompletionSource.SetResult(null);
imagePicker.DismissModalViewController(true);
}
void UnregisterEventHandlers()
{
imagePicker.FinishedPickingMedia -= OnImagePickerFinishedPickingMedia;
imagePicker.Canceled -= OnImagePickerCancelled;
}
}
}
in Android
in MainActivity
public class MainActivity : FormsAppCompatActivity
{
...
// Field, property, and method for Picture Picker
public static readonly int PickImageId = 1000;
public TaskCompletionSource<Dictionary<string,Stream>> PickImageTaskCompletionSource { set; get; }
protected override void OnActivityResult(int requestCode, Result resultCode, Intent intent)
{
base.OnActivityResult(requestCode, resultCode, intent);
if (requestCode == PickImageId)
{
if ((resultCode == Result.Ok) && (intent != null))
{
Android.Net.Uri uri = intent.Data;
Stream stream = ContentResolver.OpenInputStream(uri);
Dictionary<string, Stream> dic = new Dictionary<string, Stream>();
dic.Add(uri.ToString(), stream);
// Set the Stream as the completion of the Task
PickImageTaskCompletionSource.SetResult(dic);
}
else
{
PickImageTaskCompletionSource.SetResult(null);
}
}
}
}
[assembly: Dependency(typeof(PhotoPickerService))]
namespace xxx.Droid
{
public class PhotoPickerService : IPhotoPickerService
{
public Task<Dictionary<string,Stream>> GetImageStreamAsync()
{
// Define the Intent for getting images
Intent intent = new Intent();
intent.SetType("image/*");
intent.SetAction(Intent.ActionGetContent);
// Start the picture-picker activity (resumes in MainActivity.cs)
MainActivity.Instance.StartActivityForResult(
Intent.CreateChooser(intent, "Select Picture"),
MainActivity.PickImageId);
// Save the TaskCompletionSource object as a MainActivity property
MainActivity.Instance.PickImageTaskCompletionSource = new TaskCompletionSource<Dictionary<string,Stream>>();
// Return Task object
return MainActivity.Instance.PickImageTaskCompletionSource.Task;
}
}
}
invoke it
Dictionary<string, Stream> dic = await DependencyService.Get<IPhotoPickerService>().GetImageStreamAsync();
Stream stream;
string path;
foreach ( KeyValuePair<string, Stream> currentImage in dic )
{
stream = currentImage.Value;
path = currentImage.Key;
label.Text = path;
if (stream != null)
{
image.Source = ImageSource.FromStream(() => stream);
}
}
Update
If you want to get the path , you could invoke
Dictionary<string, Stream> dic = new Dictionary<string, Stream>();
dic.Add(uri.Path, stream);

Xamarin Android Google Plus SignIn

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 ()

Xamarin Android Receive and Send SMS more than 160 characters

I'm writting sms application, which get from server by restapi number and message where to send and also receive sms from receipent. I have issue when received sms has more than 160 characters. And issue is when I have more than 160 characters to send by SMS.
Receive sms code:
public override void OnReceive(Context context, Intent intent)
{
if (intent.HasExtra("pdus"))
{
var smsArray = (Java.Lang.Object[])intent.Extras.Get("pdus");
foreach(var item in smsArray)
{
var sms = SmsMessage.CreateFromPdu((byte[])item);
SendReceivedStatus(sms.OriginatingAddress, sms.MessageBody);
}
}
}
SendReceivedStatus(sms.OriginatingAddress, sms.MessageBody);
It's a my method that convert to json receipentNumber and message.
Now my send sms code:
var sent = PendingIntent.GetBroadcast(Application.Context, 0, new Intent("SMS_SENT"), 0);
SmsManager.Default.SendTextMessage(responseModel.receipent, null, responseModel.message, sent, null);
protected override void OnResume()
{
base.OnResume();
var smsSentReceiver = new SMSSentReceiver();
RegisterReceiver(smsSentReceiver, new IntentFilter("SMS_SENT"));
}
public override void OnReceive(Context context, Intent intent)
{
switch ((int)ResultCode)
{
case (int)Result.Ok:
SenderActivity.resultsms = true;
SendStatus();
break;
case (int)SmsResultError.GenericFailure:
SenderActivity.resultsms = false;
SendStatus();
break;
case (int)SmsResultError.NoService:
SenderActivity.resultsms = false;
SendStatus();
break;
case (int)SmsResultError.NullPdu:
SenderActivity.resultsms = false;
SendStatus();
break;
case (int)SmsResultError.RadioOff:
SenderActivity.resultsms = false;
SendStatus();
break;
}
}
How to pack these messages?
Since SmsMessage.CreateFromPdu((byte[])) is deprecated since Android API level 19, here I also provide method to receive message more than 160 characters after KitKat version, here is my demo:
[BroadcastReceiver(Enabled = true, Label = "SMS Receiver")]
[IntentFilter(new[] { "android.provider.Telephony.SMS_RECEIVED" })]
public class SMSReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
Bundle bundle = intent.Extras;
if (bundle != null)
{
if (Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat)
{
SmsMessage[] msgs = Telephony.Sms.Intents.GetMessagesFromIntent(intent);
var smstext = new StringBuilder();
foreach (var msg in msgs)
{
smstext.Append(msg.DisplayMessageBody.ToString());
}
Console.WriteLine(smstext.ToString());//output the received sms
}
else
{
var smsArray = (Java.Lang.Object[])bundle.Get("pdus");
SmsMessage[] messages = new SmsMessage[smsArray.Length];
for (int i = 0; i < smsArray.Length; i++)
{
messages[i] = SmsMessage.CreateFromPdu((byte[])smsArray[i]);
}
StringBuilder content = new StringBuilder();
if (messages.Length > 0)
{
foreach (var message in messages)
{
content.Append(message.DisplayMessageBody.ToString());
}
}
Console.WriteLine(content.ToString());//output the received sms
}
}
Toast.MakeText(context, "Received intent!", ToastLength.Short).Show();
}
}
I've tested my demo on Android 6.0 device and it works fine, I now can't find a Android 4.0 device for testing, but I think the method should work here. Any problem about this issue, please leave a comment.

Using visual studio 2013 built in message box via DTE object

I'm developing visual studio project template.
During the template installation I perform some long operations that I want to let the user know about.
I've already seen the DTE statusbar progress method but I prefer output the message in visual studio built in message box.
Is it possible?
Ok, I think I got it.
The assemblies:
Microsoft.VisualStudio.OLE.Interop
Microsoft.VisualStudio.Shell.12.0
Microsoft.VisualStudio.Shell.Interop.10.0
In the using statements:
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
The code:
private IVsThreadedWaitDialog2 _progressDialog = null;
private void StartProgressDialog(string operation, string statusBarText, int total)
{
if (_progressDialog == null)
{
IOleServiceProvider oleServiceProvider = _dte as IOleServiceProvider;
IVsThreadedWaitDialogFactory dialogFactory = new ServiceProvider(oleServiceProvider).GetService(
typeof(SVsThreadedWaitDialogFactory)) as IVsThreadedWaitDialogFactory;
IVsThreadedWaitDialog2 dialog = null;
if (dialogFactory != null)
{
dialogFactory.CreateInstance(out dialog);
_progressDialog = dialog;
}
}
if(_progressDialog != null)
{
_progressDialog.StartWaitDialogWithPercentageProgress("Wait Dialogue", operation, null, null, statusBarText, false, 0, total, 0);
}
}
private void TerminatePreogressDialog()
{
if (_progressDialog != null)
{
int canceled;
_progressDialog.EndWaitDialog(out canceled);
}
}
private void UpdateLongOperationMessage(string operation, string progressMessage, int step, int total)
{
if (_progressDialog != null)
{
bool canceled;
_progressDialog.UpdateProgress(operation, progressMessage, progressMessage, step, total, true, out canceled);
}
}

Resources