首页 > 解决方案 > 即使应用程序关闭,也可以通过在后台检查服务器 (volley) 中运行的服务显示 Android 应用程序的通知

问题描述

如问题中所述,我希望从应用程序(每天 21:30)运行后台进程,该应用程序向服务器发出凌空请求并根据结果显示通知。单击通知后,将打开一个特定链接(由应用程序处理)。

来自类的服务器请求和响应(通过异步 Volley)运行良好。链接处理程序也已设置。

我做了一项研究,对要使用的课程感到困惑。看来,我可以使用:

使用 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!");
        }
    };
}

什么是正确的方法以及如何实施?如何启动可点击通知?

标签: androidandroid-notificationsalarmmanagerbackground-process

解决方案


Android 有更新更好的解决方案,完全适合您的需求

WorkManager API 是所有以前 Android 后台调度 API 的合适且推荐的替代品

你可以在这里查看官方主题:工作经理


推荐阅读