zoukankan      html  css  js  c++  java
  • iOS APNS推送前端和后端(Java)代码

    Push的原理:

    Push 的工作机制可以简单的概括为下图:
    Provider是指某个iPhone软件的Push服务器,这篇文章我将使用.net作为Provider。
    APNS 是Apple Push Notification Service(Apple Push服务器)的缩写,是苹果的服务器。
    上图可以分为三个阶段。
    第一阶段:Push服务器应用程序把要发送的消息、目的iPhone的标识打包,发给APNS。
    第二阶段:APNS在自身的已注册Push服务的iPhone列表中,查找有相应标识的iPhone,并把消息发到iPhone。
    第三阶段:iPhone把发来的消息传递给相应的应用程序, 并且按照设定弹出Push通知。
     
    iOS前端push消息步骤:
    1.应用程序注册消息通知,代码如下:[注意喽:ios7和ios8注册通知是不一样的哦!!!]
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
          //消息推送
        [self msgPush];
    
    }
    
    /**
        消息推送
     **/
    - (void) msgPush
    {
        //推送的形式:标记,声音,提示
        if (IS_IOS8) {
            //1.创建消息上面要添加的动作(按钮的形式显示出来)
            UIMutableUserNotificationAction *action = [[UIMutableUserNotificationAction alloc] init];
            action.identifier = @"action";//按钮的标示
            action.title=@"Accept";//按钮的标题
            action.activationMode = UIUserNotificationActivationModeForeground;//当点击的时候启动程序
            //    action.authenticationRequired = YES;
            //    action.destructive = YES;
            
            UIMutableUserNotificationAction *action2 = [[UIMutableUserNotificationAction alloc] init];
            action2.identifier = @"action2";
            action2.title=@"Reject";
            action2.activationMode = UIUserNotificationActivationModeBackground;//当点击的时候不启动程序,在后台处理
            action.authenticationRequired = YES;//需要解锁才能处理,如果action.activationMode = UIUserNotificationActivationModeForeground;则这个属性被忽略;
            action.destructive = YES;
            
            //2.创建动作(按钮)的类别集合
            UIMutableUserNotificationCategory *categorys = [[UIMutableUserNotificationCategory alloc] init];
            categorys.identifier = @"alert";//这组动作的唯一标示,推送通知的时候也是根据这个来区分
            [categorys setActions:@[action,action2] forContext:(UIUserNotificationActionContextMinimal)];
            
            //3.创建UIUserNotificationSettings,并设置消息的显示类类型
            UIUserNotificationSettings *notiSettings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIRemoteNotificationTypeSound) categories:[NSSet setWithObjects:categorys, nil]];
            [[UIApplication sharedApplication] registerUserNotificationSettings:notiSettings];
        }else{
            
            [[UIApplication sharedApplication] registerForRemoteNotificationTypes: UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert];
        }
        
    }

    - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings

    {

        //注册远程通知

        [application registerForRemoteNotifications];

    }

    2、 IOS跟APNS Server要deviceToken。应用程序接受deviceToken。【代码如下:】

    3、应用程序将deviceToken发送给PUSH服务端程序

    - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
    {
        MyLog(@"myToken = %@",deviceToken);
        //保存token
        [Config saveToken:[NSString stringWithFormat:@"%@",deviceToken]];

            //将deviceToken发送给服务器

             [self initNetworkState:[NSString stringWithFormat:@"%@",deviceToken]];

    }

    -(void)initNetworkState:(NSString *)pToken

    {

        NSDictionary *dicJson = [PackJsonForMine packTokenJson:pToken];

        NSError *error;

        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dicJson options:NSJSONWritingPrettyPrinted error: &error];

        NSMutableData *tempJsonData = [NSMutableData dataWithData:jsonData];

        

        request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:IDS_URL_TOKEN]];

        [request setRequestMethod:@"POST"];

        [request setPostBody:tempJsonData];

        [request setDelegate:self];

        [request setDidFailSelector:@selector(requestLogFailed:)];

        [request setDidFinishSelector:@selector(requestLogFinish:)];

        [request startAsynchronous];

    }

    /**

        发送token失败

     **/

    - (void)requestLogFailed:(ASIHTTPRequest *)requests

    {

        MyLog(@"发送token到服务器失败%@",[requests responseString]);

    }

    /**

        发送token成功

    **/

    - (void)requestLogFinish:(ASIHTTPRequest *)requests

    {

        [Config saveTokenFlag];

    }

    4、服务端程序向APNS服务发送消息。
    5、APNS服务将消息发送给iPhone应用程序。【注意喽:处理推送分为两种:正在运行的程序收到推送消息,alerat弹窗;锁屏时通知栏显示】
    #pragma mark - 处理推送的消息内容
    - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
    {
        self.urlStr = [userInfo valueForKey:@"link"];
        self.message = [[userInfo objectForKey:@"aps"] objectForKey:@"alert"];
        
        [UIApplication sharedApplication].applicationIconBadgeNumber = [UIApplication sharedApplication].applicationIconBadgeNumber = [[[userInfo objectForKey:@"aps"] objectForKey:@"badge"] intValue];
        
        //注意:在打开应用的时候,是需要一个弹框提醒的,不然用户看不到推送消息
        if (application.applicationState == UIApplicationStateActive) {
            
            if (self.urlStr.length > 0) {
                
                CustomIOS7AlertView *alertView = [[CustomIOS7AlertView alloc] init];
                //自定义AlertView
                [alertView setContainerView:[self createView]];
                [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"关闭",@"查看", nil]];
                [alertView setBackgroundColor:[UIColor clearColor]];
                [alertView setDelegate:self];
                [alertView setUseMotionEffects:true];
                [alertView show];
    
            }else{
                
                CustomIOS7AlertView *alertView = [[CustomIOS7AlertView alloc] init];
                //自定义AlertView
                [alertView setContainerView:[self createView]];
                [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"关闭", nil]];
                [alertView setBackgroundColor:[UIColor clearColor]];
                [alertView setDelegate:self];
                [alertView setUseMotionEffects:true];
                [alertView show];
            }
        }else{
            if (self.urlStr.length > 0) {
                WebViewController *webViewC = [[WebViewController alloc] init];
                webViewC.link = self.urlStr;
                [Tool showHideToolBar:HIDE];
                [navIntergralController pushViewController:webViewC animated:YES];
            }
    
        }
        
    }
    

     无论是iPhone客户端跟APNS,还是Provider和APNS都需要通过证书进行连接的。下面介绍一下所用到证书的制作。

    一、CSR文件

    1、生成Certificate Signing Request(CSR)
    2.填写你的邮箱和常用名称,并保存到硬盘
    点击继续:
    这样就在本地生成了一个PushTest.certSigningRequest文件。
    二、SSL certificate文件 以及相关的证书制作过程详情请见如下博客内容:
     
    http://www.cnblogs.com/imlucky/p/3419581.html
     
    在推送中测试的时候需要测试的.P12文件和发布的.P12文件
     
    后台代码:
    六、JAVA后台代码:
    public static void main(String[] args) throws Exception 
    {
            try
            {
                //从客户端获取的deviceToken,在此为了测试简单,写固定的一个测试设备标识。
               String deviceToken = "df779eda 73258894 5882ec78 3ac7b254 6ebc66fe fa295924 440d34ad 6505f8c4"
                System.out.println("Push Start deviceToken:" + deviceToken);
                //定义消息模式
                PayLoad payLoad = new PayLoad();
                payLoad.addAlert("this is test!");
                payLoad.addBadge(1);//消息推送标记数,小红圈中显示的数字。
                payLoad.addSound("default");
                //注册deviceToken
                PushNotificationManager pushManager = PushNotificationManager.getInstance();
                pushManager.addDevice("iPhone", deviceToken);
                //连接APNS
                String host = "gateway.sandbox.push.apple.com";
                //String host = "gateway.push.apple.com";
                int port = 2195;
                String certificatePath = "c:/PushTest.p12";//前面生成的用于JAVA后台连接APNS服务的*.p12文件位置
                String certificatePassword = "123456";//p12文件密码。
                pushManager.initializeConnection(host, port, certificatePath, certificatePassword, SSLConnectionHelper.KEYSTORE_TYPE_PKCS12);
                //发送推送
                Device client = pushManager.getDevice("iPhone");
                System.out.println("推送消息: " + client.getToken()+" "+payLoad.toString() +" ");
                pushManager.sendNotification(client, payLoad);
                //停止连接APNS
                pushManager.stopConnection();
                //删除deviceToken
                pushManager.removeDevice("iPhone");
                System.out.println("Push End");
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
            }
    }
    }
    至此大功告成!!!!!!!
  • 相关阅读:
    tudou(土豆)、youku(优酷)API(有相应的dll [C#])
    创新工场2012笔试编程捕鱼和分鱼
    区别Web文本框和HTML文本框的RandOnly、Disabled
    DataRow[]、List<DataRow>无法绑定到GridView的问题解决!
    1、NHibernate入门
    Verilog HDL 学习笔记2blocking and nonblocking assignment
    Verilog HDL 学习笔记1data type
    2006.08.21网摘
    推荐十一个很酷的实用网站
    类 ObjectOutputStream的writeObject()方法的中英文对照
  • 原文地址:https://www.cnblogs.com/yuanyuandachao/p/4113321.html
Copyright © 2011-2022 走看看