如何向我的所有用户发送Android通知?

如何向我的所有用户发送Android通知?,android,google-cloud-messaging,Android,Google Cloud Messaging,我如何为我的Android应用程序生成通知。该通知将显示给安装我的应用程序的所有我的用户。我是Android新手。所以,请帮我向正确的方向移动。。。。谢谢 我的应用程序只能通过我的Web应用程序接收通知。我如何才能从Web应用程序接收通知。。。。谁能给我指路吗。如何启动我的编码来实现它。嘿,我正在发布完整的代码 第一个活动-GcmBroadcastReciver import com.example.vchat.R; import android.annotation.SuppressLint

我如何为我的Android应用程序生成通知。该通知将显示给安装我的应用程序的所有我的用户。我是Android新手。所以,请帮我向正确的方向移动。。。。谢谢


我的应用程序只能通过我的Web应用程序接收通知。我如何才能从Web应用程序接收通知。。。。谁能给我指路吗。如何启动我的编码来实现它。

嘿,我正在发布完整的代码

第一个活动-GcmBroadcastReciver

import com.example.vchat.R;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Notification;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.v4.content.WakefulBroadcastReceiver;


@TargetApi(Build.VERSION_CODES.HONEYCOMB) public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
    @SuppressLint("NewApi") @Override
    public void onReceive(Context context, Intent intent) 
    {        
        ComponentName comp = new ComponentName(context.getPackageName(),
        GcmIntentServicePush.class.getName());        
        startWakefulService(context, (intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);

        Notification notification = new Notification.Builder(context).setSmallIcon(R.drawable.app_icon).build();
        // Show controls on lock screen even when user hides sensitive content.
        //.setVisibility(Notification.VISIBILITY_PUBLIC)
        //.setSmallIcon(R.drawable.logo).build();
        // Add media control buttons that invoke intents in your media service
        //.addAction(R.drawable.ic_prev, "Previous", prevPendingIntent) // #0
        //.addAction(R.drawable.ic_pause, "Pause", pausePendingIntent)  // #1
        //.addAction(R.drawable.ic_next, "Next", nextPendingIntent)     // #2
        // Apply the media style template
        //.setStyle(new Notification.MediaStyle()
        //.setShowActionsInCompactView(1 /* #1: pause button */)
        //.setMediaSession(mMediaSession.getSessionToken())
       // .setContentTitle("Wonderful music")
       // .setContentText("My Awesome Band")
        //.setLargeIcon(albumArtBitmap)
        //.build();
        //Toast.makeText(GcmBroadcastReceiver.this, "received push", Toast.LENGTH_LONG).show();
        //Toast.makeText(context, "Pushnotification received", 3500).show();//("Push received !", "Push");
    }
}
  • gcminentservicepush.java

    import com.example.vchat.Friends_listing;
    import com.example.vchat.R;
    import com.google.android.gms.gcm.GoogleCloudMessaging;
    
    public class GcmIntentServicePush extends IntentService {
        public static final int NOTIFICATION_ID = 1;
        private NotificationManager mNotificationManager;
        private final static String TAG = "GcmIntentService";
    
        public GcmIntentServicePush() {
            super("GcmIntentService");
        }
    
        @Override
        protected void onHandleIntent(Intent intent) {
            Bundle extras = intent.getExtras();
            Log.e(TAG, "Notification Data Json :" + extras.getString("message"));
            GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
            String messageType = gcm.getMessageType(intent);
    
    
    
    
    
    
            if (!extras.isEmpty()) {
                if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
                        .equals(messageType)) {
                    sendNotification("Send error: " + extras.toString());
                } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
                        .equals(messageType)) {
                    sendNotification("Deleted messages on server: "
                            + extras.toString()); // If it's a regular GCM message,
                                                    // do some work.
                } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
                        .equals(messageType)) {
                    // This loop represents the service doing some work.
                    for (int i = 0; i < 5; i++) {
                        Log.e(TAG,
                                " Working... " + (i + 1) + "/5 @ "
                                        + SystemClock.elapsedRealtime());
                        try {
                            Thread.sleep(5000);
    
                        } catch (InterruptedException e) {
    
                        }
                    }
                    Log.e(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
                    sendNotification(extras.getString("message"));
                }
            }
            // Release the wake lock provided by the WakefulBroadcastReceiver.
            GcmBroadcastReceiver.completeWakefulIntent(intent);
        } 
        // Put the message into a notification and post it.
        // This is just one simple example of what you might choose to do with
        // a GCM message.
        private void sendNotification(String msg) 
        {
    //      Log.e("msgg",""+msg.toString());
            mNotificationManager = (NotificationManager) this
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                    new Intent(this, Friends_listing.class), 0);
    
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                    this)
                    .setSmallIcon(R.drawable.app_icon)
                    .setContentTitle("Vchat")
                    .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
                    .setContentText(msg);
    //              .setDefaults(
    //                      Notification.DEFAULT_SOUND
    //                              | Notification.DEFAULT_VIBRATE);
    
            mBuilder.setContentIntent(contentIntent);
            mBuilder.setAutoCancel(true);
    
             Notification notification = mBuilder.build();
             notification.sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.push_sound);
    
            mNotificationManager.notify(NOTIFICATION_ID, notification);
        }
    }
    
    在“活动”中也定义此项

    public static final String PROPERTY_REG_ID = "registration_id";
        private static final String PROPERTY_APP_VERSION = "appVersion";
        String SENDER_ID = "xyz";
    
    您将通过向谷歌注册应用程序获得发件人id。。。。。 使用以下链接了解更多信息


    可能重复使用解析推送通知。您将获得有关实现gcm的完整教程-
    if (checkPlayServices()) {
                gcm = GoogleCloudMessaging.getInstance(this);
                regid = getRegistrationId(context);
                Log.e("regid", ">>>>" + regid);
                try {
                    sharedPreference_Main.registeration_id("" + regid);
                    shared_preference.registeration_id("" + regid);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                SharedPreferences pref = getApplicationContext()
                        .getSharedPreferences("MyPref", 0);
                pref.edit().clear().commit();
                Editor editor = pref.edit();
                editor.putString("PROPERTY_REG_ID", regid);
                editor.commit();
    
                if (regid.isEmpty()) {
                    registerInBackground();
                }
            } else {
                Log.e(TAG, "No valid Google Play Services APK found.");
            }
    
        }
    
        private String getRegistrationId(Context context) {
            final SharedPreferences prefs = getGCMPreferences(context);
            String registrationId = prefs.getString(PROPERTY_REG_ID, "");
    
            if (registrationId.isEmpty()) {
                Log.e(TAG, "Registration not found.");
                return "";
            }
    
            int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION,
                    Integer.MIN_VALUE);
            int currentVersion = getAppVersion(context);
            if (registeredVersion != currentVersion) {
                Log.e(TAG, "App version changed.");
                return "";
            }
            return registrationId;
        }
    
        private boolean checkPlayServices() {
            int resultCode = GooglePlayServicesUtil
                    .isGooglePlayServicesAvailable(this);
            Log.e("resultCode: ", "" + resultCode);
            if (resultCode != ConnectionResult.SUCCESS) {
                if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                    GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                            PLAY_SERVICES_RESOLUTION_REQUEST).show();
                } else {
                    Log.e(TAG, "This device is not supported.");
                    finish();
                }
                return false;
            }
            return true;
        }
    
        private SharedPreferences getGCMPreferences(Context context) {
            return getSharedPreferences(Splash_MainActivity.class.getSimpleName(),
                    Context.MODE_PRIVATE);
        }
    
        @SuppressWarnings("unchecked")
        private void registerInBackground() {
            Log.e("msg", "registerInBackground");
            new AsyncTask() {
                @SuppressWarnings("unused")
                protected Object doInBackground(Object... params) {
                    String msg = "";
                    try {
                        if (gcm == null) {
                            gcm = GoogleCloudMessaging.getInstance(context);
                        }
                        regid = gcm.register(SENDER_ID);
                        sharedPreference_Main.registeration_id("" + regid);
                        shared_preference.registeration_id("" + regid);
                        msg = "Device registered, registration ID=" + regid;
                        Log.e("msg", msg);
                        SharedPreferences pref = getApplicationContext()
                                .getSharedPreferences("MyPref", 0);
                        // pref.edit().clear().commit();
                        Editor editor = pref.edit();
                        editor.putString("PROPERTY_REG_ID", regid);
                        editor.commit();
                        sendRegistrationIdToBackend();
                        storeRegistrationId(context, regid);
                    } catch (IOException ex) {
                        msg = "Error :" + ex.getMessage();
                        Log.e("msg", msg);
                    }
                    return msg;
                }
    
                protected void onPostExecute(String msg) {
                    // mDisplay.append(msg + "\n");
                    Log.e("msg", msg);
                }
            }.execute(null, null, null);
        }
    
        protected void sendRegistrationIdToBackend() {
            // TODO Auto-generated method stub
    
        }
    
        private void storeRegistrationId(Context context, String regId) {
            Log.e("storeRegistrationId : ", regId);
            VChatPrefrence.getInstance(getApplicationContext()).setDeviceId(regId);
            shared_preference.deviceId(regId);
    
            final SharedPreferences prefs = getGCMPreferences(context);
            int appVersion = getAppVersion(context);
            Log.e(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();
        }
    
        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);
            }
        }
    
    public static final String PROPERTY_REG_ID = "registration_id";
        private static final String PROPERTY_APP_VERSION = "appVersion";
        String SENDER_ID = "xyz";