android - 即使应用程序关闭,也可以通过在后台检查服务器 (volley) 中运行的服务显示 Android 应用程序的通知
问题描述
如问题中所述,我希望从应用程序(每天 21:30)运行后台进程,该应用程序向服务器发出凌空请求并根据结果显示通知。单击通知后,将打开一个特定链接(由应用程序处理)。
来自类的服务器请求和响应(通过异步 Volley)运行良好。链接处理程序也已设置。
我做了一项研究,对要使用的课程感到困惑。看来,我可以使用:
- 服务或
- 广播接收器(带有AlarmManager)
使用 AlarmManager(receiver
在清单中添加了标签),我设置了在MainActivity.java的onCreate中调用的以下方法:
private void setAlarms()
{
AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(this, NewNewsNotification.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0, i, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 30);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
1000 * 60 * 60, alarmIntent);
if (alarmMgr!= null) {
alarmMgr.cancel(alarmIntent);
}
}
新新闻通知.java
@Override
public void onReceive(Context context, Intent intent) {
rCtx= context;
fetch_last_update();
}
public void fetch_last_update()
{
VolleyCallback();
VolleyService = new AsyncJsonFetch(ResultCallback, rCtx);
try {
JSONObject sendObj = new JSONObject();
mVolleyService.postDataVolley("POSTCALL", "news", sendObj);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void VolleyCallback()
{
pResultCallback = new AsyncJsonData() {
@Override
public void notifySuccess(String requestType, JSONObject response) throws JSONException {
int stat = (int) response.get("status");
if (stat == 1) {
JSONObject msgJSON = (JSONObject) response.get("msg");
Log.d(TAG, "msgJSON: "+msgJSON);
/*The above log is working correctly. PROCESS THE JSON HERE AND GENERATE THE NOTIFICATION*/
}
}
@Override
public void notifyError(String requestType, VolleyError error) {
Log.d(TAG, "Volley requester " + requestType);
Log.d(TAG, "Volley JSON post" + "That didn't work!");
}
};
}
什么是正确的方法以及如何实施?如何启动可点击通知?
解决方案
推荐阅读
- html - 将文本放在背景图像上
- java - 将 MySQL 连接到 java 应用程序 - VPS (ubuntu)
- python - 浮点转换的自定义语言环境配置
- java - JAVA客户端并发修改异常到客户端通过服务器
- cython - 在 Juypter 中使用 cython:ModuleNotFoundError:没有名为 '_cython_magic 的模块
- c# - 具有子对象的实体更新是否需要初始查询
- php - 上传图片 PHP SQL
- git - 管理环境分支
- javascript - 如何使我的所有路由都具有 https 并强制 http 到 https?
- phaser-framework - 将 Phaser 3 游戏嵌入现有的秘银网站