Android 基于位置的推送通知

Location Based Push Notifications For Android

是否可以在不使用 Parse 等第三方推送通知服务的情况下为 android 设备发送基于位置的推送通知?我想向我的用户发送推送通知,而不会因为他们不在某个区域而收到与该特定用户无关的通知而烦恼。此外,我可以根据时间间隔获取用户位置,但如果可能的话,我宁愿采用不同的方式。

是的,这完全有可能,只要我正确地解释了你的问题。

为此,您需要将 GCM 推送通知发送给所有用户(除非您有办法在服务器端过滤掉其中的一些用户)。然后在您的应用程序中,不是仅仅创建一个 Notification 并将其传递给通知管理器,而是首先使用 LocationManager(或更新的 LocationServices API)来确定用户是否在正确的位置,然后如果不是,则丢弃 GCM 通知。

要执行此操作,您需要注意几件事:

  • 您的 AndroidManifest.xml 需要更改几项权限,包括 GCM 更改和位置访问权限:

    <!-- 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" />
    
  • 您还需要在清单的 <application> 部分设置通知接收器:

    <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>
    
  • 此外,您需要编写 NotificationReceiver java class,并覆盖 onReceive 函数:

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