locked
BroadcastReceiver in AlarmManager Unfortunately, MyApp has stopped while reboot devices? RRS feed

  • Question

  • User252555 posted

    Hi all, I had started working on android services using Intent services and Broadcastreceiver via AlarmManager call in the mainactivity

    My error is Unfortunately, MyApp has stopped while reboot time so please share your idea.

    1.I call Broadcastreceiver using AlarmManager specific time 4 clock it will send SMS from to one device to other devices 2.Stop intent services -By using this method(StopSelf();) stop the services, then again set another time in AlarmManager called to Broadcast receiver. 3.Reboot time call Broadcastreceiver specific time 4 clock it

    1.I call Broadcastreceiver using AlarmManager specific time 4 clock it will send SMS from to one device to other devices Broadcast receiver.

    MainActivity.cs

    using Android.App; using Android.Widget; using Android.OS; using Android.Content; using Intentservice1.MReceiver;

    namespace Intentservice1 { [Activity(Label = "Intentservice1", MainLauncher = true, Icon = "@drawable/icon")] public class MainActivity : Activity { private Handler handler; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle);

            // Set our view from the "main" layout resource
             SetContentView (Resource.Layout.Main);
    
            try
            {
                PellucidLog.Logfile.WriteEventLog("Class:MainActivity", "Method:MainActivity", 0, "OnCreate method Called", System.Diagnostics.TraceEventType.Information);
                Intent alarm = new Intent(this, typeof(MyReceiver));
                //bool alarmRunning = (PendingIntent.GetBroadcast(this, 0, alarm, PendingIntent.FLAG_NO_CREATE) != null);
                bool alarmRunning = (PendingIntent.GetBroadcast(this, 0, alarm, PendingIntentFlags.NoCreate) != null);
                if (alarmRunning == false)
                {
                    PendingIntent pendingIntent = PendingIntent.GetBroadcast(this, 0, alarm, 0);
                    AlarmManager alarmManager = (AlarmManager)GetSystemService(Context.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);
    
                    firingCal.Set(Java.Util.Calendar.Hour, 4); // At the hour you wanna fire
                    firingCal.Set(Java.Util.Calendar.Minute, 1); // Particular minute
                    firingCal.Set(Java.Util.Calendar.Second, 0); // particular second
    
                    long intendedTime = firingCal.TimeInMillis;
                    long currentTime = currentCal.TimeInMillis;
    
                    if (intendedTime >= currentTime)
                    {
                        PellucidLog.Logfile.WriteEventLog("Class:MyReceiver", "Method:MainActivity ", 0, "current time set OnCreate method Called", System.Diagnostics.TraceEventType.Information);                                               
                        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.SetExact(AlarmType.RtcWakeup, intendedTime, pendingIntent);
                    }                    
                    PellucidLog.Logfile.WriteEventLog("Class:MyReceiver", "Method:MainActivity ", 0, " end of else OnCreate method Called", System.Diagnostics.TraceEventType.Information);
                }
            }
            catch (System.Exception ex)
            {
                Toast.MakeText(this, "Exception occurred in Oncreate of MainActivity class:" + ex.Message, ToastLength.Long).Show();
            }
        }
    }
    

    }

    2.Stop intent services -By using this method(StopSelf();) stop the services, then again set another time in AlarmManager called to Broadcast receiver.

    MyIntenService.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.Telephony; using Intentservice1.MReceiver;

    namespace Intentservice1.TimerServices { [Service] public class MyIntenService : IntentService { public MyIntenService() { PellucidLog.Logfile.WriteEventLog("Class:MyIntenService", "Method:MyIntenService", 0, "MyIntenService constructor called ", System.Diagnostics.TraceEventType.Information); } public override void OnCreate() { base.OnCreate(); PellucidLog.Logfile.WriteEventLog("Class:MyIntenService", "Method:OnCreate", 0, "OnCreate method called ", System.Diagnostics.TraceEventType.Information); } [return: GeneratedEnum] public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId) { PellucidLog.Logfile.WriteEventLog("Class:MyIntenService", "Method:OnStartCommand", 0, "OnStartCommand method called ", System.Diagnostics.TraceEventType.Information); return base.OnStartCommand(intent, flags, startId); } public override void OnDestroy() { PellucidLog.Logfile.WriteEventLog("Class:MyIntenService", "Method:OnDestroy", 0, "OnDestroy method called ", System.Diagnostics.TraceEventType.Information); base.OnDestroy(); } public override IBinder OnBind(Intent intent) { return base.OnBind(intent); }
    PendingIntent sentPI; String SENT = "SMS_SENT"; protected override void OnHandleIntent(Intent intent) { try { sentPI = PendingIntent.GetBroadcast(this, 0, new Intent(SENT), 0);
    SmsManager.Default.SendTextMessage("+919600605918", null, "Message send from Alarm manager to client place. ", sentPI, null); PellucidLog.Logfile.WriteEventLog("Class:MyIntenService", "Method:OnHandleIntent", 0, "Message send ", System.Diagnostics.TraceEventType.Information); StopSelf(); Intent alarm = new Intent(this, typeof(MyReceiver)); PendingIntent pendingIntent = PendingIntent.GetBroadcast(this, 0, alarm, 0); AlarmManager alarmManager = (AlarmManager)GetSystemService(Context.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);
    
                firingCal.Set(Java.Util.Calendar.Hour, 4); // At the hour you wanna fire
                firingCal.Set(Java.Util.Calendar.Minute, 5); // Particular minute
                firingCal.Set(Java.Util.Calendar.Second, 0); // particular second
    
                long intendedTime = firingCal.TimeInMillis;
                long currentTime = currentCal.TimeInMillis;
    
                if (intendedTime >= currentTime)
                {                    
                    alarmManager.SetExact(AlarmType.RtcWakeup, intendedTime, pendingIntent);
                }
                else
                {
    
                    firingCal.Add(Java.Util.Calendar.DayOfMonth, 1);
                    intendedTime = firingCal.TimeInMillis;
                    alarmManager.SetExact(AlarmType.RtcWakeup, intendedTime, pendingIntent);
                }
            }
            catch(Exception ex)
            {
                PellucidLog.Logfile.WriteEventLog("Class:MyIntenService", "Method:OnHandleIntent", 0, "Error occurred:"+ex.Message, System.Diagnostics.TraceEventType.Information);
            }
    
        }
    }
    

    }

    3.Reboot time call Broadcastreceiver specific time 4 clock it

    MyReceiver.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 Intentservice1.TimerServices; using Android.Util;

    namespace Intentservice1.MReceiver { [BroadcastReceiver(Enabled =true)] [IntentFilter(new[] { Android.Content.Intent.ActionBootCompleted })] public class MyReceiver : BroadcastReceiver { public override void OnReceive(Context context, Intent intent) { try { if (intent.Action != null) { if (intent.Action.Equals(Intent.ActionBootCompleted)) { PellucidLog.Logfile.WriteEventLog("Class:MyReceiver", "Method:OnReceive first ", 0, "ActionBootCompleted OnReceive method Called", System.Diagnostics.TraceEventType.Information); Intent alarm = new Intent(context, typeof(MyReceiver)); Intent alarmservices = new Intent(context, typeof(MyIntenService));

                            PendingIntent pendingIntent = PendingIntent.GetService(context, 0, alarmservices, PendingIntentFlags.CancelCurrent);
                            AlarmManager alarmManager = (AlarmManager)context.GetSystemService(Context.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);
    
                            firingCal.Set(Java.Util.Calendar.Hour, 4); // At the hour you wanna fire
                            firingCal.Set(Java.Util.Calendar.Minute,10); // Particular minute
                            firingCal.Set(Java.Util.Calendar.Second, 0); // particular second
    
                            long intendedTime = firingCal.TimeInMillis;
                            long currentTime = currentCal.TimeInMillis;
                            if (intendedTime >= currentTime)
                            {
    
                                PellucidLog.Logfile.WriteEventLog("Class:MyReceiver", "Method:OnReceive second ", 0, "ActionBootCompleted current time set OnReceive method Called", System.Diagnostics.TraceEventType.Information);                               
                                alarmManager.SetExact(AlarmType.RtcWakeup, intendedTime, pendingIntent);
                            }
                            else
                            {
                                PellucidLog.Logfile.WriteEventLog("Class:MyReceiver", "Method:OnReceive second ", 0, "ActionBootCompleted later time OnReceive method Called", System.Diagnostics.TraceEventType.Information);
    
                                firingCal.Add(Java.Util.Calendar.DayOfMonth, 1);
                                intendedTime = firingCal.TimeInMillis;                               
                                alarmManager.SetExact(AlarmType.RtcWakeup, intendedTime, pendingIntent);
                            }
    
    
                        Toast.MakeText(context, "MyReceiver BroadcastReceiver called AlarmReceiver Received intent!", ToastLength.Short).Show();
                        Log.Info("Received intent!", "MyReceiver BroadcastReceiver called ");
    
                    }
                }
                else
                {
                    Toast.MakeText(context, "MyReceiver Received intent second called!", ToastLength.Short).Show();
                    Log.Info("Received intent!", "Received second");
                    PellucidLog.Logfile.WriteEventLog("Class:MyReceiver", "Method:OnReceive second", 0, "Null OnReceive method Called", System.Diagnostics.TraceEventType.Information);
                    context.StartService(new Intent(context, typeof(MyIntenService)));
                }
            }
            catch (Exception ex)
            {
                Toast.MakeText(context, "MyReceiver Received intent!" + ex.Message, ToastLength.Short).Show();
            }
        }
    }
    

    }

    Mainfest file screen shot and attached

    Log.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 System.IO;

    namespace PellucidLog { public static class Logfile {
    public static void WriteEventLog(string sClassName, string sFunctionName, int iErrorCode, string sErrorMessage, System.Diagnostics.TraceEventType eletLogType) { LogEvent(sClassName + " " + sFunctionName + " " + sErrorMessage, eletLogType); }

        public static void LogEvent(String Message, System.Diagnostics.TraceEventType type)
        {
            try
            {
                LogToFile(DateTime.Now.ToString("hh:mm:ss") + " : " + type.ToString() + ": " + Message + System.Environment.NewLine);
            }
            catch (Exception ex)
            {
                LogToFile(DateTime.Now.ToString("hh:mm:ss") + " : " + type.ToString() + ": " + ex.Message + System.Environment.NewLine);
            }
            finally
            {
    
            }
        }
        private readonly static object _syncklock = new object();
    
        public static void LogToFile(string msg)
        {
            lock (_syncklock)
            {
                try
                {
                    // if (Convert.ToBoolean(LogDisplay))
                    {
                        var path = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).AbsolutePath;
                        Java.IO.File Download = new Java.IO.File(path);
                        if (!Download.Exists() && !Download.IsDirectory)
                        {
                            Download.Mkdir();
                        }
    
                        string directroy = System.IO.Path.Combine(path, "Pellucid");
                        Java.IO.File Pellucid = new Java.IO.File(directroy);
                        if (!Pellucid.Exists() && !Pellucid.IsDirectory)
                        {
                            Pellucid.Mkdir();
                        }
    
                        string _Filename = Path.Combine(directroy, "ServicesMobility.log");
                        if (!File.Exists(_Filename))
                        {
                            FileStream CreateFileStream = new FileStream(_Filename, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite);
                            CreateFileStream.Close();
                            CreateFileStream = null;
                        }
                        int _ConfigFileSizeRange = 20000;//Convert.ToInt32(WebConfigurationManager.AppSettings["FileSize"].ToString());
                        FileInfo _LogFileInfo = new FileInfo(_Filename);
                        int _LogFileLength = Convert.ToInt32(_LogFileInfo.Length.ToString());
                        if (_LogFileLength > _ConfigFileSizeRange)
                        {                          
    
                            string destinationFileName = Path.Combine(directroy, "LogEntries");// + DateTime.Now.ToString("MM.dd.yy"), DateTime.Now.ToString("hh.mm.ss") + ".txt");                            
                            Java.IO.File PellucidDestination = new Java.IO.File(destinationFileName);
                            if (!PellucidDestination.Exists() && !PellucidDestination.IsDirectory)
                            {
                                PellucidDestination.Mkdir();
                            }
                            string destinationDate = Path.Combine(destinationFileName, DateTime.Now.ToString("MM.dd.yy"));
                            Java.IO.File PellucidDatetime = new Java.IO.File(destinationDate);
    
                            if (!PellucidDatetime.Exists() && !PellucidDatetime.IsDirectory)
                            {
                                PellucidDatetime.Mkdir();
                            }
    
                            string destinationDatefile = Path.Combine(destinationDate, DateTime.Now.ToString("hh.mm.ss") + ".txt");
    
                            if (!Directory.Exists(Path.GetDirectoryName(destinationDatefile)))
                            {
                                Directory.CreateDirectory(Path.GetDirectoryName(destinationDatefile));
                            }
                            File.Copy(_Filename, destinationDatefile);
                            File.WriteAllText(_Filename, "");
                        }
                        File.AppendAllText(_Filename, msg);
                    }
                }
                catch (Exception ex)
                {
                    LogToFile(DateTime.Now.ToString("hh:mm:ss") + " : " + "LogToFile method" + ": " + ex.Message + System.Environment.NewLine);
                }
            }
        }
    }
    

    }

    Thursday, February 8, 2018 2:10 PM

Answers

  • User252555 posted

    Hi all, I have fixed issues for Unfortunately, MyApp has stopped. while reboot devices

    I have removed the register of the broadcaster in AndroidManifest.xml file

       <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="19" />
    <uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.SET_ALARM" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <application android:allowBackup="true" android:label="@string/app_name">
        <activity android:name="appApplication.MainActivity" android:label="@string/ApplicationName">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </activity>
        <service android:name=".MyIntenService" android:exported="false" />
    </application>
    

    Andro also register in the main activity class like this

       protected override void OnPause()
        {
            base.OnPause();
            UnregisterReceiver(_receiver);
        }
        protected override void OnResume()
        {
            base.OnResume();
            _receiver = new MyWorkReceiver();            
            RegisterReceiver(_receiver, new IntentFilter("android.intent.action.BOOT_COMPLETED"));
        }
    
    • Marked as answer by Anonymous Thursday, June 3, 2021 12:00 AM
    Monday, February 12, 2018 6:42 AM