向所有设备发送通知

时间:2015-04-16 17:59:05

标签: android notifications alert

我有一个应用程序可以使用Google Maps API将标记添加到地图中,我正在尝试向添加了新标记时安装了应用程序的所有设备发送通知,这适用于目前正在使用该应用程序而不是我的其他没有加载应用程序的设备,我还需要做些什么来将其注册到其他设备吗?

以下是连接服务器并添加标记的代码,该标记调用showNotification方法:

try
{
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost("http://***.***.***.**/markerLocation/save.php");
    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    HttpResponse response = httpClient.execute(httpPost);

    HttpEntity entity = response.getEntity();

    is = entity.getContent();

    String msg = "Data entered successfully";

    //The method call that makes the alert notification
    ShowNotification(name);
    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}

以下是创建警报的代码:

public  void ShowNotification(String name)
{
    // define sound URI, the sound to be played when there's a notification
    Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    // intent triggered, you can add other intent for other actions
    Intent intent = new Intent(GoogleMapsActivity.this, NotificationReceiver.class);
    PendingIntent pIntent = PendingIntent.getActivity(GoogleMapsActivity.this, 0, intent, 0);

    // this is it, we'll build the notification!
    // in the addAction method, if you don't want any icon, just set the first param to 0
    Notification mNotification = new Notification.Builder(this)


            .setContentTitle(name)
            .setContentText(name + " has added a marker in your area")
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentIntent(pIntent)
            .setSound(soundUri)

            .addAction(0, "View", pIntent)
            .addAction(0, "Remind", pIntent)

            .build();

    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    // If you want to hide the notification after it was selected, do the code below
    mNotification.flags |= Notification.FLAG_AUTO_CANCEL;

    notificationManager.notify(0, mNotification);
}    

3 个答案:

答案 0 :(得分:1)

首先你需要一个Push服务来警告你的新标记的其他设备,然后你需要一个BroadCastReceiver来接收推送消息,并在收到它的所有设备上发出通知,我很乐意解释这个并写一些您的示例代码,但在Android Docus中广泛解释,为什么要重新发明轮子?

看看这个页面,它有你需要的一切:

Google Cloud Messaging GCM

答案 1 :(得分:0)

我认为你没有理解两种通知类型的功能。这样做的方法是在服务器上存储已请求接收通知的所有用户的设备ID。然后,您从服务器而不是从应用程序启动所有设备的通知。从应用程序发起的通知仅用于在我们应用程序的UI之外的设备上显示消息

看看这个:https://developer.android.com/google/gcm/index.html

答案 2 :(得分:0)

您需要的是对推送通知的某种支持,Android的一个明显选择是Google Cloud Messaging(GCM)。

由于您有可用的服务器,您可以自己定制服务器端来管理接收通知的设备(有很多教程)。

如果您匆忙并且只想让工作正常,您可以使用parse.com。它们允许您免费向1 mil独特设备(通过GCM)发送推送消息。这里的好处是,它们可以更轻松地设置和过滤应该接收通知的设备。