0

如果 firebase 数据库有任何更改,我想向用户发送通知。我试过使用Broadcast-Receiver, Service, Work-Manager, Alarm-Manager. 但它们都不是完美的。它仅在应用程序正在运行或在后台运行并且在应用程序关闭时也可以在某些设备中工作[在 android 7 中测试] 。但是在 android 10 [在三星和小米测试] 中,应用程序关闭时它不起作用。当我在小米的应用程序中关闭电池保护程序时,它会在关闭应用程序后的某个时间工作,然后停止工作。有人说,你有turn-off battery saverandturn-on auto-start mode in Xiaomido something in other manufacturers phone。但是有很多应用程序显示通知,即使我已经超过 10/15 天没有打开应用程序并且我已经检查了那些省电模式和自动启动关闭的应用程序的应用程序信息[在 Xiaomi-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 中更改数据时通知用户]。

4

2 回答 2

0

当应用程序被杀死或关闭时,上面给出的所有这些都不起作用。然后我尝试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

于 2021-01-30T15:55:55.413 回答
0

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

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

于 2021-01-20T08:22:27.843 回答