【问题标题】:Broadcast receiver to download data and send a notification广播接收器下载数据并发送通知
【发布时间】:2015-09-28 07:21:39
【问题描述】:

我有一个接收器捕获警报/系统广播,然后它必须从服务器获取当前数据,然后发送通知。我怎样才能做到这一点?请帮忙。谢谢。

【问题讨论】:

    标签: android download broadcastreceiver server


    【解决方案1】:

    从广播接收器启动 Intent 服务。使用 HTTP 请求从服务器下载数据。然后解析响应并相应地放置通知..

     public class MyBroadcastReceiver extends BroadcastReceiver {
           @Override
           public void onReceive(Context context, Intent intent) {
           ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
           final NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
           final NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
           if (wifi.isConnected() || mobile.isConnected()) {
              Intent intent=new Intent(context,DownloadService.class);
              context.startService(intent);
           }
           else {
              Toast.makeText(context, "No Network Connectivity", Toast.LENGTH_SHORT).show();
           }
        }
     }
    

    下载服务类:

     public class DownloadService extends IntentService{
          String response = "";
          private NotificationManager mNotificationManager;
          public DownloadService() {
              super("DownloadService");
          }
    
          @Override
          protected void onHandleIntent(Intent intent) {
                // Get the data
                // Parse the data
                // Put the notificaton using NotificationManager
          }
     }
    

    【讨论】:

    • IntentService 会立即开始运行,还是必须等待系统稍后安排?
    • IntentService 一收到广播意图就会被调用
    【解决方案2】:

    对于您的问题,您可以做的是执行 AsyncTask,它将在 OnReceive 方法中从您的服务器获取数据,当您在检索数据时成功时,您可以在那里设置您的通知构建器。

    以下代码可用于显示通知

    NotificationCompat.Builder mBuilder =   new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_launcher) // notification icon
                .setContentTitle("Notification!") // title for notification
                .setContentText("Hello word") // message for notification
                .setAutoCancel(true); // clear notification after click
    Intent intent = new Intent(this, MainActivity.class);
    PendingIntent pi = PendingIntent.getActivity(this,0,intent,Intent.FLAG_ACTIVITY_NEW_TASK);
    mBuilder.setContentIntent(pi);
    NotificationManager mNotificationManager =
                        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(0, mBuilder.build());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多