使用 json/php 的 Android Studio 简单通知

Android Studio simple notification using json/php

提问人:Ben 提问时间:2/4/2017 更新时间:2/4/2017 访问量:522

问:

我构建了一个简单的 android 应用程序,仅供内部使用。这个应用程序每隔几秒钟发送一次数据(GPS坐标),通过一个简单的PHP脚本保存到mysql。如果 json 有一定的响应,我确实需要用户的 Android 设备显示预设通知(如果手机处于待机状态、查看其他应用程序等,则会显示该通知)。

我看过的大多数教程都建议这是使用 GCM 完成的。我本来以为,“自我推送”通知应该比这更容易。

例如 如果 JSON 回复“notify: 1”,则 androids 通知将显示“有作业在等待”。

有没有一种简单的方法可以做到这一点?如果是这样,请指导我一个简单的解决方案。

new HttpRequestTask(
                new HttpRequest("https://www.autoflora.net/driver/gps.php?Driver_ID=" + driver_id + "&latlong=" +
                        location.getLatitude() + "*" + location.getLongitude(), HttpRequest.POST, "{ \"some\": \"data\" }"),
                new HttpRequest.Handler() {
                    @Override
                    public void response(HttpResponse response) {
                        if (response.code == 200) {
                            Log.d(this.getClass().toString(), "Request successful!");
                        } else {
                            Log.e(this.getClass().toString(), "Request unsuccessful: " + response);
                        }
                    }
                }).execute();
php json android-studio 推送 通知

评论


答:

0赞 dpaksoni 2/4/2017 #1

从 httpresponse 获取响应正文后。 从中创建 JSON 对象, 例如

...
JSON response = new JSON(responseBody); //responseBody is what you received from server

if(response.has("notify") && (response.getInt("notify") == 1))
{
  NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context);
  notificationBuilder.setContentTitle(title); //Set notification title
  notificationBuilder.setContentText(message); // set notification text

  NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

  notificationManager.notify(0 /* ID of notification */, 
  notificationBuilder.build());

}
...

希望这会有所帮助