Google Cloud消息服务返回空注册ID

时间:2015-03-06 09:58:39

标签: java android android-emulator google-cloud-messaging

我遇到了实施Google Cloud Messaging的问题。当我尝试注册我的模拟器时,我想要获取设备的注册ID,在这种情况下是我的模拟器。因此,当我环顾四周时,我看到我需要链接一个谷歌帐户,所以我这样做,但我仍然有同样的问题。它返回它是一个新注册但注册ID为空。有人可以帮助我朝正确的方向发展吗?如果您需要了解其他信息,请告诉我们。提前致谢

代码:

LoginActivity.java

package com.vict.voffice;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.vict.voffice.utilities.Dialogs;
import com.vict.voffice.utilities.GCMClientManager;
import com.vict.voffice.utilities.UserDetailCache;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;


public class LoginActivity extends Activity {

    EditText mNaam;
    EditText mVersie;
    EditText mWachtwoord;
    String PROJECT_NUMBER = "##########";
    private GCMClientManager pushClientManager;

    private Context cont = this;

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

        cont = this;

        pushClientManager = new GCMClientManager(this, PROJECT_NUMBER);

        mNaam = (EditText)findViewById(R.id.editText_login);
        mVersie = (EditText)findViewById(R.id.editText_bedrijf);
        mWachtwoord = (EditText)findViewById(R.id.editText_wachtwoord);

        final Button button = (Button) findViewById(R.id.btnLogin);
        button.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v){
                pushClientManager.registerIfNeeded(new GCMClientManager.RegistrationCompletedHandler() {
                    @Override
                    public void onSuccess(String registrationId, boolean isNewRegistration) {
                        //Dialogs.LoginDialog(cont).show();
                        Toast.makeText(getApplicationContext(), "Regid: "+registrationId+" "+isNewRegistration, Toast.LENGTH_SHORT).show();
                        //Login(mNaam.getText().toString(), mWachtwoord.getText().toString(), mVersie.getText().toString(), pushClientManager.getRegistrationId(cont));
                    }
                    @Override
                    public void onFailure(String ex) {}});
                Log.d("DBG", "Login Pressed");
            }
        });

        Log.d("DBG", ""+UserDetailCache.GetNodeFromFile(cont));
        if(UserDetailCache.GetNodeFromFile(cont) != null || UserDetailCache.GetNodeFromFile(cont) != "" || UserDetailCache.GetNodeFromFile(cont) != "null" || UserDetailCache.GetNodeFromFile(cont).isEmpty()){
            if(UserDetailCache.GetUserNameFromFile(cont) != null || UserDetailCache.GetUserNameFromFile(cont) != "" || UserDetailCache.GetUserNameFromFile(cont) != "null"){
                if(UserDetailCache.GetPasswordFromFile(cont) != null || UserDetailCache.GetPasswordFromFile(cont) != "" || UserDetailCache.GetPasswordFromFile(cont) != "null"){
                    Log.d("DBG", "Filling Fields from DB");
                    mNaam.setText(UserDetailCache.GetUserNameFromFile(getApplicationContext()));
                    mWachtwoord.setText(UserDetailCache.GetPasswordFromFile(getApplicationContext()));
                    mVersie.setText(UserDetailCache.GetNodeFromFile(getApplicationContext()));
                    button.performClick();
                }else{
                    Log.d("DBG", "No Password");
                }
            }else{
                Log.d("DBG", "No Username");
            }
        }else{
            Log.d("DBG", "No Node");
        }

    }

    @Override
    public void onBackPressed(){
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        super.onBackPressed();
        System.exit(0);
    }

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

    public void Login(String Username, String Password, String Node, String Token){

        class LoginAsyncTask extends AsyncTask<String, Void, String>{
            UserDetailCache Dtc = new UserDetailCache();
            String uniqueKey = "";


            @Override
            protected void onPreExecute(){
                super.onPreExecute();
                //Dialogs.LoginDialog(getApplicationContext()).show();
            }

            @Override
            protected String doInBackground(String... params) {


                String paramUsername = params[0];
                String paramPassword = params[1];
                String paramVersion = params[2];
                uniqueKey = params[3];


                Log.d("LoginActivity", "Token: " + uniqueKey);

                HttpClient httpClient = new DefaultHttpClient();

                HttpPost httpPost = new HttpPost("http://node11.voffice.nl/login/appcheck.asp?login=" + paramUsername + "&wachtw=" + paramPassword + "&versie=" + paramVersion + "&token=" + uniqueKey);
                //Log.e("HTTP", "send link: " + httpPost.getURI());

                try{
                    HttpResponse httpResponse = httpClient.execute(httpPost);


                    InputStream inputStream = httpResponse.getEntity().getContent();
                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    StringBuilder stringBuilder = new StringBuilder();
                    String bufferedStrChunk = null;

                    while((bufferedStrChunk = bufferedReader.readLine()) != null){
                        stringBuilder.append(bufferedStrChunk);
                    }



                    return stringBuilder.toString();

                }catch (ClientProtocolException cpe){
//                  Log.e("HTTP", "First Exception, httpResponse : " + cpe);
                    cpe.printStackTrace();
                }catch (IOException ioe){
//                  Log.e("HTTP", "Second Exception, httpResonse : " + ioe);
                    ioe.printStackTrace();
                }

                return null;
            }

            @Override
            protected void onPostExecute(String result){
                super.onPostExecute(result);
                Log.e("HTTP", "Server Responded with : " + result);
                String splitResult[] = result.split("\\|");

                if(splitResult[0].equals("OK") && splitResult != null){
                    String tempCompany = splitResult[1].substring(8);
                    User usr = new User(splitResult[1], tempCompany, splitResult[2], uniqueKey, splitResult[4], splitResult[3]);


                    Dialogs.LoginDialog(getApplicationContext()).hide();
                    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                    startActivityForResult(intent, 0);
                }else{
                   Dialogs.TextDialog(getApplicationContext(), "Verkeerde Logingegeven", Toast.LENGTH_LONG);
                    Dialogs.LoginDialog(getApplicationContext()).hide();
                }

                Dialogs.TextDialog(getApplicationContext(), "", Toast.LENGTH_LONG);
                Dialogs.LoginDialog(getApplicationContext()).hide();
            }
        }

        LoginAsyncTask Logintask = new LoginAsyncTask();
        Logintask.execute(Username, Password, Node, Token);
    }
}

