我正在嘗試使用 Xamarin Forms 運行一個函式,特別是在 Android 上,每隔幾分鐘。可悲的是,圍繞這一點的檔案如果不是含糊的,就什么都不是。除其他外,它向我推薦了(已棄用的)FireBase Job Dispatcher。
目前,我已經嘗試過這個:
Android
MainActivity.cs
[Activity(Label = "SolutionName", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize )]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
Xamarin.FormsMaps.Init(this, savedInstanceState);
LoadApplication(new App());
//StartService(new Intent(this, typeof(PeriodicService)));
var alarmIntent = new Intent(this, typeof(BackgroundReceiver));
var pending = PendingIntent.GetBroadcast(this, 0, alarmIntent, PendingIntentFlags.UpdateCurrent);
var alarmManager = GetSystemService(AlarmService).JavaCast<AlarmManager>();
alarmManager.Set(AlarmType.ElapsedRealtime, SystemClock.ElapsedRealtime() 3 * 1000, pending);
}
}
}
廣播接收器.cs
[BroadcastReceiver]
public class BackgroundReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
PowerManager pm = (PowerManager)context.GetSystemService(Context.PowerService);
PowerManager.WakeLock wakeLock = pm.NewWakeLock(WakeLockFlags.Partial, "BackgroundReceiver");
wakeLock.Acquire();
MessagingCenter.Send<object, string>(this, "UpdateLabel", "Hello from Android");
wakeLock.Release();
}
}
主 主頁.xaml
<Label Text="Welcome to Xamarin Forms!"
x:Name="BackgroundServiceLabel"
VerticalOptions="Center"
HorizontalOptions="Center" />
主頁.xaml.cs
public HomePage()
{
InitializeComponent();
InitializeGeofences();
GetData();
MessagingCenter.Subscribe<object, string>(this, "UpdateLabel", (s, e) =>
{
Device.BeginInvokeOnMainThread(() =>
{
BackgroundServiceLabel.Text = e;
});
});
}
此代碼不會運行,并且沒有任何錯誤。我做錯什么了嗎?有任何修復嗎?有替代路線嗎?
感謝您花時間閱讀本文。
uj5u.com熱心網友回復:
簡短的回答是“你做不到。” 長的答案是:強制系統定期執行某些內容并不是一個好的設計,因為新的 Android 作業系統版本有更多限制。最好將您的應用程式設計為基于某些系統或用戶事件執行某些邏輯。
您可以使用WorkManager API安排您的任務來啟動一些流程 您可以使用 Push Notifications API
有時我們必須強制系統為此執行一些任務,我們可以使用 ForegroundService 但它應該再次成為您的“最后手段”。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/384144.html
標籤:C# 安卓 沙马林 xamarin.forms
