Android Keep Broadcast Receiver is not Running After Application Exit?

jackrajjackraj USMember ✭✭

Hi all,
1. An app is locked state only services and broadcast are working in the background suppose is the app is not locked services and broadcast are not working in background services and broadcast mentioned on the screen below.
2. Reboot the devices that time services not working.
3.Attached AndroidManifest.xml
4.Using device is lenova tab37 and phab tab.

Mainactivity.cs

using Android.App;
using Android.Widget;
using Android.OS;
using Android.Content;
using PellucidSMSServices.Broadcast;
using System;
using Android.Util;

namespace PellucidSMSServices
{
[Activity(Label = "PellucidSMSServices", MainLauncher = true)]
public class MainActivity : Activity
{
Button btn_Submit;
EditText edt_Time;
EditText edt_Second;
EditText edt_prefix;
EditText edt_mobile;
EditText edt_message;
AlarmManager alarmManager;
PendingIntent pendingIntent;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);
        btn_Submit = FindViewById<Button>(Resource.Id.btn_Submit);
        edt_Time = FindViewById<EditText>(Resource.Id.edt_Time);
        edt_Second = FindViewById<EditText>(Resource.Id.edt_Second);
        edt_prefix = FindViewById<EditText>(Resource.Id.edt_prefix);
        edt_mobile = FindViewById<EditText>(Resource.Id.edt_mobile);
        edt_message = FindViewById<EditText>(Resource.Id.edt_message);
        btn_Submit.Click += Btn_Submit_Click;
    }
    private void Btn_Submit_Click(object sender, System.EventArgs e)
    {
        try
        {
            string Mobilenumber = string.Empty;
            if (!string.IsNullOrEmpty(edt_Time.Text) && !string.IsNullOrEmpty(edt_Second.Text) && !string.IsNullOrEmpty(edt_message.Text) && !string.IsNullOrEmpty(edt_mobile.Text))
            {
                if (Convert.ToInt32(edt_Second.Text) > 59)
                {
                    return;
                }
                try
                {
                    Mobilenumber = edt_prefix.Text + edt_mobile.Text;                      
                }
                catch (System.Exception ex)
                {
                    Toast.MakeText(this, "SharedPreferences in Mainactivity" + ex.Message, ToastLength.Long).Show();
                }                   
                Intent alarm = new Intent(this, typeof(SMSBroadcastReceiver));                  
                bool alarmRunning = (PendingIntent.GetBroadcast(this, 0, alarm, PendingIntentFlags.NoCreate) != null);
                if (alarmRunning == false)
                {
                    alarm.PutExtra("Message", edt_message.Text);
                    alarm.PutExtra("PhoneNumber", Mobilenumber);

                    //PASS CONTEXT,YOUR PRIVATE REQUEST CODE,INTENT OBJECT AND FLAG
                    pendingIntent = PendingIntent.GetBroadcast(this, 0, alarm, 0);
                    // rependingIntent = PendingIntent.GetBroadcast(this, 0, realarm, 0);

                    //INITIALIZE ALARM MANAGER
                    alarmManager = (AlarmManager)GetSystemService(AlarmService);

                    Java.Util.Calendar firingCal = Java.Util.Calendar.GetInstance(Java.Util.TimeZone.Default);
                    Java.Util.Calendar currentCal = Java.Util.Calendar.GetInstance(Java.Util.TimeZone.Default);
                    int time = Convert.ToInt32(edt_Time.Text);
                    int sec = Convert.ToInt32(edt_Second.Text);
                    firingCal.Set(Java.Util.Calendar.Hour, time); // At the hour you wanna fire
                    firingCal.Set(Java.Util.Calendar.Minute, sec); // Particular minute
                    firingCal.Set(Java.Util.Calendar.Second, 0); // particular second

                    long intendedTime = firingCal.TimeInMillis;
                    long currentTime = currentCal.TimeInMillis;

                    if (intendedTime >= currentTime)
                    {   
                        //SET THE ALARM
                        Toast.MakeText(this, "Your alarm set successfully now", ToastLength.Long).Show();
                        Log.Info("DataBasedOnUserResynce", "Your alarm set successfully now");
                        alarmManager.SetExact(AlarmType.RtcWakeup, intendedTime, pendingIntent);                          
                    }
                    else
                    {
                        // set from next day
                        // you might consider using calendar.add() for adding one day to the current day
                        firingCal.Add(Java.Util.Calendar.DayOfMonth, 1);
                        intendedTime = firingCal.TimeInMillis;                          
                        //alarmManager.SetRepeating(AlarmType.RtcWakeup, intendedTime, AlarmManager.IntervalDay, pendingIntent);
                        alarmManager.SetExact(AlarmType.RtcWakeup, intendedTime, pendingIntent);                            
                    }                       
                }
                else
                {
                    Toast.MakeText(this, "You already set alarm", ToastLength.Long).Show();
                }
            }
        }
        catch (System.Exception ex)
        {
            Toast.MakeText(this, "Exception occurred in Btn_Submit_Click:" + ex.Message, ToastLength.Long).Show();
        }
    }
}

}

