Table of Contents
- 1. Description
- 2. Realization
-
- 2.1 Effect
- 2.2 Principle Description
- 2.3 Specific code implementation
-
- 2.3.1 layout
- 2.3.3 Broadcast Receiver
- 2.3.3 Activity that makes a phone call
- 2.3.4 Main Interface Activity
- 3. Code download
- 4. Reference materials
1. Description
I just compiled two articles in the past few days: Xamarin.Android implements the function of making calls and Xamarin.Android implements the function of alarm clock. Just like the story of the apple-pen, so two articles have created a new one: the scheduled call function
This article is purely a technical exchange, please use it correctly.
2. Concrete implementation
2.1 Effect
2.2 Principle Description
First define a broadcast receiver to monitor the status of the alarm clock. When the alarm clock is on, the broadcast receiver receives the information, and then starts the activity
(PhoneActivity
in this article) to make a call, in PhoneActivity
Enable the phone listener (PhoneStateListener
), when the phone is found to be connected, perform the following actions: close the phone, close PhoneActivity
. Then continue to cycle above.
2.3 Specific code implementation
2.3.1 layout
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <EditText android:id="@ + id/phoneNumber" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="28dp" android:textSize="25dp" android:textStyle="bold" android:ems="10" android:hint="Set the phone number to call" android:inputType="phone" /> <EditText android:id="@ + id/timeTxt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="28dp" android:textSize="25dp" android:textStyle="bold" android:layout_below="@ + id/phoneNumber" android:ems="10" android:hint="Set the current time in seconds and start" android:inputType="numberDecimal" /> <EditText android:id="@ + id/initTime" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="28dp" android:textSize="25dp" android:textStyle="bold" android:layout_below="@ + id/timeTxt" android:ems="10" android:hint="Set interval (please >=60) seconds" android:inputType="numberDecimal" /> <Button android:id="@ + id/startBtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="60dp" android:layout_marginTop="240dp" android:text="Start" /> <androidx.coordinatorlayout.widget.CoordinatorLayout android:minWidth="25px" android:minHeight="25px" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:id="@ + id/coordinatorLayout1" /> </RelativeLayout>
2.3.3 Broadcast Receiver
using Android.Content; using Android. Widget; namespace AlarmDemo {<!-- --> [Broadcast Receiver] public class MyReceiver : BroadcastReceiver {<!-- --> public override void OnReceive(Context context, Intent intent) {<!-- --> Intent phoneIntent = new Intent(context, typeof(PhoneActivity)); phoneIntent.AddFlags(ActivityFlags.NewTask); //Open a new thread to host the activity phoneIntent.PutExtra("phoneNumber", intent.GetStringExtra("phoneNumber")); context.StartActivity(phoneIntent); //Start a new activity and make a phone call } } }
2.3.3 Activity for making phone calls
Complete phone calls and hang up
using Android. App; using Android. Content; using Android. OS; using Android. Telephony; using Android. Widget; using System; using System. Threading; namespace AlarmDemo {<!-- --> [Activity(Label = "PhoneActivity")] public class PhoneActivity : Activity {<!-- --> private Android.Telecom.TelecomManager telecomManager = null; protected override void OnCreate(Bundle savedInstanceState) {<!-- --> base.OnCreate(savedInstanceState); //Create your application here //parameter initialization //Turn off the manager of the phone telecomManager = (Android.Telecom.TelecomManager)GetSystemService(Context.TelecomService); //Call the system method (monitor phone status) MyPhoneStateListener phoneStateListener = new MyPhoneStateListener(telecomManager, this); TelephonyManager telephonyManager = (TelephonyManager)GetSystemService(Context.TelephonyService); telephonyManager.Listen(phoneStateListener, PhoneStateListenerFlags.CallState); try {<!-- --> var intent = new Intent(Intent. ActionCall); intent.SetData(Android.Net.Uri.Parse("tel:" + Intent.GetStringExtra("phoneNumber"))); StartActivity(intent); } catch(Exception ex) {<!-- --> Toast.MakeText(this, ex.Message, ToastLength.Long).Show(); } } } public class MyPhoneStateListener : PhoneStateListener {<!-- --> private Android.Telecom.TelecomManager v_telecomManager; private PhoneActivity v_phoneActivity; public MyPhoneStateListener(Android.Telecom.TelecomManager v_telecomManager, PhoneActivity phoneActivity) {<!-- --> this.v_telecomManager = v_telecomManager; this.v_phoneActivity = phoneActivity; } public override void OnCallStateChanged(CallState state, string incomingNumber) {<!-- --> base.OnCallStateChanged(state, incomingNumber); switch (state) {<!-- --> case CallState.Offhook: //If the call is connected, hang up Thread. Sleep(3000); this.v_telecomManager.EndCall(); //Close the phone v_phoneActivity.Finish(); break; default: break; } } } }
2.3.4 Main Interface Activity
Mainly complete the permission judgment and start the alarm clock
using Android; using Android. App; using Android. Content; using Android.Content.PM; using Android. OS; using Android. Runtime; using Android. Views; using Android. Widget; using AndroidX.AppCompat.App; using AndroidX. CoordinatorLayout. Widget; using AndroidX. Core. App; using Google.Android.Material.Snackbar; using Java. Lang; using System; namespace AlarmDemo {<!-- --> [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)] public class MainActivity : AppCompatActivity {<!-- --> //DECLARE WIDGETS private Button startBtn; private EditText timeTxt, internalTxt, phoneNumberTxt; private CoordinatorLayout coordinatorLayout; private const int REQUEST_CALL = 1, STOP_CALL=2, ALL_ALLOW=3; protected override void OnCreate(Bundle savedInstanceState) {<!-- --> base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); // Set our view from the "main" layout resource SetContentView(Resource. Layout. activity_main); this.initializeViews(); } public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults) {<!-- --> Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults); if(requestCode==ALL_ALLOW) {<!-- --> if ((grantResults. Length == 2) & amp; & amp; (grantResults[0] == Permission. Granted) & amp; & amp; (grantResults[1] == Permission. Granted)) {<!-- --> go();//Call the specific method of making a call } else {<!-- --> Snackbar.Make(coordinatorLayout, "The user failed to grant permission to make calls", Snackbar.LengthShort).Show(); } } else {<!-- --> base.OnRequestPermissionsResult(requestCode, permissions, grantResults); } } private void initializeViews() {<!-- --> timeTxt = FindViewById<EditText>(Resource.Id.timeTxt); internalTxt = FindViewById<EditText>(Resource.Id.initTime); phoneNumberTxt = FindViewById<EditText>(Resource.Id.phoneNumber); startBtn = FindViewById<Button>(Resource.Id.startBtn); coordinatorLayout= FindViewById<CoordinatorLayout>(Resource.Id.coordinatorLayout1); startBtn.Click += startBtn_Click; } void startBtn_Click(object sender, EventArgs e) {<!-- --> //checkPermission(this, "Is the permission to make calls granted?", Manifest.Permission.CallPhone, REQUEST_CALL); checkPermission(); } private void go() {<!-- --> //Get interface settings int time = Convert.ToInt32(timeTxt.Text); int intervalTime = Convert.ToInt32(internalTxt.Text); string phoneNulber = phoneNumberTxt.Text; Intent i = new Intent(this, typeof(MyReceiver)); i.PutExtra("phoneNumber", phoneNulber); PendingIntent pi = PendingIntent. GetBroadcast(this, 0, i, 0); AlarmManager alarmManager = (AlarmManager)GetSystemService(AlarmService); //set the interval alarmManager.SetRepeating(AlarmType.RtcWakeup, JavaSystem.CurrentTimeMillis() + (time * 1000), intervalTime*1000, pi); Toast.MakeText(this, "The alarm clock will start after " + time + " seconds! And run repeatedly at intervals of " + intervalTime + " seconds!", ToastLength.Short).Show(); } private void checkPermission(Activity activity, string tips, string permission, int permission_code) {<!-- --> if (ActivityCompat. ShouldShowRequestPermissionRationale(activity, permission)) {<!-- --> var requiredPermissions = new System. String[] {<!-- --> permission }; Snackbar. Make(coordinatorLayout, tips, Snackbar. LengthIndefinite) .SetAction("Agree to authorize", new Action<View>(delegate (View obj) {<!-- --> ActivityCompat.RequestPermissions(this, requiredPermissions, permission_code); }) ).Show(); } else {<!-- --> var requiredPermissions = new System. String[] {<!-- --> permission }; ActivityCompat.RequestPermissions(this, requiredPermissions, permission_code); } } private void checkPermission() {<!-- --> if (ActivityCompat. ShouldShowRequestPermissionRationale(this, Manifest. Permission. CallPhone)) {<!-- --> var requiredPermissions = new System.String[] {<!-- --> Manifest.Permission.CallPhone }; Snackbar.Make(coordinatorLayout, "Is the permission to make calls granted?", Snackbar.LengthIndefinite) .SetAction("Agree to authorize", new Action<View>(delegate (View obj) {<!-- --> ActivityCompat. RequestPermissions(this, requiredPermissions, REQUEST_CALL); }) ).Show(); }else if (ActivityCompat.ShouldShowRequestPermissionRationale(this, Manifest.Permission.AnswerPhoneCalls)) {<!-- --> var requiredPermissions = new System.String[] {<!-- --> Manifest.Permission.AnswerPhoneCalls }; Snackbar.Make(coordinatorLayout, "Is the permission to make calls granted?", Snackbar.LengthIndefinite) .SetAction("Agree to authorize", new Action<View>(delegate (View obj) {<!-- --> ActivityCompat. RequestPermissions(this, requiredPermissions, STOP_CALL); }) ).Show(); } else {<!-- --> var requiredPermissions = new System.String[] {<!-- --> Manifest.Permission.CallPhone, Manifest.Permission.AnswerPhoneCalls }; ActivityCompat. RequestPermissions(this, requiredPermissions, ALL_ALLOW); } } } }
3. Code download
code download
4. Reference
1. Mainly refer to this article
2. How does this monitor the phone status
3. Official website materials of the broadcast receiver
4. How to stop the phone through the program