0

我试图构建一个在后台运行并在传入呼叫时激活的应用程序,经过一些研究后,我发现我必须nativelly执行,但我的代码是什么都不做。Xamarin:如何构建在来电时执行代码的应用程序

如果有办法在PCL项目上做到这一点,请让我知道。 我正在使用服务和广播接收器。 这里是我的实际代码:

[Activity(Label = "Teste2", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] 
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity 
    { 

     public static Context AppContext; 

     protected override void OnCreate(Bundle bundle) 
     { 
      TabLayoutResource = Resource.Layout.Tabbar; 
      ToolbarResource = Resource.Layout.Toolbar; 

      base.OnCreate(bundle); 

      global::Xamarin.Forms.Forms.Init(this, bundle); 
      LoadApplication(new App()); 

      AppContext = this.ApplicationContext; 

      StartPushService(); 
     } 

     public static void StartPushService() 
     { 
      AppContext.StartService(new Intent(AppContext, typeof(Services.BackgroundService))); 
      if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat) 
      { 

       PendingIntent pintent = PendingIntent.GetService(AppContext, 0, new Intent(AppContext, typeof(Services.BackgroundService)), 0); 
       AlarmManager alarm = (AlarmManager)AppContext.GetSystemService(Context.AlarmService); 
       alarm.Cancel(pintent); 
      } 
     } 

     public static void StopPushService() 
     { 
      AppContext.StopService(new Intent(AppContext, typeof(Services.BackgroundService))); 

      PendingIntent pintent = PendingIntent.GetService(AppContext, 0, new Intent(AppContext, typeof(Services.BackgroundService)), 0); 
      AlarmManager alarm = (AlarmManager)AppContext.GetSystemService(Context.AlarmService); 
      alarm.Cancel(pintent); 
     } 
    } 

服务:

[Service(Name = "com.xamarin.Teste2.BackgroundService")] 
    public class BackgroundService : Service 
    { 
     // Magical code that makes the service do wonderful things. 
     public override void OnCreate() 
     { 
      base.OnCreate(); 
     } 

     public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId) 
     { 

      return StartCommandResult.Sticky; 
     } 

     public override Android.OS.IBinder OnBind(Android.Content.Intent intent) 
     { 

      return null; 
     } 


     public override void OnDestroy() 
     { 
      base.OnDestroy(); 
     } 
    } 

和广播接收器:

[BroadcastReceiver] 
    [IntentFilter(new[] { Android.Content.Intent.ActionAnswer })] 
    public class CallReceiver : BroadcastReceiver 
    { 
     public override void OnReceive(Context context, Intent intent) 
     { 
      Toast.MakeText(context, "Incoming call from someone", ToastLength.Short).Show(); 
      System.Console.WriteLine("Incoming call from someone"); 
     } 
    } 
+0

你不能做它在PCL中,因为这种代码是由平台定义的。 iOS没有任何API来支持这一点。 – Jason

+0

这很奇怪,我们不能控制IOS中的来电。 –

+0

允许第三方应用程序干扰设备的基本功能将是一个巨大的安全风险 – Jason

回答

0

这是不可能的,因为IOS不会允许它

相关问题