How can I turn on the GPS if fhe GPS is turn off with XAMARIN in Android system?
My devices is not rooted.
You could invoke the corresponding system dialog.
Check if GPS is available, if not, navigate to system Settings to turn it on.
protected override void OnResume()
{
base.OnResume();
checkGPSEnabled();
}
private void checkGPSEnabled()
{
LocationManager manager = GetSystemService(Context.LocationService) as LocationManager;
if (!manager.IsProviderEnabled(LocationManager.GpsProvider))
{
Intent intent = new Intent(Android.Provider.Settings.ActionLocat‌​ionSourceSettings);
intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask);
StartActivity(intent);
}
}
Related
I'm trying to implement a mediaplayer in Xamarin.Forms, and to make a full screen function I've added a button which toggles the device between landscape and portrait. This works fine, but for some reason my android device doesn't trigger the DeviceDisplay.MainDisplayInfoChanged event until I actually flip the phone to match the new orientation.
So the app DOES change orientation, but doesn't fire the event until I physically flip my phone. This is happening on a physical device.
On iOS this works fine, so I'm a little confused.
My shared code on the video player page:
private void VideoControlView_ToggleFullScreen(object sender, EventArgs e)
{
if (_isFullScreen)
DependencyService.Get<IOrientationService>().SetOrientationToPortrait();
else
DependencyService.Get<IOrientationService>().SetOrientationToLandscape();
}
private async void DeviceDisplay_MainDisplayInfoChanged(object sender, DisplayInfoChangedEventArgs e)
{
if (AutoRotateDisabled)
return;
await DisplayVideoFullScreen(e.DisplayInfo.Orientation == DisplayOrientation.Landscape);
}
And my service to change the orientation for android:
public class OrientationService : IOrientationService
{
public void SetOrientationToLandscape()
{
((Activity)Forms.Context).RequestedOrientation = ScreenOrientation.Landscape;
}
public void SetOrientationToPortrait()
{
((Activity)Forms.Context).RequestedOrientation = ScreenOrientation.Portrait;
}
}
And for iOS just in case:
public class OrientationService : IOrientationService
{
private const string ORIENTATION_KEY = "orientation";
public void SetOrientationToLandscape()
{
SetOrientation(UIInterfaceOrientation.LandscapeRight);
}
public void SetOrientationToPortrait()
{
SetOrientation(UIInterfaceOrientation.Portrait);
}
public void SetOrientation(UIInterfaceOrientation orientation)
{
UIDevice.CurrentDevice.SetValueForKey(new NSNumber((int)orientation), new NSString(ORIENTATION_KEY));
}
}
To recap:
When I trigger my ToggleFullScreen event, my android device corrently enters landscape mode, but it does NOT trigger MainDisplayInfoChanged.
I have tested this on two different physical android devices with the same issue.
Any help is appreciated, thanks!
I'm coding a map tracking app on Xamarin forms. I'm using async tasks(with Device.StartTimer) to keep track of the location and another task for counter timer, but when I need to open another app, like a music app or whatever the app can't keep track while it is in the background. All tasks are stopping when I send the app in the background. When I start the app again, the tasks are not continued.
I just need to keep working while app running.
How could this be done?
You should use background task in this case, which is running outside the life cycle of the application. You can find more information here Xamarin background tasks
Due to Background Execution Limits in Android 8.0 or later, Normal service will be killed when in the Background.
In the Android 8.0 or later, I suggest you to achieve a foreground service to achieve that( receive higher priority than a "regular" service and a foreground service must provide a Notification that Android will display as long as the service is running).
You can use dependence service to open a foreground service in xamarin forms.
IService.cs create a interface for android to start service.
public interface IService
{
void Start();
}
Then achieved DependentService to start a Foreground Service.
DependentService.cs
[assembly: Xamarin.Forms.Dependency(typeof(DependentService))]
namespace TabGuesture.Droid
{
[Service]
public class DependentService : Service, IService
{
public void Start()
{
var intent = new Intent(Android.App.Application.Context,
typeof(DependentService));
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.O)
{
Android.App.Application.Context.StartForegroundService(intent);
}
else
{
Android.App.Application.Context.StartService(intent);
}
}
public override IBinder OnBind(Intent intent)
{
return null;
}
public const int SERVICE_RUNNING_NOTIFICATION_ID = 10000;
public override StartCommandResult OnStartCommand(Intent intent,
StartCommandFlags flags, int startId)
{
// From shared code or in your PCL
CreateNotificationChannel();
string messageBody = "service starting";
var notification = new Notification.Builder(this, "10111")
.SetContentTitle(Resources.GetString(Resource.String.app_name))
.SetContentText(messageBody)
.SetSmallIcon(Resource.Drawable.main)
.SetOngoing(true)
.Build();
StartForeground(SERVICE_RUNNING_NOTIFICATION_ID, notification);
//do you work
return StartCommandResult.Sticky;
}
void CreateNotificationChannel()
{
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{
// Notification channels are new in API 26 (and not a part of the
// support library). There is no need to create a notification
// channel on older versions of Android.
return;
}
var channelName = Resources.GetString(Resource.String.channel_name);
var channelDescription = GetString(Resource.String.channel_description);
var channel = new NotificationChannel("10111", channelName, NotificationImportance.Default)
{
Description = channelDescription
};
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.CreateNotificationChannel(channel);
}
}
}
Here is a similar thread about your needs.
How to create service doing work at period time in Xamarin.Forms?
For IOS background Tasks. you can refer to this thread
Using Xam.Plugins.Notifier for Local Notifications I am able to show a notification in Android. However, when I tap the notification, it reloads the application. Similar to how a remote notification would.
I handle the OnNewIntent() in the MainActivitiy.cs but it never fires.
How do I tap a Local Notification made by Xam.Plugins.Notifier so that OnNewIntent() fires and I can show a Shell item?
protected async override void OnNewIntent(Intent intent)
{
base.OnNewIntent(intent);
var title = intent.GetStringExtra("title");
if (title != null)
{
await Shell.Current.GoToAsync("Tools/Sales");
}
}
I have a SplashScreen Activity that actually starts the app:
How do I pass the Intent that starts the activity to the MainActitity from the Splash
[Activity(Theme = "#style/MyTheme.Splash", MainLauncher = true, NoHistory = true, LaunchMode = Android.Content.PM.LaunchMode.SingleTop)]
public class SplashActivity : AppCompatActivity
{
public override void OnCreate(Bundle savedInstanceState, PersistableBundle persistentState)
{
base.OnCreate(savedInstanceState, persistentState);
}
// Launches the startup task
protected override void OnResume()
{
base.OnResume();
StartActivity(new Intent(Application.Context, typeof(MainActivity)));
}
public override void OnBackPressed() { }
}
On the MainActivty class, set its LaunchMode to SingleTop so the OS will reuse the activity IF it is all already running vs. starting a new one:
[Activity(Label = "Your Xamarin Forms App", MainLauncher = true, Icon = "#mipmap/icon", LaunchMode = Android.Content.PM.LaunchMode.SingleTop)]
NOTE: There are two entry points into MainActvity for the notification intent
a. If the activity is already running, OnNewIntent will be called with the intent that you setup on the notification.
b. If your app is not running, MainActvity will be created as a normal startup but will include the intent from from the notification, so check the intent in the OnCreate.
Is there a custom circular activity indicator for UWP/ Win10 apps using Xamarin?
Is there a custom circular activity indicator for UWP/ Win10 apps using Xamarin?
You need to create your own View for UWP's ProgressRing:
Shared Project\MyProgressRing.cs:
public class MyProgressRing:View
{
}
UWP Project\MyProgressRingRenderer.cs:
[assembly:ExportRenderer(typeof(MyProgressRing),typeof(MyProgressRingRenderer))]
namespace CircularActivityDemo.UWP
{
public class MyProgressRingRenderer:ViewRenderer<MyProgressRing,ProgressRing>
{
ProgressRing ring;
protected override void OnElementChanged(ElementChangedEventArgs<MyProgressRing> e)
{
base.OnElementChanged(e);
if (Control == null)
{
ring = new ProgressRing();
ring.IsActive = true;
ring.Visibility = Windows.UI.Xaml.Visibility.Visible;
ring.IsEnabled = true;
SetNativeControl(ring);
}
}
}
}
Notes: I hardcoded the properties of ProgressRing Control. You can create DependencyProperties for your custom ProgressRing control.
In regards to Android auto how can i get a callback when user has plugged the device into a car ? I'd like to trigger an action to occur based on when the user actually connects to android auto, is it possible ?
You should be able to get USB connection broadcast. From there you will have to write your own logic to figure out Android Auto is in foreground.
(may need to introduce a slight delay in case android auto takes time to come up. Launcher seems to be part of google play service)
Here is how I did it in my services onCreate method (right form the example code):
IntentFilter filter = new IntentFilter(CarHelper.ACTION_MEDIA_STATUS);
mCarConnectionReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String connectionEvent = intent.getStringExtra(CarHelper.MEDIA_CONNECTION_STATUS);
mIsConnectedToCar = "media_connected".equals(connectionEvent);
LogHelper.i(TAG, "Connection event to Android Auto: ", connectionEvent,
" isConnectedToCar=", mIsConnectedToCar);
if(mIsConnectedToCar ) {
if(mService == null) {
bindMusicService();
if (mService != null) {
try {
initMediaMetaData();
toggleMediaPlaybackState(mService.isPlaying());
} catch (RemoteException e) {
Log.d(TAG, e.toString());
}
}
}
}
}
};
registerReceiver(mCarConnectionReceiver, filter);