Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Android推送通知在应用程序未运行时中断应用程序_C#_Azure_Xamarin.android_Azure Notificationhub - Fatal编程技术网

C# Android推送通知在应用程序未运行时中断应用程序

C# Android推送通知在应用程序未运行时中断应用程序,c#,azure,xamarin.android,azure-notificationhub,C#,Azure,Xamarin.android,Azure Notificationhub,我正在尝试通过以下方式向我的应用程序添加推送通知 在遵循本分步教程在Xamarin.Android上设置推送通知后,Android设备会在应用程序运行或后台运行时收到推送通知。但如果我关闭应用程序,使其不再运行,然后发送推送通知,设备会显示此信息 错误消息: “很遗憾,[应用程序名称]已停止” 下面是我的代码实现 [Service] // Must use the service tag public class PushHandlerService : GcmServiceBase {

我正在尝试通过以下方式向我的应用程序添加推送通知

在遵循本分步教程在Xamarin.Android上设置推送通知后,Android设备会在应用程序运行或后台运行时收到推送通知。但如果我关闭应用程序,使其不再运行,然后发送推送通知,设备会显示此信息 错误消息:

“很遗憾,[应用程序名称]已停止”

下面是我的代码实现

[Service] // Must use the service tag
public class PushHandlerService : GcmServiceBase
{
    public static string RegistrationID { get; private set; }
    private NotificationHub Hub { get; set; }

    public PushHandlerService() : base(Constants.SenderID)
    {
        Log.Info(MyBroadcastReceiver.TAG, "PushHandlerService() constructor");
    }

    protected override void OnRegistered(Context context, string registrationId)
    {
        Log.Verbose(MyBroadcastReceiver.TAG, "GCM Registered: " + registrationId);
        RegistrationID = registrationId;

        /*createNotification("PushHandlerService-GCM Registered...",
                            "The device has been Registered!");*/

        Hub = new NotificationHub(Constants.NotificationHubName, Constants.ListenConnectionString,
                                    context);
        try
        {
            Hub.UnregisterAll(registrationId);
        }
        catch (Exception ex)
        {
            Log.Error(MyBroadcastReceiver.TAG, ex.Message);
        }

        //var tags = new List<string>() { "falcons" }; // create tags if you want
        var tags = new List<string>() { };

        try
        {
            var hubRegistration = Hub.Register(registrationId, tags.ToArray());
        }
        catch (Exception ex)
        {
            Log.Error(MyBroadcastReceiver.TAG, ex.Message);
        }
    }
    protected override void OnMessage(Context context, Intent intent)
    {
        Log.Info(MyBroadcastReceiver.TAG, "GCM Message Received!");

        var msg = new System.Text.StringBuilder();

        if (intent != null && intent.Extras != null)
        {
            foreach (var key in intent.Extras.KeySet())
                msg.AppendLine(key + "=" + intent.Extras.Get(key).ToString());
        }

        string messageText = intent.Extras.GetString("message");
        if (!string.IsNullOrEmpty(messageText))
        {
            createNotification("New hub message!", messageText);
        }
        else
        {
            createNotification("Unknown message details", msg.ToString());
        }
    }
    void createNotification(string title, string desc)
    {
        //Create notification
        var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;

        //Create an intent to show UI
        var uiIntent = new Intent(this, typeof(MainActivity));

        //Create the notification
        var notification = new Notification(Android.Resource.Drawable.SymActionEmail, title);

        //Auto-cancel will remove the notification once the user touches it
        notification.Flags = NotificationFlags.AutoCancel;

        //Set the notification info
        //we use the pending intent, passing our ui intent over, which will get called
        //when the notification is tapped.
        notification.SetLatestEventInfo(this, title, desc, PendingIntent.GetActivity(this, 0, uiIntent, 0));

        //Show the notification
        notificationManager.Notify(1, notification);
        dialogNotify(title, desc);
    }

    protected void dialogNotify(string title, string message)
    {
        MainActivity.instance.RunOnUiThread(() => {
            AlertDialog.Builder dlg = new AlertDialog.Builder(MainActivity.instance);
            AlertDialog alert = dlg.Create();
            alert.SetTitle(title);
            alert.SetButton("Ok", delegate {
                alert.Dismiss();
            });
            alert.SetMessage(message);
            alert.Show();
        });
    }

    protected override void OnUnRegistered(Context context, string registrationId)
    {
        Log.Verbose(MyBroadcastReceiver.TAG, "GCM Unregistered: " + registrationId);

        createNotification("GCM Unregistered...", "The device has been unregistered!");
    }

    protected override bool OnRecoverableError(Context context, string errorId)
    {
        Log.Warn(MyBroadcastReceiver.TAG, "Recoverable Error: " + errorId);

        return base.OnRecoverableError(context, errorId);
    }