SMSBroadcastReceiver.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Util;
using PellucidSMSServices.ServicesClass;

namespace PellucidSMSServices.Broadcast
{
[BroadcastReceiver(Enabled =true)]
public class SMSBroadcastReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
try
{
Toast.MakeText(context, "SMSBroadcastReceiver Received intent called!", ToastLength.Short).Show();

            if (intent.Action != null)
            {
                if (intent.Action.Equals(Intent.ActionBootCompleted))
                {                       

                    Toast.MakeText(context, "SMSBroadcastReceiver Received intent second called!", ToastLength.Short).Show();
                    Log.Info("Received intent!", "Received second");                       
                    context.StartService(new Intent(context, typeof(SMSBackupServicesCall)));
                }
            }
            else
            {
                Toast.MakeText(context, "SMSBroadcastReceiver Received intent second called!", ToastLength.Short).Show();
                Log.Info("Received intent!", "Received second");
                context.StartService(new Intent(context, typeof(SMSBackupServicesCall)));
            }
        }
        catch (Exception ex)
        {
            Toast.MakeText(Application.Context, "Exception occurred in OnReceive method of SMSBroadcastReceiver:" + ex.Message, ToastLength.Long).Show();
        }
    }
}

}

**SMSBackupServicesCall.cs **

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using PellucidSMSServices.Broadcast;

namespace PellucidSMSServices.ServicesClass
{
[Service(Exported = true)]
public class SMSBackupServicesCall : IntentService
{
public int counter = 0;
Intent intentthirdparty = null;
public SMSBackupServicesCall()
{
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
try
{
base.OnStartCommand(intent, flags, startId);
return StartCommandResult.Sticky;
// return
}
catch (Exception ex)
{
return StartCommandResult.Sticky;
}
}
protected override void OnHandleIntent(Intent intent)
{
try
{
try
{
intentthirdparty = new Intent();
intentthirdparty.AddFlags(ActivityFlags.IncludeStoppedPackages);
intentthirdparty.SetAction("android.intent.action.SMSTest");
intentthirdparty.PutExtra("EntityID", "Hai");
intentthirdparty.PutExtra("PhoneNumber", "XXXXX5918");
SendBroadcast(intentthirdparty);
StopSelf();

                Toast.MakeText(this, "Your services stoped successfully now", ToastLength.Long).Show();

                //Again start the services specific preiod of time
                Intent alarm = new Intent(this, typeof(SMSBroadcastReceiver));
                PendingIntent pendingIntent = PendingIntent.GetBroadcast(this, 0, alarm, 0);
                AlarmManager alarmManager = (AlarmManager)GetSystemService(AlarmService);

                Java.Util.Calendar firingCal = Java.Util.Calendar.GetInstance(Java.Util.TimeZone.Default);
                Java.Util.Calendar currentCal = Java.Util.Calendar.GetInstance(Java.Util.TimeZone.Default);

                int time = 3;
                int sec = 15;
                firingCal.Set(Java.Util.Calendar.Hour, time); // At the hour you wanna fire
                firingCal.Set(Java.Util.Calendar.Minute, sec); // Particular minute
                firingCal.Set(Java.Util.Calendar.Second, 0); // particular second

                long intendedTime = firingCal.TimeInMillis;
                long currentTime = currentCal.TimeInMillis;

                if (intendedTime >= currentTime)
                {                        
                    // you can add buffer time too here to ignore some small differences in milliseconds
                    // set from today                      
                    alarmManager.SetExact(AlarmType.RtcWakeup, intendedTime, pendingIntent);
                    Toast.MakeText(this, "Your alarm set successfully now", ToastLength.Long).Show();
                }
                else
                {
                    // set from next day
                    // you might consider using calendar.add() for adding one day to the current day
                    firingCal.Add(Java.Util.Calendar.DayOfMonth, 1);
                    intendedTime = firingCal.TimeInMillis;

                    //alarmManager.SetRepeating(AlarmType.Rtc, intendedTime, AlarmManager.IntervalDay, pendingIntent);
                    alarmManager.SetExact(AlarmType.RtcWakeup, intendedTime, pendingIntent);
                }
            }
            catch (Exception ex)
            {                  
            }
        }
        catch (Exception ex)
        {                
        }
    }
}

}

Mainfest.xml

Screen shot marked

VS configration

Sign In or Register to comment.