Push notification gcm注册id未进入我的服务器

Push notification gcm注册id未进入我的服务器,push-notification,google-cloud-messaging,Push Notification,Google Cloud Messaging,我正在尝试实现gcm。我获得了注册id,但无法进入我的在线服务器。有人能帮我解决这个问题吗 sendRegistrationIdToBackend(字符串regid)是我尝试将寄存器id输入服务器的方法 MainActivity.java package com.myapp.revanth.gcm; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; impor

我正在尝试实现gcm。我获得了注册id,但无法进入我的在线服务器。有人能帮我解决这个问题吗

sendRegistrationIdToBackend(字符串regid)是我尝试将寄存器id输入服务器的方法

MainActivity.java

package com.myapp.revanth.gcm;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;


public class MainActivity extends Activity {

private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
public static final String EXTRA_MESSAGE = "message";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private static final String TAG = "GCMRelated";



String SENDER_ID = "1096796854079";
   EditText txt;
GoogleCloudMessaging gcm;
AtomicInteger msgId = new AtomicInteger();
String regid;
SharedPreferences prefs;
Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    context = getApplicationContext();
    final Button button = (Button) findViewById(R.id.register);
    txt=(EditText)findViewById(R.id.display);


    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            // Check device for Play Services APK.
            if (checkPlayServices()) {
                gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
                regid = getRegistrationId(getApplicationContext());

                if (regid.isEmpty()) {
                    button.setEnabled(false);

                    new RegisterBackground().execute();

                }else{
                    Toast.makeText(getApplicationContext(), "Device already Registered", Toast.LENGTH_SHORT).show();
                }
            } else {
                Log.i(TAG, "No valid Google Play Services APK found.");
            }
        }
    });


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

class RegisterBackground extends AsyncTask<String,String,String> {

    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub

        String msg="";
        try {
            if (gcm == null) {
                gcm = GoogleCloudMessaging.getInstance(context);
            }
            regid = gcm.register(SENDER_ID);

            msg = "Device registered, registration ID=" + regid;

            Log.d("111", msg);
            sendRegistrationIdToBackend(regid);

            storeRegistrationId(context,regid);
        } catch (IOException ex) {
            msg = "Error :" + ex.getMessage();
        }
        return msg;
    }

    @Override
    protected void onPostExecute(String msg) {
        txt.setText(regid);
        Toast.makeText(getApplicationContext(), "msg"+msg, Toast.LENGTH_SHORT).show();
    }

    private void sendRegistrationIdToBackend(String regid) {
        // this code will send registration id of a device to our own server.
        URI url = null;
        try {
            url = new URI("http://myname.byethost4.com/getdevice.php?regId=" + regid);
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet request = new HttpGet();
        request.setURI(url);
        try {
            httpclient.execute(request);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    private void storeRegistrationId(Context context, String regId) {
        final SharedPreferences prefs = getGCMPreferences(context);
        int appVersion = getAppVersion(context);
        Log.i(TAG, "Saving regId on app version " + appVersion);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(PROPERTY_REG_ID, regId);
        editor.putInt(PROPERTY_APP_VERSION, appVersion);
        editor.commit();
    }
}
/**
 * Check the device to make sure it has the Google Play Services APK. If
 * it doesn't, display a dialog that allows users to download the APK from
 * the Google Play Store or enable it in the device's system settings.
 */

private boolean checkPlayServices() {
    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if (resultCode != ConnectionResult.SUCCESS) {
        if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
            GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                    PLAY_SERVICES_RESOLUTION_REQUEST).show();
        } else {
            Log.i(TAG, "This device is not supported.");
            finish();
        }
        return false;
    }
    return true;
}

/**
 * Gets the current registration ID for application on GCM service.
 * <p>
 * If result is empty, the app needs to register.
 *
 * @return registration ID, or empty string if there is no existing
 *         registration ID.
 */
private String getRegistrationId(Context context) {
    final SharedPreferences prefs = getGCMPreferences(context);
    String registrationId = prefs.getString(PROPERTY_REG_ID, "");
    if (registrationId.isEmpty()) {
        Log.i(TAG, "Registration not found.");
        return "";
    }
    // Check if app was updated; if so, it must clear the registration ID
    // since the existing regID is not guaranteed to work with the new
    // app version.
    int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
    int currentVersion = getAppVersion(getApplicationContext());
    if (registeredVersion != currentVersion) {
        Log.i(TAG, "App version changed.");
        return "";
    }
    return registrationId;
}

/**
 * @return Application's {@code SharedPreferences}.
 */
private SharedPreferences getGCMPreferences(Context context) {
    // This sample app persists the registration ID in shared preferences, but
    // how you store the regID in your app is up to you.
    return getSharedPreferences(MainActivity.class.getSimpleName(),
            Context.MODE_PRIVATE);
}

/**
 * @return Application's version code from the {@code PackageManager}.
 */