GCMClientManager.java

package com.vict.voffice.utilities;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;

import java.io.IOException;


/**
 * Created by Kevin on 3/3/2015.
 */
public class GCMClientManager {
    // Constants
    public static final String TAG = "GCMClientManager";
    public static final String PROPERTY_REG_ID = "registration_id";
    private static final String PROPERTY_APP_VERSION = "6";
    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    // Member variables
    private GoogleCloudMessaging gcm;
    private String regid;
    private String projectNumber;
    private Activity activity;

    public static abstract class RegistrationCompletedHandler {
        public abstract void onSuccess(String registrationId, boolean isNewRegistration);
        public void onFailure(String ex) {
            // If there is an error, don't just keep trying to register.
            // Require the user to click a button again, or perform
            // exponential back-off.
            Log.e(TAG, ex);
        }
    }

    public GCMClientManager(Activity activity, String projectNumber) {
        this.activity = activity;
        this.projectNumber = projectNumber;
        this.gcm = GoogleCloudMessaging.getInstance(activity);
    }

    // Register if needed or fetch from local store
    public void registerIfNeeded(final RegistrationCompletedHandler handler) {
        if (checkPlayServices()) {
            regid = getRegistrationId(getContext());

            if (regid.isEmpty()) {
                registerInBackground(handler);
            } else { // got id from cache
                Log.i(TAG, regid);
                handler.onSuccess(regid, false);
            }
        } else { // no play services
            Log.i(TAG, "No valid Google Play Services APK found.");
        }
    }

    /**
     * Registers the application with GCM servers asynchronously.
     * <p>
     * Stores the registration ID and app versionCode in the application's
     * shared preferences.
     */
    private void registerInBackground(final RegistrationCompletedHandler handler) {
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                try {
                    if (gcm == null) {
                        gcm = GoogleCloudMessaging.getInstance(getContext());
                    }
                    regid = gcm.register(projectNumber);
                    Log.i(TAG, regid);

                    // Persist the regID - no need to register again.
                    storeRegistrationId(getContext(), regid);

                } catch (IOException ex) {
                    // If there is an error, don't just keep trying to register.
                    // Require the user to click a button again, or perform
                    // exponential back-off.
                    handler.onFailure("Error :" + ex.getMessage());
                }
                return regid;
            }

            @Override
            protected void onPostExecute(String regId) {
                if (regId != null) {
                    handler.onSuccess(regId, true);
                }
            }
        }.execute(null, null, null);
    }

    /**
     * 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.
     */
    public 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(context);
        if (registeredVersion != currentVersion) {
            Log.i(TAG, "App version changed.");
            return "";
        }
        return registrationId;
    }

    /**
     * Stores the registration ID and app versionCode in the application's
     * {@code SharedPreferences}.
     *
     * @param context application's context.
     * @param regId registration ID
     */
    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();
    }

    /**
     * @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 (PackageManager.NameNotFoundException e) {
            // should never happen
            throw new RuntimeException("Could not get package name: " + e);
        }
    }

    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 getContext().getSharedPreferences(context.getPackageName(),
                Context.MODE_PRIVATE);
    }

    /**
     * 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(getContext());
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(),
                        PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Log.i(TAG, "This device is not supported.");
            }
            return false;
        }
        return true;
    }

    private Context getContext() {
        return activity;
    }

    private Activity getActivity() {
        return activity;
    }
}

1 个答案:

答案 0 :(得分:1)

尝试将您的模拟器目标设置为Google API并添加Google    帐户。(在模拟器上添加帐户:设置 - &gt;帐户和同步)

相关问题