Rooban
Rooban

Reputation: 248

Send gcm Notifications to specific user

I am working on GCM.

I am able to send notifications to all registered android devices from my local server.

I have saving regid and userid in database. my requirement is send notifications to particular devices.how to do that?

am using java on server side. Any answers will save me..i posted server side code

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);
 }

    }

Upvotes: 1

Views: 299

Answers (1)

kuma  DK
kuma DK

Reputation: 1861

Simply add a where clause to your sql query to filter out the exact user you want to deal with. If you want to filter the user by the email then use something like this..

 sql = "SELECT regid, fname, email FROM my_db.Persons where email = '[email protected]'";

Upvotes: 1

Related Questions