Can I know if the user turn Off or turn On the phone? [Xamarin Forms Android]

Luciano Nicolas SPONTON 1 Reputation point
2022-04-06T18:44:20+00:00

I need to know if in some moment the user turned off the phone and register it if that happens

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

1 answer

Sort by: Most helpful
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 77,256 Reputation points Microsoft Vendor
    2022-04-07T06:00:37.807+00:00

    Hello,

    Can I know if the user turn Off or turn On the phone?

    Yes. You can use **BroadCastReceiver**detect turn-on the Phone(Note: Please test following way in the physical device).

    Step 1 Create a BroadCastReceiver like following code in your Xamarin Forms Android project.

       [BroadcastReceiver(Enabled = true, Exported = false)]  
           [IntentFilter(new[] { "android.intent.action.BOOT_COMPLETED" })]  
           public class DeviceTrunOnReceiver : BroadcastReceiver  
           {  
               public override void OnReceive(Context context, Intent intent)  
               {  
                   Toast.MakeText(context, "Received intent!", ToastLength.Short).Show();  
               }  
           }  
    

    Step 2: Register this broadcast in AndroidManifest.xml, and add RECEIVE_BOOT_COMPLETED permission.

       <!-- ... -->  
       <application android:label="App4.Android" android:theme="@style/MainTheme">  
       		<receiver android:name=".DeviceTrunOnReceiver" android:enabled="true"   
                               android:permission="android.permission.RECEIVE_BOOT_COMPLETED">  
       			<intent-filter>  
       				<action android:name="android.intent.action.BOOT_COMPLETED" />  
       				<category android:name="android.intent.category.DEFAULT" />  
       			</intent-filter>  
       		</receiver>  
       	</application>  
       <!-- Don't forget about permission -->  
       <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>  
    

    Best Regards,
    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    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.


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.