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

时间:2016-01-04 07:17:43

标签: android google-cloud-messaging

如何为Android应用生成通知。该通知显示给安装了我的应用的所有用户。我是Android新手。所以,请帮我正确行动......谢谢

我的应用程序只通过我的Web应用程序接收通知。是否可能如何从Web应用程序接收通知....任何人都可以指导我。如何启动编码来实现它。

1 个答案:

答案 0 :(得分:0)

嘿我发布完整代码....

第一项活动 - 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");
    }
}
  1. GcmIntentServicePush.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);
        }
    }
    
  2. SimpleWakeFullReciver.java

        import android.content.Context;
        import android.content.Intent;
        import android.os.SystemClock;
        import android.support.v4.content.WakefulBroadcastReceiver;
        import android.util.Log;
    
        public class SimpleWakefulReceiver extends WakefulBroadcastReceiver {
            @Override
            public void onReceive(Context context, Intent intent) {
                // This is the Intent to deliver to our service.
                Intent service = new Intent(context, SimpleWakefulService.class);
                // Start the service, keeping the device awake while it is launching.
                Log.e("SimpleWakefulReceiver", "Starting service @ " + SystemClock.elapsedRealtime());
                startWakefulService(context, service);
            }
        }
    
    SimpleWakefullService
    
    
    import android.app.IntentService;
    import android.content.Intent;
    import android.os.SystemClock;
    import android.util.Log;
    
    public class SimpleWakefulService extends IntentService {
        public SimpleWakefulService() {
            super("SimpleWakefulService");
        }
    
        @Override
        protected void onHandleIntent(Intent intent) {
            // At this point SimpleWakefulReceiver is still holding a wake lock
            // for us.  We can do whatever we need to here and then tell it that
            // it can release the wakelock.  This sample just does some slow work,
            // but more complicated implementations could take their own wake
            // lock here before releasing the receiver's.
            //
            // Note that when using this approach you should be aware that if your
            // service gets killed and restarted while in the middle of such work
            // (so the Intent gets re-delivered to perform the work again), it will
            // at that point no longer be holding a wake lock since we are depending
            // on SimpleWakefulReceiver to that for us.  If this is a concern, you can
            // acquire a separate wake lock here.
            for (int i=0; i<5; i++) {
                Log.e("SimpleWakefulReceiver", "Running service " + (i+1)
                        + "/5 @ " + SystemClock.elapsedRealtime());
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                }
            }
            Log.e("SimpleWakefulReceiver", "Completed service @ " + SystemClock.elapsedRealtime());
            SimpleWakefulReceiver.completeWakefulIntent(intent);
        }
    }
    

    制作新活动并粘贴以下代码....

    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";
    

    您可以通过google注册您的应用来获取发件人ID 使用以下链接获取更多信息

    http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/

    https://developers.google.com/cloud-messaging/android/client