Android 广播接收器下载数据并发送通知
我有一个接收器,它捕捉报警/系统广播,然后它必须从服务器获取当前数据,然后发送通知。我怎样才能做到这一点?请帮忙。谢谢。对于您的问题,您可以执行AsyncTask,该任务将以OnReceive方法从服务器获取数据,当您在检索数据时获得成功时,您可以在那里设置通知生成器 下面的代码可用于显示通知Android 广播接收器下载数据并发送通知,android,download,broadcastreceiver,server,Android,Download,Broadcastreceiver,Server,我有一个接收器,它捕捉报警/系统广播,然后它必须从服务器获取当前数据,然后发送通知。我怎样才能做到这一点?请帮忙。谢谢。对于您的问题,您可以执行AsyncTask,该任务将以OnReceive方法从服务器获取数据,当您在检索数据时获得成功时,您可以在那里设置通知生成器 下面的代码可用于显示通知 NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon
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());
从广播接收器启动意图服务。使用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