简体   繁体   中英

send device to device gcm notification

Can someone please point a link where i can easily understand how to use GCM for device to device notification. What is required to make device as server and receiver.

Let me explain my requirement , you guys might have a better solution to my problem

I want to send a notification(pre defined message) to one or group of people on a button click, the other user can do the same.

Thanks

Let me try to explain the basic working You need- A server and two mobile phones

Step 1 You have a server that both the phones connect to.

Step 2 You go to Google Developers page at this link

Step 3 You create a new project there and then add a GCM API to your project. Save the sender_id of the project. Also check the credentials of the API and add a new browser key and save that key.

Step 4 Add GCM to your project. For that, goto the root directory where your Eclipse is installed. Then navigate to the folder extras/google/google-play-services/libsproject/ and then copy the folder that is there to another location. Then import that folder into your workspace in Eclipse and change its properties to make it a library. Then add this to your app project.

Step 5 You need to register your mobile with GCM. For that you can work with a sample code like this

// to start process
public void registerDevice() {
    // TODO Auto-generated method stub
    try {
        if (checkPlayServices()) {
             regid = getRegistrationId();

            if (regid.isEmpty()) { // creating a new reg id
                registerInBackground();
            } else
                saveid();
        } else{

        }
    } catch (Exception e) {
    }
}

// to create a new id
private void registerInBackground() {
    // TODO Auto-generated method stub
    try {

        AsyncRegister logMeIn = new AsyncRegister("<you project id here>", context);

        logMeIn.doneWith = this;
        logMeIn.execute();

        System.out.println("execute complete");

    } catch (Exception e) {
    }
}

// to fetch stored registration id
private String getRegistrationId() {
    // TODO Auto-generated method stub
    try {


        int i=myPrefs.getInt("cuid", 0);

        if(id!=i){
            myPrefs.edit().putInt("cuid", id).commit();

            int registeredVersion = myPrefs.getInt("appversion",
                    Integer.MIN_VALUE); // to check if app is updated
            int currentVersion = getAppVersion();

            if (registeredVersion != currentVersion) {
                myPrefs.edit().putInt("appversion",currentVersion).commit();
            }

            return "";
        }

        String registrationId = myPrefs.getString("regid", ""); 

        if (registrationId.isEmpty()) {
            return "";
        }

        int registeredVersion = myPrefs.getInt("appversion",
                Integer.MIN_VALUE); // to check if app is updated
        int currentVersion = getAppVersion();

        if (registeredVersion != currentVersion) {
            myPrefs.edit().putInt("appversion", currentVersion).commit();
            return "";
        }

        // when id is stored previously then this is called
        return registrationId;
    } catch (Exception e) {
    }
}

//to fetch the current app version
private int getAppVersion() throws NameNotFoundException {
    // TODO Auto-generated method stub

        PackageInfo packageInfo = context.getPackageManager().getPackageInfo(
                context.getPackageName(), 0);
        return packageInfo.versionCode;
}

// to check if play services are there on the device
private boolean checkPlayServices() {
    // TODO Auto-generated method stub
    try {

        int resultCode = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(context);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                toSend = new Bundle();
                  //tell user google play needs to be updated

            } else {
                //tell user their system does not support GCM
            }

            myPrefs.edit().putBoolean("support", false).commit();

            return false;
        }
        myPrefs.edit().putBoolean("support", true).commit();
        return true;
    } catch (Exception e) {
    }
}

Step 6 Save the registration ID and pass it to your server to save it.

Step 7 When user clicks the send button, pass a message to your server. The server will pull out the list of ids stored with the DB and will then push the message to GCM along with those ids.

Step 8 Now GCM will send that message to all the phones whose ids were given to it.

Step 9 Add a receiver in your app that receives the text from GCM and then displays it to the user.

This is a brief explanation. If you want to understand this in details please read online tutorials. Else you can also text me on my group (link you will find in my profile description) and i will gladly help you out.

String postData = "{ \"registration_ids\": [ \"" + OtherDeviceToken+ "\" ], " +
                          "\"delay_while_idle\": true, " +
                          "\"data\": {\"tickerText\":\"Your title\", "+
                          "\"contentTitle\":\"AppName\", " +
                     "\"message\": \" " + edtYourMessage.getText().toString() + "\"}}";

MediaType JSON= MediaType.parse("application/json; charset=utf-8");
 RequestBody body = RequestBody.create(JSON, postData);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://android.googleapis.com/gcm/send")
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", "key=" + SERVER_API_KEY)
.post(body)
.build();

Execute the okkhttp request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM