2017-04-03 65 views
2

我試圖在打出電話時顯示通知,但它不起作用(不顯示任何內容)。我單獨測試了通知,它工作正常,但我很確定我在BroadcastReceiver中做了錯誤。 在此先感謝!Xamarin/Android應用程序:廣播接收器無法正常工作

MainActivity:

[Activity(Label = "ExamProject", MainLauncher = true, Icon = "@drawable/icon")] 
public class MainActivity : Activity 
{ 
    protected override void OnCreate(Bundle bundle) 
    { 
     MyBroadcastRecieverClass reciever; 
     base.OnCreate(bundle); 
     // Set our view from the "main" layout resource 
     SetContentView(Resource.Layout.Main); 
     reciever = new MyBroadcastRecieverClass(); 
     RegisterReceiver(reciever, new IntentFilter("android.intent.action.NEW_OUTGOING_CALL")); 

BroadcastReciever類:

namespace App3 
{ 
[BroadcastReceiver(Enabled = true, Exported = true)] 
[IntentFilter(new[] { Android.Content.Intent.ActionNewOutgoingCall })] 
public class MyBroadcastRecieverClass: BroadcastReceiver 
{ 
    public override void OnReceive(Context context, Intent intent) 
    { 
     // Do stuff here. 

     //String value = intent.GetStringExtra("key"); 

     Notification.Builder builder = new Notification.Builder(Application.Context) 
       .SetContentTitle("Test Title") 
       .SetContentText("test content") 
       .SetSmallIcon(Resource.Drawable.Icon) 
       .SetPriority(100) 
       .SetDefaults(NotificationDefaults.Sound) 
       .SetVisibility(NotificationVisibility.Public) 
       .SetCategory(Notification.CategoryAlarm); 


     //build the notification 
     Notification test = builder.Build(); 

     // Get the notification manager: 
     NotificationManager notificationManager = 
      context.GetSystemService(Context.NotificationService) as NotificationManager; 

     // Publish the notification: 
     const int notificationId = 0;//should be changed to generate a uniqe value 
     notificationManager.Notify(notificationId, test); 
    } 
} 

}

+2

你有沒有添加權限處理外撥電話? ('PROCESS_OUTGOING_CALLS') – SushiHangover

回答

0

你得到的logcat的日誌中的任何錯誤?

確保您向項目添加了PROCESS_OUTGOING_CALLS權限。

您必須持有PROCESS_OUTGOING_CALLS權限才能接收此意向。

+0

設置權限不是原因。不確定您指的是哪個日誌,Visual Studio中的調試輸出日誌中有很多信息,但我沒有看到引用廣播接收器的任何內容 –

1

我發現錯誤,這裏有一個問題syntaxt:

RegisterReceiver(reciever, new IntentFilter("android.intent.action.NEW_OUTGOING_CALL")); 

正確的代碼:

public class MainActivity : Activity 
{ 
    protected override void OnCreate(Bundle bundle) 
    { 
     MyBroadcastRecieverClass reciever; 
     base.OnCreate(bundle); 
     // Set our view from the "main" layout resource 
     SetContentView(Resource.Layout.Main); 
     reciever = new MyBroadcastRecieverClass(); 

     IntentFilter myIntentFilter = new IntentFilter("android.intent.action.NEW_OUTGOING_CALL"); 
     RegisterReceiver(reciever, myIntentFilter); 

     Button settingsButton = FindViewById<Button>(Resource.Id.settingsButton);