简体   繁体   English

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

[英]How to send Android Notifications to all my Users?

How can I generate Notifications to my Android App. 如何生成到我的Android应用程序的通知。 That notifications Shown to all my users who installed my app. 该通知显示给所有安装了我的应用程序的用户。 I am new to Android. 我是Android新手。 So, Please help me to move right way.... Thanks 所以,请帮助我朝正确的方向前进。

and my app only receiving Notifications through my Web application.Is it Possible How can I receive notifications from Web applications.... can any one please guide me. 并且我的应用程序仅通过Web应用程序接收通知。有可能如何从Web应用程序接收通知...。任何人都可以指导我。 How can I initiate my coding to achieve it. 如何启动我的编码来实现它。

hey I am Posting Complete code .... 嘿,我正在发布完整代码....

First activity - GcmBroadcastReciver 第一次活动-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 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); } } 

SimpleWakeFullReciver.java 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);
    }
}

Make a new activity and paste the following code.... 进行新的活动并粘贴以下代码。

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

also define this also in activity.. 在活动中也要定义它。

public static final String PROPERTY_REG_ID = "registration_id";
    private static final String PROPERTY_APP_VERSION = "appVersion";
    String SENDER_ID = "xyz";

you will get Sender id by registering your app with google ..... use following link for more information 您将通过在google上注册您的应用来获取发件人ID。..使用以下链接了解更多信息

http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/ 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 https://developers.google.com/cloud-messaging/android/client

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM