Karthick M
Karthick M

Reputation: 779

After rebooting my device,sending sms frequently is sending sms one more time also while switch on

I am sending sms frequently,while rebooting my device sending sms one more time while we "switch on" also.After that its sending sms correct intervals.But its sending the sms one more time when we switch on our device.

public class BootCompletedIntentReceiver extends BroadcastReceiver {     

          @Override
          public void onReceive(Context ctxt, Intent i) {
            try {
                scheduleAlarms(ctxt);
            } catch (java.text.ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
          }

          @SuppressLint("SimpleDateFormat")
        static void scheduleAlarms(Context ctxt) throws java.text.ParseException {
              String share_pref_file = "IMS";
                SharedPreferences prefs = ctxt.getSharedPreferences(share_pref_file,
                Context.MODE_PRIVATE);

                String number = prefs.getString("extraSmsNumber", "");
                String message= prefs.getString("extraSmsText", "");
                String mytime = prefs.getString("Mytime", "");
                int year= prefs.getInt("Year", 0);
                int month= prefs.getInt("Month", 0);
                int dmonth= prefs.getInt("DMonth", 0);
                int hour= prefs.getInt("Hour", 0);
                int time= prefs.getInt("Time", 0);
                String nyear = String.valueOf(year);
                String nmonth = String.valueOf(month);
                String ndmonth = String.valueOf(dmonth);
                String nhour = String.valueOf(hour);
                String ntime = String.valueOf(time);
                //int tottime = dmonth +  month +  year + hour + time;
                String newtime = ndmonth + "-" +  nmonth + "-" +  nyear + "/" +  nhour + ":" + ntime;
                SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy/hh:mm");
                Date startDate=null;
                try {
                    startDate = df.parse(newtime);
                    String newDateString = df.format(startDate);

                } catch (ParseException e) {
                    e.printStackTrace();
                }

                 AlarmManager alarmManager =
                            (AlarmManager)ctxt.getSystemService(Context.ALARM_SERVICE);
                        Intent i=new Intent(ctxt, MyAlarmService.class);
                        PendingIntent pendingIntent=PendingIntent.getService(ctxt, 0, i, 0);



                        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy/hh:mm");
                 //SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYYY/HH:mm");
                 String currentLocalTime =sdf.format(new Date());
                    Date startTDate = null;
                    try {
                        startTDate = sdf.parse(currentLocalTime);
                        String newDateString = df.format(startTDate);
                        System.out.println(newDateString);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }


            if(startDate.compareTo(startTDate) < 0)
            {
                Toast.makeText(
                        ctxt,
                        "Welcome", Toast.LENGTH_LONG).show();   

            }



            if (mytime.equals("Once")) {
                Calendar calendar = Calendar.getInstance();

                calendar.set(year, month,
                        dmonth,
                        hour,
                        time, 0);

                alarmManager.set(AlarmManager.RTC_WAKEUP,
                        calendar.getTimeInMillis(), pendingIntent);
            } else if (mytime.equals("Every 5 Minutes")) {
                Calendar calendar = Calendar.getInstance();

                calendar.set(year, month,
                        dmonth,
                        hour,
                        time, 0);
                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                        calendar.getTimeInMillis(), 1000 * 60 * 5,
                        pendingIntent); // Millisec * Second *
                                        // Minute
            } else if (mytime.equals("Every hour")) {
                Calendar calendar = Calendar.getInstance();

                calendar.set(year, month,
                        dmonth,
                        hour,
                        time, 0);
                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                        calendar.getTimeInMillis(), 1000 * 60 * 60,
                        pendingIntent); // Millisec * Second *
                                        // Minute
            } else if (mytime.equals("Every day")) {
                Calendar calendar = Calendar.getInstance();

                calendar.set(year, month,
                        dmonth,
                        hour,
                        time, 0);
                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                        calendar.getTimeInMillis(),
                        24 * 60 * 60 * 1000, pendingIntent);

            } else if (mytime.equals("Weekly")) {
                Calendar calendar = Calendar.getInstance();

                calendar.set(year, month,
                        dmonth,
                        hour,
                        time, 0);
                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                        calendar.getTimeInMillis(), 7 * 24 * 60
                                * 60 * 1000, pendingIntent);

            } else if (mytime.equals("Weekdays(Mon-Fri)")) {

                forWeekdays(ctxt, year, month,
                        dmonth,
                        hour,
                        time);

            } else if (mytime.equals("Weekend")) {
                forWeekend(ctxt, year, month,
                        dmonth,
                        hour,
                        time);

            } else if (mytime.equals("Every month")) {
                Calendar calendar = Calendar.getInstance();

                calendar.set(year, month,
                        dmonth,
                        hour,
                        time, 0);
                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                        calendar.getTimeInMillis(), 30 * 24 * 60
                                * 60 * 1000, pendingIntent);

            } else {
                Calendar calendar = Calendar.getInstance();

                calendar.set(year, month,
                        dmonth,
                        hour,
                        time, 0);
                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                        calendar.getTimeInMillis(), 365 * 24 * 60
                                * 60 * 1000, pendingIntent);

            }
}

