使用GCM将推送通知从一个活动发送到另一个活动 - Android Studio

时间:2016-03-12 17:18:50

标签: java android android-studio google-cloud-messaging google-play-services

我目前正在Android Studio中编写Android应用程序。我正在尝试使用GCM实现推送通知服务。推送通知将从一个用户帐户发送到另一个用户帐户,第二个用户将接受,然后将链接这两个帐户。我使用000webhost.com在mySQL服务器上设置了两个帐户。我尝试按照本教程link来实施GCM,但我无法弄清楚如何发送和接收通知。 这是我获得注册ID的地方:

package com.jack.pointcollector;

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.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 com.google.android.gms.iid.InstanceID;

import java.io.IOException;

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 = "appVersion";
    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;

    // Member variables
    private GoogleCloudMessaging gcm;
    private String regID;
    private String projectNumber;
    private Activity activity;

    public GCMClientManager(Activity activity, String projectNumber) {
        this.activity = activity;
        this.projectNumber = projectNumber;
        this.gcm = GoogleCloudMessaging.getInstance(activity);
    }
    /**
    * @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);
        }
    }
    // 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());
                    }
                    InstanceID instanceID = InstanceID.getInstance(getContext());
                    regID = instanceID.getToken(projectNumber, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
                    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.
     */
    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(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.apply();
    }
    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;
    }
    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);
        }
    }
}

这是我的GCMListnerService类:

package com.jack.pointcollector;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;

import com.google.android.gms.gcm.GcmListenerService;

public class PushNotificationManager extends GcmListenerService{
    @Override
    public void onMessageReceived(String from, Bundle data) {
        childNotification(from);
        super.onMessageReceived(from, data);
    }
    private AlertDialog childNotification(String name) {
        AlertDialog.Builder response = new AlertDialog.Builder(this.getBaseContext());
        response.setMessage(name + " has added you as their child. Is this correct?");
        response.setTitle("Point Collector");
        response.setPositiveButton("Correct", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        response.setNegativeButton("I don't know them", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        response.setCancelable(false);
        return response.create();
    }
}

最后是我要从

发送通知的课程
package com.jack.pointcollector;

import android.app.Activity;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class Add_Child extends Activity implements View.OnClickListener {
    Button bAddChild;
    EditText etUsername, etEmail;
    String PROJECT_NUMBER = "76770391940";

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

        bAddChild = (Button) findViewById(R.id.addButton);
        etUsername = (EditText) findViewById(R.id.name);
        etEmail = (EditText) findViewById(R.id.child_email);

        bAddChild.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.addButton:
                GCMClientManager pushClientManager = new GCMClientManager(this, PROJECT_NUMBER);
                pushClientManager.registerIfNeeded(new GCMClientManager.RegistrationCompletedHandler() {
                    @Override
                    public void onSuccess(String registrationId, boolean isNewRegistration) {
                        Log.d("Registration id", registrationId);
                        //send this registrationId to your server
                        toServer(registrationId);
                    }
                    @Override
                    public void onFailure(String ex) {
                        super.onFailure(ex);
                    }
                });

                break;
        }
    }
    private void toServer(final String id) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                try {
                    URL url = new URL("http://point_collector.netau.net/");
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setReadTimeout(15000);
                    conn.setConnectTimeout(15000);
                    conn.setRequestMethod("POST");
                    conn.setDoInput(true);
                    conn.setDoOutput(true);

                    Uri.Builder builder = new Uri.Builder().appendQueryParameter("id", id);
                    String query = builder.build().getEncodedQuery();

                    OutputStream os = conn.getOutputStream();
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                    writer.write(query);
                    writer.flush();
                    writer.close();
                    os.close();
                    //Gets the response code to ensure this was succesful.
                    int code = conn.getResponseCode();
                    Log.d("code", Integer.toString(code));
                    conn.connect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
        };
    }
}

我看过很多视频教程以及在线教程,但根本无法弄明白。如果有人能帮助我,我会非常感激。

由于

编辑 - 如果任何人都可以提供一些见解,仍然真的坚持这个!

0 个答案:

没有答案