【发布时间】:2015-09-28 07:21:39
【问题描述】:
我有一个接收器捕获警报/系统广播,然后它必须从服务器获取当前数据,然后发送通知。我怎样才能做到这一点?请帮忙。谢谢。
【问题讨论】:
标签: android download broadcastreceiver server
我有一个接收器捕获警报/系统广播,然后它必须从服务器获取当前数据,然后发送通知。我怎样才能做到这一点?请帮忙。谢谢。
【问题讨论】:
标签: android download broadcastreceiver server
从广播接收器启动 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
}
}
【讨论】:
对于您的问题,您可以做的是执行 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());
【讨论】: