xamarin 应用程序终止时检查网络状态更新

4zcjmb1e  于 2023-02-17  发布在  其他
关注(0)|答案(1)|浏览(135)

我的设想如下:
我在一个聊天应用程序上工作,我想实现某种类型的同步服务,当设备恢复网络连接时会自动启动。任何时候设备再次连接网络,未发送的消息都会自动发送。与应用程序状态(前台,后台或杀死)无关。
尝试的选项:

1.广播接收器与android.net.conn.CONNECTIVITY_CHANGE

此方案仅在应用程序处于活动状态(前台或后台)时有效,但在应用程序被杀死时停止工作。

2.前台服务

一个通知将显示所有的时间,这是不理想的。而且我想避免耗尽用户的电池。

3.安卓X.工作.工人

PeriodicWorkRequest networkCheckingPeriodicWork = PeriodicWorkRequest.Builder.
                From<ConnectivityChangeWroker>(repeatInterval:30, repeatIntervalTimeUnit: Java.Util.Concurrent.TimeUnit.Minutes, flexInterval:25, flexIntervalTimeUnit:Java.Util.Concurrent.TimeUnit.Minutes)
                .SetConstraints(new Constraints.Builder().SetRequiredNetworkType(AndroidX.Work.NetworkType.Connected)
                .SetRequiredNetworkType(AndroidX.Work.NetworkType.Unmetered).Build()).Build();

            WorkManager.Instance.EnqueueUniquePeriodicWork("", ExistingPeriodicWorkPolicy.Replace, networkCheckingPeriodicWork);

public class ConnectivityChangeWroker : AndroidX.Work.Worker
{
    public ConnectivityChangeWroker(Context context, WorkerParameters workerParameters) : base(context, workerParameters)
    {

    }

    public override Result DoWork()
    {
        try
        {
            //Start synch service

            return Result.InvokeSuccess();
        }
        catch (Exception)
        {
            return Result.InvokeFailure();
        }
    }
}

但是在这个例子中,我没有达到预期的行为。为了我的理解,我只是设置了一个周期性的工作来检查网络连接,如果有,就运行**DoWork()**方法。
有什么办法可以实现我的梦想吗?

6ljaweal

6ljaweal1#

我想androidx.Work.Worker是最好的选择。
DoWork中,您应该更新数据库并发送请求。
除辅助进程支持long-running workers
示例下载工作进程:

class DownloadWorker(context: Context, parameters: WorkerParameters) :
   CoroutineWorker(context, parameters) {

   private val notificationManager =
       context.getSystemService(Context.NOTIFICATION_SERVICE) as
               NotificationManager

   override suspend fun doWork(): Result {
       val inputUrl = inputData.getString(KEY_INPUT_URL)
                      ?: return Result.failure()
       val outputFile = inputData.getString(KEY_OUTPUT_FILE_NAME)
                      ?: return Result.failure()
       // Mark the Worker as important
       val progress = "Starting Download"
       setForeground(createForegroundInfo(progress))
       download(inputUrl, outputFile)
       return Result.success()
   }

   private fun download(inputUrl: String, outputFile: String) {
       // Downloads a file and updates bytes read
       // Calls setForeground() periodically when it needs to update
       // the ongoing Notification
   }
   // Creates an instance of ForegroundInfo which can be used to update the
   // ongoing notification.
   private fun createForegroundInfo(progress: String): ForegroundInfo {
       val id = applicationContext.getString(R.string.notification_channel_id)
       val title = applicationContext.getString(R.string.notification_title)
       val cancel = applicationContext.getString(R.string.cancel_download)
       // This PendingIntent can be used to cancel the worker
       val intent = WorkManager.getInstance(applicationContext)
               .createCancelPendingIntent(getId())

       // Create a Notification channel if necessary
       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
           createChannel()
       }

       val notification = NotificationCompat.Builder(applicationContext, id)
           .setContentTitle(title)
           .setTicker(title)
           .setContentText(progress)
           .setSmallIcon(R.drawable.ic_work_notification)
           .setOngoing(true)
           // Add the cancel action to the notification which can
           // be used to cancel the worker
           .addAction(android.R.drawable.ic_delete, cancel, intent)
           .build()

       return ForegroundInfo(notificationId, notification)
   }

   @RequiresApi(Build.VERSION_CODES.O)
   private fun createChannel() {
       // Create a Notification channel
   }

   companion object {
       const val KEY_INPUT_URL = "KEY_INPUT_URL"
       const val KEY_OUTPUT_FILE_NAME = "KEY_OUTPUT_FILE_NAME"
   }
}

相关问题