代码之家  ›  专栏  ›  技术社区  ›  PPavesi

使用服务发送新闻

  •  0
  • PPavesi  · 技术社区  · 2 年前

    我有一个应用程序,每次发布新新闻时都需要通知用户。这种情况每天发生3到4次。

    我正在尝试创建一个服务,负责为每个新闻项目向用户发送通知。

    我在这里请求指导,但没有发布我的代码,因为我认为我走错了路,但我删除了它,因为他们说我不能请求这种帮助。我三个月前开始使用Android Studio,但我成功地开发了我的应用程序。

    这是我启动服务的代码。

    public class adminNewsService extends Service {
    
        public void disparaNotificacao() {
    
            Context context = iPPGetContexto.getAppContext();
            Intent intent = new Intent(this, Repeating_Activity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            NotificationManagerCompat notificationManager;
    
            Spanned titleNote = Html.fromHtml("<b>iPP - Instituto</b>");
    
            notificationManager = NotificationManagerCompat.from(context);
            Notification notification = new NotificationCompat.Builder(context, CHANNEL_IPP_1)
                    .setSmallIcon(R.drawable.logo_png)
                    .setContentTitle(titleNote)
                    .setContentIntent(pendingIntent)
                    .setContentText(iPPNews.getNewsTitle())
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                    .build();
            notificationManager.notify(1, notification);
    
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Runnable r = new Runnable() {
                @Override
    
                public void run() {
                   if (checkNews()) {
                      disparaNotificacao();
                   } 
                }
            };
            Thread thread = new Thread(r);
            thread.start();
            return Service.START_STICKY;
        }
    
        @Override
        public void onTaskRemoved(Intent rootIntent) {
            super.onTaskRemoved(rootIntent);
            Intent startServiceIntent = new Intent(this, adminNewsService.class);
            this.startService(startServiceIntent);
        }
    
        @Override
        public void onDestroy() {
            Toast.makeText(this, "Servico suspenso", Toast.LENGTH_SHORT).show();
        }
    
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    }
    

    这项服务只运行一次。也许我得启动某种警报。无论如何,如果有人能指导我,我将非常感激。不需要发送代码。只要引导我就会大有裨益。

    总结一下。

    1. 我的应用程序应该每天检查3到4次新闻。
    2. 然后,即使应用程序关闭,它也必须通知用户。

    谢谢

    0 回复  |  直到 2 年前