将gcm通知发送给特定用户

时间:2016-01-29 05:31:02

标签: android google-cloud-messaging

我正在研究GCM。

我可以从本地服务器向所有注册的Android设备发送通知。

我在数据库中保存了regid和userid。我的要求是向特定设备发送通知。如何做到这一点?

我在服务器端使用java。任何答案都会节省我..我发布的服务器端代码

server side code
 public class GCMNotification extends HttpServlet {
        private static final long serialVersionUID = 1L;

        // Put your Google API Server Key here
        private static final String GOOGLE_SERVER_KEY = "AIzaSyDzlDr2viv-EghBFZGpjwXcDoqh24Wt9yE";
        static final String MESSAGE_KEY = "message";    
        static final String TITLE_KEY = "title";    
        static final String IMAGE_KEY= "image";                 
        static final String ORDER_KEY= "order";


     private List<String> androidTargets = new ArrayList<String>();

        public GCMNotification() {
                super();
        //  androidTargets.add(re);

        }

        protected void doGet(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {
            //doPost(request, response);
            Connection con=null; 
            try {

                Class.forName("com.mysql.jdbc.Driver");
                //Get a connection to the particular database
                 con=DriverManager.getConnection(  
                        "jdbc:mysql://localhost:3306/my_db","root","root1");  

                String sql;
                 sql = "SELECT regid, fname, email FROM my_db.Persons";
                Statement stmt = con.createStatement();
                ResultSet rs = stmt.executeQuery(sql);

                while(rs.next()){
                    //Retrieve by column name
                    int id  = rs.getInt("regid");
                    String first = rs.getString("fname");
                    String last = rs.getString("email");
                    androidTargets.add(id);
                }   

                  rs.close();
                  stmt.close();
                  con .close();

            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }



    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
         doGet(request, response);


         response.setContentType("text/html");  
         PrintWriter pw = response.getWriter();  
    //MulticastResult result = null;
        //Result result1=null;
        Writer writer=null;
        Connection con=null; 
        PrintWriter out = response.getWriter();
        String share = request.getParameter("shareRegId");

        // GCM RedgId of Android device to send push notification
    String reg = "";
    String emailId="";
    String fname="";

    if (share != null && !share.isEmpty()) {
            reg = request.getParameter("regId");
            emailId=request.getParameter("email");
            fname=request.getParameter("name");
            System.out.println("regId: " + reg);
            System.out.println("mailid " + emailId);
            System.out.println("name "+ fname);

            try {
                //Load the Driver for connection
                Class.forName("com.mysql.jdbc.Driver");
                //Get a connection to the particular database
                 con=DriverManager.getConnection(  
                        "jdbc:mysql://localhost:3306/my_db","root","root1");  

                PreparedStatement pst=con.prepareStatement("insert into my_db.Persons(regid,email,fname) values(?,?,?)");
                pst.setString(1,reg);  
                  pst.setString(2,emailId);        
                  pst.setString(3,fname);     
                  int i = pst.executeUpdate();  
                  if(i!=0){  
                    pw.println("<br>Record has been inserted");  


                  }  
                  else{  
                    pw.println("failed to insert the data");  
                   }  

                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

             MulticastResult result1=null;
                String userMessage = request.getParameter("message");
                String imageUrl = request.getParameter("image");
                String order1=request.getParameter("odt");
                String titl=request.getParameter("tit");
                Sender sender = new Sender(GOOGLE_SERVER_KEY);
                Message message = new Message.Builder().timeToLive(10000)
                         .delayWhileIdle(false)
                         .addData(TITLE_KEY, titl)
                         .addData(MESSAGE_KEY,userMessage)
                         .addData(IMAGE_KEY, imageUrl)
                         .addData(ORDER_KEY, order1)
                         .build();


                try {
                    // use this for multicast messages.  The second parameter
                    HashSet<String> set = new HashSet<String>(androidTargets);

                    // Create ArrayList from the set.
                    ArrayList<String> result = new ArrayList<String>(set);

                    System.out.println("reg2:"+result);
                    // of sender.send() will need to be an array of register ids.
                 result1 = sender.send(message, result,1);

                /*  if (result1.getResults() != null) {
                        int canonicalRegId = result1.getCanonicalIds();
                        if (canonicalRegId != 0) {  
                        }
                    } else {
                        int error = result1.getFailure();
                        System.out.println("Broadcast failure: " + error);
                    }*/

                } catch (Exception e) {
                    e.printStackTrace();
                }



                request.setAttribute("pushStatus", result1.toString());

            request.getRequestDispatcher("index.jsp")
                    .forward(request, response);
 }

    }

1 个答案:

答案 0 :(得分:1)

只需在sql查询中添加where子句即可筛选出您想要处理的确切用户。如果您想通过电子邮件过滤用户,请使用类似的内容..

 sql = "SELECT regid, fname, email FROM my_db.Persons where email = 'abc@gmail.com'";