how to run background service even the app is closed ? AIM services is always run.

jackrajjackraj USMember ✭✭
edited November 2017 in General

I have created the service successfully but when the app is closed my services is closed so please help me?

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>






<service android:name="BackgroundService" android:label="SMSservice" />
<receiver android:name="AlarmReceiver"></receiver>

AlarmReviceiver.cs
[BroadcastReceiver(Enabled = true)]
[IntentFilter(new[] { Intent.ActionBootCompleted })]
public class AlarmReceiver: BroadcastReceiver
{
private static string TAG = "LL24";
public override void OnReceive(Context context, Intent intent)
{
// Work that should be done when the device boots.
Log.Debug(TAG, "Alarm for LifeLog...");
//Intent ll24Service = new Intent(context, typeof(SimpleStartedService));
//context.StartService(ll24Service);
Toast.MakeText(context, "Received broadcast in MyBroadcastReceiver, " +
" value received: " + intent.GetStringExtra("key"),ToastLength.Long).Show();
Intent background = new Intent(context, typeof(BackgroundService));
context.StartService(background);

    }
}

BackgroundService.cs
[Service(Exported = true)]
public class BackgroundService: Service
{
private Boolean isRunning;
private Context context;
private Thread thread;

    public override void OnCreate()
    {
        base.OnCreate();
        this.context = this;
        this.isRunning = false;
        thread = new Thread(myTask);            
    }
    public async void myTask()
    {
        try
        {
            //System.Threading.Task.Run(async () =>
            //{
            //    this.context.Toast.MakeText(this, "SMS Services is Running", ToastLength.Long).Show();
            //    //Add your code here.
            //}).ConfigureAwait(false);

            await Task.Run(async () => runmessage());

            //this.context. Toast.MakeText(this, "SMS Services is Running", ToastLength.Long).Show();
            // Console.WriteLine("SMS Services is Running");
        }
        catch(Exception ex)
        {
            Toast.MakeText(this, "Latitude and Longitude is null."+ex.Message, ToastLength.Long).Show();
        }
    }
    private async  System.Threading.Tasks.Task runmessage()
    {
        try
        {
            Task.Run(() =>
            {
                Toast.MakeText(this, "SMS Services is Running", ToastLength.Long).Show();
            });
            //Add your code here.
        }
        catch (Exception ex)
        {
            Toast.MakeText(this, "Error occurred runmessage method SMS Services is Running" + ex.Message , ToastLength.Long).Show();
        }
    }
    public override void OnDestroy()
    {
        this.isRunning = false;
    }
    //@Override
    public override IBinder OnBind(Intent intent)
    {
        // This is a started service, not a bound service, so we just return null.
        return null;
    }
    public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
    {
        try
        {
            if (!this.isRunning)
            {
                this.isRunning = true;
                this.thread.Start();
            }
        }
        catch(Exception ex)
        {
            Toast.MakeText(this, "Error occurred StartCommandResult" + ex.Message, ToastLength.Long).Show();
        }            

        return StartCommandResult.Sticky;
    }
}

Mainactivity.cs
[Activity(Label = "SendSMS", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);

        // Set our view from the "main" layout resource
         SetContentView (Resource.Layout.Main);
        Intent alarm = new Intent(this, typeof(AlarmReceiver));
        bool alarmRunning = (PendingIntent.GetBroadcast(this, 0, alarm,PendingIntentFlags.NoCreate)!=null);
        if (alarmRunning == false)
        {
            PendingIntent pendingIntent = PendingIntent.GetBroadcast(this, 0, alarm, 0);
            AlarmManager alarmmanger = (AlarmManager)GetSystemService(Context.AlarmService);
            //alarmmanger.SetRepeating(AlarmType.RtcWakeup,SystemClock.ElapsedRealtime(), 1800000,pendingIntent);
            //alarmmanger.SetRepeating(AlarmType.RtcWakeup, SystemClock.ElapsedRealtime(), 1000, pendingIntent);
            alarmmanger.SetInexactRepeating(AlarmType.RtcWakeup, SystemClock.ElapsedRealtime(), 1000, pendingIntent);
        }
    }
}

I follow this link
https://forums.xamarin.com/discussion/84049/how-to-run-a-background-service-even-the-app-is-closed

xml file
service android:name="BackgroundService" android:label="SMSservice"
receiver android:name="AlarmReceiver"

Sign In or Register to comment.