    protected override void OnError(Context context, string errorId)
    {
        Log.Error(MyBroadcastReceiver.TAG, "GCM Error: " + errorId);
    }
}
[Service]//必须使用服务标签
公共类PushHandlerService:GcmServiceBase
{
公共静态字符串注册ID{get;private set;}
私有通知中心{get;set;}
public PushHandlerService():base(Constants.SenderID)
{
Info(MyBroadcastReceiver.TAG,“PushHandlerService()构造函数”);
}
受保护的覆盖void OnRegistered(上下文上下文,字符串注册ID)
{
详细日志(MyBroadcastReceiver.TAG,“GCM注册:”+registrationId);
注册ID=注册ID;
/*createNotification(“PushHandlerService GCM已注册…”,
“设备已注册!”)*/
Hub=新的NotificationHub(Constants.NotificationHubName,Constants.ListenConnectionString,
上下文);
尝试
{
Hub.UnregisterAll(注册ID);
}
捕获(例外情况除外)
{
Log.Error(MyBroadcastReceiver.TAG,ex.Message);
}
//var tags=new List(){“falcons”};//如果需要,可以创建标记
var tags=newlist(){};
尝试
{
var hubRegistration=Hub.Register(registrationId,tags.ToArray());
}
捕获(例外情况除外)
{
Log.Error(MyBroadcastReceiver.TAG,ex.Message);
}
}
受保护的覆盖无效消息(上下文、意图)
{
Log.Info(MyBroadcastReceiver.TAG,“收到GCM消息!”);
var msg=new System.Text.StringBuilder();
if(intent!=null&&intent.Extras!=null)
{
foreach(var key in intent.Extras.KeySet())
msg.AppendLine(key+“=”+intent.Extras.Get(key.ToString());
}
string messageText=intent.Extras.GetString(“消息”);
如果(!string.IsNullOrEmpty(messageText))
{
createNotification(“新建中心消息!”,messageText);
}
其他的
{
createNotification(“未知消息详细信息”,msg.ToString());
}
}
void createNotification(字符串标题、字符串描述)
{
//创建通知
var notificationManager=GetSystemService(Context.NotificationService)作为notificationManager;
//创建显示UI的意图
var uiIntent=新意图(此,类型为(MainActivity));
//创建通知
var通知=新通知(Android.Resource.Drawable.SymActionEmail,标题);
//“自动取消”将在用户触摸通知后删除该通知
notification.Flags=NotificationFlags.AutoCancel;
//设置通知信息
//我们使用挂起的意图,传递我们的ui意图,它将被调用
//当点击通知时。
notification.SetLatestEventInfo(this,title,desc,pendingent.GetActivity(this,0,uiIntent,0));
//显示通知
通知经理。通知(1,通知);
dialogNotify(标题、描述);
}
受保护的无效对话框Notify(字符串标题、字符串消息)
{
MainActivity.instance.RunOnUiThread(()=>{
AlertDialog.Builder dlg=新建AlertDialog.Builder(MainActivity.instance);
AlertDialog alert=dlg.Create();
警报。设置标题(标题);
警报。设置按钮(“确定”,代表{
警惕。解散();
});
警报。设置消息(消息);
alert.Show();
});
}
未注册的受保护覆盖无效(上下文上下文、字符串注册ID)
{
详细日志(MyBroadcastReceiver.TAG,“GCM未注册:”+registrationId);
createNotification(“GCM已注销…”,“设备已注销!”);
}
受保护的覆盖布尔OnRecoverableError(上下文上下文,字符串errorId)
{
Log.Warn(MyBroadcastReceiver.TAG,“可恢复错误:+errorId”);
返回base.OnRecoverableError(上下文,errorId);
}
受保护的覆盖无效OnError(上下文上下文,字符串错误ID)
{
Log.Error(MyBroadcastReceiver.TAG,“GCM错误:”+errorId);
}
}

}`

最后,我通过在message

代码如下:

    protected override async void OnMessage(Context context, Intent intent)
    {
    Log.Info(MyBroadcastReceiver.TAG, "GCM Message Received!");
        await Task.Delay(1000);

        var msg = new System.Text.StringBuilder();
        if (intent != null && intent.Extras != null)
        {
            foreach (var key in intent.Extras.KeySet())
                msg.AppendLine(key + "=" + intent.Extras.Get(key).ToString());
        }

        string messageText = intent.Extras.GetString("message");
        if (!string.IsNullOrEmpty(messageText))
        {
           createNotification("New hub message!", messageText);
        }
        else
        {
           createNotification("Unknown message details", msg.ToString());
        }
    }`

你在实际设备上试过了吗?有时是因为emulator.Yaa我试过了,但输出是相同的,可能是重复的,我已经通过了这个链接,但这是完全不同的问题,因此我要求保留这个问题,因为它是您可以共享您的实现代码吗?你们可能错过了什么?嗨,我正在尝试在应用程序不是在后台运行但运气不好的情况下获取推送通知。您是否收到此场景的通知。