当应用程序在所有设备上关闭时,有没有办法显示通知?

Isn't there any way to show notification when app is closed in all devices?

如果 firebase 数据库发生任何变化,我想向用户发送通知。我试过使用 Broadcast-ReceiverServiceWork-ManagerAlarm-Manager。但其中 none 完美运行。它仅在应用程序处于 运行 或在后台运行并且在 某些设备[在 android 7] 关闭应用程序时也能正常工作。但是在android 10[在三星和小米测试],当应用程序关闭时它不工作。当我在小米的应用程序中关闭节电模式时,它会在关闭应用程序后的某个时间运行,然后停止运行。有人说,你有turn-off battery saverturn-on auto-start modein Xiaomido somethingin other manufacturers phone。但是 即使我超过 10/15 天没有打开应用程序,仍有许多应用程序显示通知并且我已经检查了这些应用程序的应用程序信息省电模式开启和自动启动关闭[已在小米-android10] 中查看。我究竟做错了什么? 服务:

public class ServiceManager extends Service {


public ServiceManager() {}

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onCreate() {
    getLastModifiedTime2(new HomePage.MyCallback() {
        @Override
        public void onCallback(String roll) {
            SharedPreferences spExtra = getSharedPreferences("spExtra",MODE_PRIVATE);
            if(!Objects.equals(spExtra.getString("1", "No changes"), roll)){
                SharedPreferences.Editor editor = spExtra.edit();
                editor.putString("1",roll);
                editor.apply();
                showNotification(getApplicationContext());
                //
            }
        }
    });
}

@Override
public void onDestroy() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startid) {
    System.out.println("called start command");
    //
    getLastModifiedTime2(new HomePage.MyCallback() {
        @Override
        public void onCallback(String roll) {
            SharedPreferences spExtra = getSharedPreferences("spExtra",MODE_PRIVATE);
            if(!Objects.equals(spExtra.getString("1", "No changes"), roll)){
                SharedPreferences.Editor editor = spExtra.edit();
                editor.putString("1",roll);
                editor.apply();
                showNotification(getApplicationContext());
            }
        }
    });
    //
    return START_STICKY;
}

private void stopService() {
}
 //not showing the method getlastmodifiedtime2 and shownotification;
}

并启动以下服务:

startService(new Intent(this, ServiceManager.class));

工作经理:

public class UploadWorker extends Worker {

public UploadWorker(
        @NonNull Context context,
        @NonNull WorkerParameters workerParams){
    super(context, workerParams);
}

@NonNull
@Override
public Result doWork() {
    System.out.println("UploadWorker called");
    getLastModifiedTime2(new HomePage.MyCallback() {
        @Override
        public void onCallback(String roll) {
            SharedPreferences spExtra = getApplicationContext().getSharedPreferences("spExtra",MODE_PRIVATE);
            if(!Objects.equals(spExtra.getString("1", "No changes"), roll)){
                SharedPreferences.Editor editor = spExtra.edit();
                editor.putString("1",roll);
                editor.apply();
                showNotification(getApplicationContext());
                //
            }
            //startNewRequest();
        }
    });
    return Result.success();
    //return Result.Retry.retry();
}
//not showing function getlastmodifiedtime2 and shownotification
}

呼叫工作人员如下:

PeriodicWorkRequest workRequest = new PeriodicWorkRequest
                .Builder(UploadWorker.class,15,TimeUnit.MINUTES).build();
        WorkManager.getInstance(this).enqueueUniquePeriodicWork("firebaseTest",
                ExistingPeriodicWorkPolicy.KEEP,workRequest);

和警报管理器代码:

Calendar cal = Calendar.getInstance();
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 12);
    calendar.set(Calendar.MINUTE, 25);
    calendar.set(Calendar.SECOND, 30);

    Intent intent = new Intent(HomePage.this, ServiceManager.class);
    PendingIntent pintent = PendingIntent.getService(HomePage.this, 0, intent, 0);
    AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    System.out.println("called alarm-intent");
    System.out.println("called"+cal.getTimeInMillis());
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 60*1000, pintent);

当应用程序关闭时,所有这些都不起作用。有人说使用前台服务,但它不会一直显示通知吗?我应该使用什么流程来完成我的工作[在 firebase 中更改数据时通知用户]。

您需要显示通知,请参阅此 link

前台服务是一个单独的问题。在 Oreo+ 设备中,当应用程序处于后台或关闭时,服务不能 运行 除非 服务在前台启动,其中它们需要在整个时间显示的通知服务是运行宁。

当应用程序被终止或关闭时,上面给出的所有这些都不起作用。然后我尝试了 Firebase cloud messaging 并且即使应用程序被关闭或被杀死,它仍然有效[在 android 7,10 中测试]。

RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(this);

--

public void sendNotificationToUser() {
        JSONObject mainObj = new JSONObject();
        try {
            mainObj.put("to", "/topics/" + topic_name);//
            JSONObject notificationObj = new JSONObject();
            notificationObj.put("title", "About title");
            notificationObj.put("body", "Enter you message here");
            mainObj.put("notification", notificationObj);

            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, value,
                    mainObj, new Response.Listener<JSONObject>() {//value="https://fcm.googleapis.com/fcm/send"
                @Override
                public void onResponse(JSONObject response) {
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {

                    Map<String, String> header = new HashMap<>();
                    header.put("content-type", "application/json");
                    header.put("authorization", "key=" + server-key);
                    return header;
                }
            };
            Toast.makeText(this, "Successfully added", Toast.LENGTH_SHORT).show();
            requestQueue.add(jsonObjectRequest);
            //
    }
}

确保导入

implementation 'com.mcxiaoke.volley:library:1.0.19'

不要将您的服务器密钥放入您的应用程序中。您可以为此使用 Firebase cloud function[不是免费的]。上面的代码将向所有订阅 topic_name.

的用户发送通知