RikNorakomi
12/15/2015 - 4:24 PM

send appje voor GCM

send appje voor GCM

public class SendActivity extends Activity {

    public static final String API_KEY = "AIzaSyB_iy81CHGYuRmCi6ypDGQkKPFYd74MOgU";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send);

        Button send = (Button) findViewById(R.id.sendButton);
        final EditText edit = (EditText) findViewById(R.id.editText);

        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (edit.getText().toString().length() > 0) {

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            sendTxt(edit.getText().toString());
                        }
                    }).start();
                }
            }
        });


    }

    private void sendTxt(String s) {
//        Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
        Log.e(" ", " sending msg: " + s);
        String[] args = {s};
        // Prepare JSON containing the GCM message content. What to send and where to send.
        JSONObject jGcmData = new JSONObject();
        JSONObject jData = new JSONObject();

        try {

            jData.put("message", s);

            // Where to send GCM message.
            jGcmData.put("to", "/topics/global");

            // What to send in GCM message.
            jGcmData.put("data", jData);

            // Create connection to send GCM Message request.
            URL url = new URL("https://android.googleapis.com/gcm/send");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Authorization", "key=" + API_KEY);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);

            // Send GCM message content.
            OutputStream outputStream = conn.getOutputStream();
            outputStream.write(jGcmData.toString().getBytes());

            // Read GCM response.
            InputStream inputStream = conn.getInputStream();
            String resp = IOUtils.toString(inputStream);
            System.out.println(resp);
            System.out.println("Check your device/emulator for notification or logcat for " +
                    "confirmation of the receipt of the GCM message.");
        } catch (IOException e) {
            System.out.println("Unable to send GCM message.");
            System.out.println("Please ensure that API_KEY has been replaced by the server " +
                    "API key, and that the device's registration token is correct (if specified).");
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }