簡體   English   中英

Android和長期運行的后台任務

[英]Android and long running background task

我有一個Xamarin Android應用程序。 我需要在此應用中開始長時間運行的任務。 據我所知,我應該使用類Service 我創建了一個這樣的類:

[Service]
public class BackgroundService : IntentService
{
    Handler mHandler;

    public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
    {
        mHandler = new Handler();
        SomeTask();
        return 0;
    }

    private void SomeTask()
    {
        // Thread.CurrentThread.ManagedThreadId here is 1
        Thread.Sleep(5000);
        for (int i = 1; i <= 10; i++)
        {
            mHandler.Post(new Runnable(() =>
            {
                Toast.MakeText(this, $"Current thread ID in service: {Thread.CurrentThread.ManagedThreadId}", ToastLength.Short).Show();
            }));
        }
        StopSelf();                       
    }

    protected override void OnHandleIntent(Intent intent)
    {
    }
}

以及我如何在活動中使用該服務:

// And here Thread.CurrentThread.ManagedThreadId is 1
var serviceToStart = new Intent(this, typeof(BackgroundService));
StartService(serviceToStart);

我預計這項服務在另一個后台線程啟動,但Thread.CurrentThread.ManagedThreadId在活動僅僅一樣Thread.CurrentThread.ManagedThreadId的方法SomeTask類BackgroundService的。 此外,當SomeTask運行時,我的應用程序沒有響應。 顯然,這意味着該服務無法在后台線程中運行。 如何使服務在后台線程/進程中運行?

您應該在OnHandleIntent方法中彈出Toast並將new Handler()代碼更改為new Handler(Looper.MainLooper)

您可以參考以下演示。

在此處輸入圖片說明

IntentServiceDemo.cs

[Service]
public  class IntentServiceDemo : IntentService
{

    Handler mHandler;
    public IntentServiceDemo() : base("IntentServiceDemo")
    {

    }
    protected override void OnHandleIntent(Intent intent)
    {
        mHandler = new Handler(Looper.MainLooper);
        SomeTask();
    }

    private void SomeTask()
    {
        Thread.Sleep(1000);
        int id=System.Threading.Thread.CurrentThread.ManagedThreadId;
        for (int i = 1; i <= 10; i++)
        {
            mHandler.Post(new Runnable(() =>
            {

                Toast.MakeText(ApplicationContext, $"Current thread ID in service:"+ id, ToastLength.Short).Show();

            }));
        }
        StopSelf();
    }
}

MainActivity.cs

[Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
    //string TAG = "DemoService:";
  //  private Messenger messenger; // Instance variable for the Messenger
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);

        SetContentView(Resource.Layout.activity_main);
        int id = System.Threading.Thread.CurrentThread.ManagedThreadId;
        Toast.MakeText(this ,"Main thread"+ id, ToastLength.Short).Show();
        Button bt_service = FindViewById<Button>(Resource.Id.bt_service);

        bt_service.Click += (e, o) =>
        {
            Intent downloadIntent = new Intent(this, typeof(IntentServiceDemo));
            StartService(downloadIntent);

        };

    }

activity_main.axml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
 <Button
  android:id="@+id/bt_service"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:text="startService"/>
</RelativeLayout>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM