using System; using Android.App; using Android.Content; using Android.Net; using Android.Telephony; namespace Shared { public class MyBroadcastReceive : BroadcastReceiver { /// /// 响铃事件 /// public static Action ActioRinging; /// /// 电话挂断事件 /// public static Action ActionIdle; /// /// 是否在通话中 /// public static bool IsCalling; public override void OnReceive (Context context, Intent intent) { //return; System.Console.WriteLine ($"接收到广播事:{intent.Action}"); switch (intent.Action) { // 如果是拨打电话 case "android.intent.action.NEW_OUTGOING_CALL": { System.Console.WriteLine ($"播打电话->{intent.GetStringExtra (Intent.ExtraPhoneNumber)}"); } break; //被打电话 case "android.intent.action.PHONE_STATE": { // 如果是来电 var tManager = (TelephonyManager)context.GetSystemService (Service.TelephonyService); System.Console.WriteLine ($"通话状态->{tManager.CallState}"); switch (tManager.CallState) { //响铃 case CallState.Ringing: IsCalling = true; var mIncomingNumber = intent.GetStringExtra ("incoming_number"); ActioRinging?.Invoke (); break; //接通 case CallState.Offhook: IsCalling = true; ActioRinging?.Invoke (); break; //挂断电话 case CallState.Idle: IsCalling = false; ActionIdle?.Invoke (); break; } break; } case "android.net.conn.CONNECTIVITY_CHANGE": if (intent.Extras != null) { var ni = (NetworkInfo)intent.Extras.Get (ConnectivityManager.ExtraNetworkInfo); if (ni != null && ni.GetState () == NetworkInfo.State.Connected) { //可以再这里进行一些网络突然断开未完成的操作 System.Console.WriteLine ($"网络变化:{ni.GetState ()}"); var type = getConnectedType (context); if (type == 2) { Application.IsWifi = true; } else { Application.IsWifi = false; } BaseActivity.NetworkStateChanged?.Invoke (type); } } break; } } int getConnectedType (Context context) { if (context != null) { var mConnectivityManager = (ConnectivityManager)context.GetSystemService (Context.ConnectivityService); if (mConnectivityManager == null) { return 0; } var mNetworkInfo = mConnectivityManager.ActiveNetworkInfo; if (mNetworkInfo != null && mNetworkInfo.IsAvailable) { switch (mNetworkInfo.Type) { case ConnectivityType.Mobile: return 1; case ConnectivityType.Wifi: return 2; } } } return 0; } } }