private static int getAppVersion(Context context) {
    try {
        PackageInfo packageInfo = context.getPackageManager()
                .getPackageInfo(context.getPackageName(), 0);
        return packageInfo.versionCode;
    } catch (NameNotFoundException e) {
        // should never happen
        throw new RuntimeException("Could not get package name: " + e);
    }
}
package com.myapp.revanth.gcm;
导入java.io.IOException;
导入java.io.UnsupportedEncodingException;
导入java.net.URI;
导入java.net.URISyntaxException;
导入java.util.ArrayList;
导入java.util.List;
导入java.util.concurrent.AtomicInteger;
导入com.google.android.gms.common.ConnectionResult;
导入com.google.android.gms.common.GooglePlayServicesUtil;
导入com.google.android.gms.gcm.GoogleCloudMessaging;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.app.Activity;
导入android.content.Context;
导入android.content.SharedReferences;
导入android.content.pm.PackageInfo;
导入android.content.pm.PackageManager.NameNotFoundException;
导入android.util.Log;
导入android.view.Menu;
导入android.view.view;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.TextView;
导入android.widget.Toast;
导入org.apache.http.HttpResponse;
导入org.apache.http.NameValuePair;
导入org.apache.http.client.ClientProtocolException;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.entity.UrlEncodedFormEntity;
导入org.apache.http.client.methods.HttpGet;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.message.BasicNameValuePair;
公共类MainActivity扩展了活动{
专用静态最终整数播放服务解析请求=9000;
公共静态最终字符串EXTRA_MESSAGE=“MESSAGE”;
公共静态最终字符串属性\u REG\u ID=“注册\u ID”;
私有静态最终字符串属性\u APP\u VERSION=“appVersion”;
私有静态最终字符串TAG=“GCMRelated”;
字符串发送者\u ID=“1096796854079”;
编辑文本文本;
谷歌云通讯gcm;
AtomicInteger msgId=新的AtomicInteger();
字符串寄存器;
共享引用优先权;
语境;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=getApplicationContext();
最终按钮按钮=(按钮)findViewById(R.id.register);
txt=(EditText)findViewById(R.id.display);
setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
//检查设备的播放服务APK。
如果(checkPlayServices()){
gcm=GoogleCloudMessaging.getInstance(getApplicationContext());
regid=getRegistrationId(getApplicationContext());
if(regid.isEmpty()){
按钮。设置启用(错误);
新寄存器background().execute();
}否则{
Toast.makeText(getApplicationContext(),“设备已注册”,Toast.LENGTH\u SHORT.show();
}
}否则{
i(标记“找不到有效的Google Play服务APK”);
}
}
});
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
//为菜单充气;这会将项目添加到操作栏(如果存在)。
getMenuInflater().充气(右菜单菜单菜单主菜单);
返回true;
}
类RegisterBackground扩展了AsyncTask{
@凌驾
受保护的字符串doInBackground(字符串…arg0){
//TODO自动生成的方法存根
字符串msg=“”;
试一试{
如果(gcm==null){
gcm=GoogleCloudMessaging.getInstance(上下文);
}
regid=gcm.寄存器(发送方ID);
msg=“设备已注册,注册ID=“+regid;
Log.d(“111”,msg);
发送注册IDToBackend(regid);
storeRegistrationId(上下文,regid);
}捕获(IOEX异常){
msg=“错误:”+ex.getMessage();
}
返回味精;
}
@凌驾
受保护的void onPostExecute(字符串msg){
txt.setText(regid);
Toast.makeText(getApplicationContext(),“msg”+msg,Toast.LENGTH\u SHORT.show();
}
私有void sendRegistrationIdToBackend(字符串regid){
//此代码将设备的注册id发送到我们自己的服务器。
uriurl=null;
试一试{
url=新URI(“http://myname.byethost4.com/getdevice.php?regId=“+regid);
}捕获(URISyntaxException e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
HttpClient HttpClient=新的DefaultHttpClient();
HttpGet请求=新建HttpGet();
setURI(url);
试一试{
httpclient.execute(请求);
}捕获(客户端协议例外e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
私有void storeRegistrationId(上下文上下文,字符串regId){
最终SharedReferences prefs=getGCMPreferences(上下文);
int-appVersion=getAppVersion(上下文);
Log.i(标记“在应用程序版本上保存注册表”+应用程序版本);
SharedReferences.Editor=prefs.edit();
编辑器.putString(PROPERTY\u REG\u ID,regId);
编辑器.putInt(属性\应用\版本,应用版本);
commit();
}
}
/**
*检查设备以确保其具有Google Play Services APK。如果
*它不会显示一个对话框,允许用户从中下载APK
*Google Play存储或在设备的系统设置中启用它。
*/
私有布尔值checkPlayServices(){
int-resultCode=GooglePlayServicesUtil.isgoogleplayservicesavaailable(this);
如果(结果代码!=连接结果)
<?php
$id = $_GET["regId"];
echo $id;
$con = mysql_connect("ftp.byethost4.com","my_username","password");
mysql_select_db("database_name",$con);
mysql_query("INSERT INTO gcmreguser VALUES('".$id."')");
mysql_close($con);