question

00014943 avatar image
0 Votes"
00014943 asked LeonLu-MSFT edited

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

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

dotnet-xamarin
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

LeonLu-MSFT avatar image
0 Votes"
LeonLu-MSFT answered LeonLu-MSFT edited

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.



· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

@00014943 May I know if you have got any chance to check my answer? I am glad to help if you have any other questions

0 Votes 0 ·