this is my service class

public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);

        String share_pref_file = "IMS";
        SharedPreferences prefs = getSharedPreferences(share_pref_file,
                Context.MODE_PRIVATE);

        String number = prefs.getString("extraSmsNumber", "");
        String message = prefs.getString("extraSmsText", "");

        Toast.makeText(this, "MyAlarmService.onStart()", Toast.LENGTH_LONG)
                .show();
        Toast.makeText(
                this,
                "MyAlarmService.onStart() with \n" + "smsNumberToSend = "
                        + number + "\n" + "smsTextToSend = " + message,
                Toast.LENGTH_LONG).show();

        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(number, null, message, null, null);
    }

The error occuring is sending one more sms while we switch on

if i am seeting to send sms at every 5 minutes, and i am starting at 5.0 clock na its sending 5.00 and 5.05 and after that i switched off my device at 5.07 and switch on at 5.08,so that 5.08 also sending sms,and then its continue to sending sms at 5.01 ,5.15 like that.only that 5.08 its sending sms is the problem.

Service class automatically started after rebooting one time.

Upvotes: 3

Views: 669

Answers (3)

PARDEEP YADAV
PARDEEP YADAV

Reputation: 1

Just Remove this permission from manifest.xml

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>

and also remove 

<intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"> </action>
    </intent-filter>

from <receiver> Tag in manifest.xml 

Upvotes: 0

vinay kumar
vinay kumar

Reputation: 1449

Service class automatically started after rebooting one time.

There are lots of questions posted by many users on this issue "Service automatically started after rebooting".

As a solution many of them suggested on return value onStartCommand() method with START_NOT_STICKY (It may worked for many, but isn't for me).

Note: it works good for lower versions of android 2.3.3 and 3.0 but not on 4.0 and later versions.

After analyzing bit ,came to known that startID seems to be giving different value when it is starting automatically, and on invoking by users.

So for me startID played a trick

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
 if(startId!=2)
        {
               //to do
            }
 return super.onStartCommand(intent, flags, startId);
}

And For tracking your time even after reboot.

I am not sure if android provide a API for tracking the time,but it can be achieved with simple mathematical computation.

For this you need to track at what time Alarm has fired for last time (use sharedpreference storing date/time in milli seconds).

long lastInvoked = preferences.getLong(AndroidAlarmSMS.LASTALARAMINVOKED, -1);
            Log.d("last_time_invoked",""+lastInvoked);
            long currentTime = System.currentTimeMillis();
            long period = 1000*60*5; // using 5 min of interval to repeat
            long diff = currentTime - lastInvoked;

            Log.d("difference",""+diff);

            if(diff > period)
            {
                long result= diff % period;
                long nextInvokeAt;
                if(result > period)
                {
                    nextInvokeAt = currentTime + (result - result); 
                }
                else{
                    nextInvokeAt = currentTime + (period - result); 
                }

                Log.d("invoked_next_time",""+nextInvokeAt);
                setPendingIntent(context,nextInvokeAt,period);
            }
            else
            {
                long result= period-diff;
                long nextInvokeAt = currentTime + result; 
                Log.d("next_time_invoked_else",""+nextInvokeAt);
                setPendingIntent(context,nextInvokeAt,period);
            }

and do the above operations in your Broadcast receiver class for action "BOOT_COMPLETED" and set the alarm with the resultant time

public static void setPendingIntent(Context ctx,long time,long period){
        AlarmManager alarmManager=
                (AlarmManager)ctx.getSystemService(Context.ALARM_SERVICE);
        Intent myIntent = new Intent(ctx,
                MyAlarmService.class);
        PendingIntent pendingIntent = PendingIntent.getService(ctx, 0, myIntent, 0);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                time, period , pendingIntent);

        Toast.makeText(ctx, "repeating --> "+time, Toast.LENGTH_LONG).show();
    }

Note: It is not a standard answer to resolve this issue, but for time being it work for me, hope it may help you to resolve this.

Note: Looking for better answers too...

Upvotes: 1

Kalai.G
Kalai.G

Reputation: 1610

Hi Karthi just have a look at this code:

Start your service exactly after 5 minutes when the device is booted

Calendar cal = Calendar.getInstance(); 
  // Start 5 minutes after boot completed
  cal.add(Calendar.MINUTE, 5); 
  alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,
            cal.getTimeInMillis(), REPEAT_TIME, pendingIntent);

Here alarm will not trigger before this cal.getTimeInMillis() time

Also go through this void android.app.AlarmManager.setInexactRepeating(int type, long triggerAtMillis, long intervalMillis, PendingIntent operation)

Upvotes: 0

Related Questions