简体   繁体   English

将设备发送到设备gcm通知

[英]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. 有人可以指向一个链接,我可以在其中轻松地了解如何将GCM用于设备到设备的通知。 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. 步骤1您有两部电话都连接到的服务器。

Step 2 You go to Google Developers page at this link 步骤2前往此链接的 Google Developers页面

Step 3 You create a new project there and then add a GCM API to your project. 步骤3在此处创建一个新项目,然后将GCM API添加到您的项目中。 Save the sender_id of the project. 保存项目的sender_id Also check the credentials of the API and add a new browser key and save that key. 还要检查API的凭据,并添加新的浏览器密钥并保存该密钥。

Step 4 Add GCM to your project. 步骤4将GCM添加​​到您的项目。 For that, goto the root directory where your Eclipse is installed. 为此,转到安装Eclipse的根目录。 Then navigate to the folder extras/google/google-play-services/libsproject/ and then copy the folder that is there to another location. 然后导航到extras/google/google-play-services/libsproject/文件夹,然后将那里的文件夹复制到另一个位置。 Then import that folder into your workspace in Eclipse and change its properties to make it a library. 然后将该文件夹导入Eclipse中的工作区,并更改其属性以使其成为库。 Then add this to your app project. 然后将此添加到您的应用程序项目。

Step 5 You need to register your mobile with GCM. 步骤5您需要在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. 步骤6保存注册ID,并将其传递到服务器以进行保存。

Step 7 When user clicks the send button, pass a message to your server. 步骤7当用户单击发送按钮时,将消息传递到您的服务器。 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. 服务器将拉出与数据库一起存储的ID列表,然后将消息和这些ID一起推送到GCM。

Step 8 Now GCM will send that message to all the phones whose ids were given to it. 步骤8现在,GCM会将该消息发送到为其提供ID的所有电话。

Step 9 Add a receiver in your app that receives the text from GCM and then displays it to the user. 步骤9在您的应用程序中添加一个接收器,该接收器从GCM接收文本,然后将其显示给用户。

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. 执行okkhttp请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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