Location Based Push Notifications For Android

≯℡__Kan透↙ 提交于 2019-12-03 03:35:00

Yes, this is entirely possible, as long as I'm correctly interpreting what you are asking.

To accomplish this, you would send the GCM push notification to all of your users (unless you had a way, server-side of filtering some of them out). Then in your application, instead of just creating a Notification and passing it to the notification manager, you would first use the LocationManager (or the newer LocationServices API) to determine if the user is within the proper location first, and then just discard the GCM notification if they're not.

You'll need to take care of several things in order to do this:

  • Your AndroidManifest.xml will require several permission changes, both for the GCM changes, and for the Location access:

    <!-- Needed for processing notifications -->
    <permission android:name="com.myappname.permission.C2D_MESSAGE" android:protectionLevel="signature" />
    <uses-permission android:name="com.myappname.permission.C2D_MESSAGE" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    
    <!--  Needed for Location -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    
  • You'll also need to set up a Notification Receiver in the <application> section of the manifest:

    <receiver android:name="com.myappname.NotificationReceiver" android:permission="com.google.android.c2dm.permission.SEND">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            <category android:name="com.myappname" />
        </intent-filter>
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
            <category android:name="com.myappname" />
        </intent-filter>
    </receiver>
    
  • In addition, you'll need write your NotificationReceiver java class, and override the onReceive function:

    public class NotificationReceiver extends BroadcastReceiver {
        public void onReceive(final Context context, final Intent intent) {
    
            if ("com.google.android.c2dm.intent.REGISTRATION".equals(intent.getAction())) {
    
                handleRegistration(context, intent); // you'll have to write this function
    
            } else if ("com.google.android.c2dm.intent.RECEIVE".equals(intent.getAction())) {
    
                // the handle message function will need to check the user's current location using the location API you choose, and then create the proper Notification if necessary.
                handleMessage(context, intent);
    
            }
    }
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!