How to request `REQUEST_IGNORE_BATTERY_OPTIMIZATIONS` permission in xamarin.essentials.permission?

mc 4,596 Reputation points
2021-07-08T09:35:51.517+00:00

how to request this permission? in android?

I want to connect to the internet while is in background running. but it failed.

after search I know I have to request this permission REQUEST_IGNORE_BATTERY_OPTIMIZATIONS how to request it?

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,363 questions
0 comments No comments
{count} votes

Accepted answer
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 76,551 Reputation points Microsoft Vendor
    2021-07-09T01:20:37.703+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!

    REQUEST_IGNORE_BATTERY_OPTIMIZATIONS is not a dangerous permission. You do not need, or want, any of that code(do not need request runtime permission). Here is Google's document.

    Permission an application must hold in order to use ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS. This is a normal permission: an app requesting it will always be granted the permission, without the user needing to approve or see it.

    Requesting REQUEST_IGNORE_BATTERY_OPTIMIZATIONS grants you the authority, from a security standpoint, to start an activity with an ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS Intent. Be sure to include your app's package as the Uri, Here is code

       private void Button1_Click(object sender, System.EventArgs e)  
               {  
                   
                   
                   Intent intent = new Intent();  
                   string packageName = this.PackageName;  
                   PowerManager pm = (PowerManager)this.GetSystemService(Context.PowerService);  
                   if (pm.IsIgnoringBatteryOptimizations(packageName))  
                       intent.SetAction(Android.Provider.Settings.ActionIgnoreBatteryOptimizationSettings);  
                   else  
                   {  
                       intent.SetAction(Android.Provider.Settings.ActionRequestIgnoreBatteryOptimizations);  
                       intent.SetData(Uri.Parse("package:" + packageName));  
                   }  
                   StartActivity(intent);  
                    
               }  
    

    Best Regards,

    Leon Lu


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    2 people found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.