监听器位于WorkManager内部

huangapple 未分类评论56阅读模式
英文:

Listener inside of a WorkManager

问题

我想要在用户关闭应用程序后仍然向他们发送通知。我尝试过 BroadcastReceiver、Service 和 Worker,但是在用户滑动关闭应用程序后,通知就不再显示。我该如何保持我的 ValueEventListener 处于活动状态?

public class NotificationWorker extends Worker {
    private static int notificationId;
    public NotificationWorker(
            @NonNull Context context,
            @NonNull WorkerParameters params) {
        super(context, params);
    }

    @Override
    public Result doWork() {
        createNotificationChannel(getApplicationContext());
        final String username = getInputData().getString("username");
        final NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), "Catting Around")
                .setSmallIcon(R.drawable.logo)
                .setContentTitle("Catting Around")
                .setPriority(NotificationCompat.PRIORITY_DEFAULT);
        final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getApplicationContext());
        FirebaseDatabase database = FirebaseDatabase.getInstance();
        final DatabaseReference latest = database.getReference(username + "/latest");
        latest.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                String name = snapshot.getValue(String.class);
                if (!name.equals(username)) {
                    latest.setValue(username);
                    notificationManager.notify(notificationId++, builder.setContentText("You received a new message from " + name + "!").build());
                }
            }
            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(getApplicationContext(), "Could not connect to the database...", Toast.LENGTH_SHORT).show();
            }
        });
        return Result.success();
    }
    private void createNotificationChannel(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "Catting Around";
            String description = "Catting Around";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel("Catting Around", name, importance);
            channel.setDescription(description);
            NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }
}
英文:

I want to give the user notifications, even after they have closed the app. I have tried a BroadcastReceiver, Service and a Worker, but the notifications stop coming in after the user swipes the app away. How do I keep my ValueEventListener alive?

public class NotificationWorker extends Worker {
    private static int notificationId;
    public NotificationWorker(
            @NonNull Context context,
            @NonNull WorkerParameters params) {
        super(context, params);
    }

    @Override
    public Result doWork() {
        createNotificationChannel(getApplicationContext());
        final String username=getInputData().getString("username");
        final NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), "Catting Around")
                .setSmallIcon(R.drawable.logo)
                .setContentTitle("Catting Around")
                .setPriority(NotificationCompat.PRIORITY_DEFAULT);
        final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getApplicationContext());
        FirebaseDatabase database=FirebaseDatabase.getInstance();
        final DatabaseReference latest = database.getReference(username + "/latest");
        latest.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                String name=snapshot.getValue(String.class);
                if(!name.equals(username)) {
                    latest.setValue(username);
                    notificationManager.notify(notificationId++, builder.setContentText("You received a new message from " + name + "!").build());
                }
            }
            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(getApplicationContext(), "Could not connect to the database...", Toast.LENGTH_SHORT).show();
            }
        });
        return Result.success();
    }
    private void createNotificationChannel(Context context) {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "Catting Around";
            String description = "Catting Around";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel("Catting Around", name, importance);
            channel.setDescription(description);
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }
}

huangapple
  • 本文由 发表于 2020年7月24日 07:45:59
  • 转载请务必保留本文链接:https://java.coder-hub.com/63064724.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定