Difficulties with Android Alarm Manager, Boot Comp

2019-07-08 12:10发布

I encountered an issue where my scheduled tasks stopped working once a device was rebooted. I was informed this was normal behavior for Alarm Manager, and that I should use the BOOT_COMPLETED action. Unfortunately, it is still not working. Here is what I have

The main/launcher activity

public class launch_activity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_launch_activity);

        File dbFile = new File(getFilesDir(), "bk.db");
        if(!dbFile.exists()) {
            try {
                InputStream localDB = getAssets().open("bk.db");
                OutputStream newDB = new FileOutputStream(dbFile);
                byte[] buffer = new byte[1024];
                int read;

                while ((read = localDB.read(buffer)) > 0) {
                    newDB.write(buffer, 0 , read);
                }

                localDB.close();
                newDB.close();

            } catch(IOException e) {
                Log.e(this.getClass().toString(), "IO Error!");
            }
        }

        SharedPreferences preferences = getSharedPreferences("config", MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        if(!(preferences.contains("User"))) {
            editor.putString("User", "admin");

            editor.putString("Pass", "admin");
            editor.commit();
        }
    }

    protected void onStart() {
        super.onStart();


        SharedPreferences preferences = getSharedPreferences("config", MODE_PRIVATE);
       Intent i = new Intent(this, screenSaver.class);
startService(i);

        if (!(preferences.getBoolean("configured", false))) { // app has not yet been set-up

            // set the timer

            Intent downloadIntent = new Intent(launch_activity.this, downloadReceiver.class);
            PendingIntent pending = PendingIntent.getBroadcast(launch_activity.this, 0, downloadIntent, 0);
            final Calendar cal = Calendar.getInstance();
            cal.setTimeInMillis(System.currentTimeMillis());
            cal.set(Calendar.HOUR_OF_DAY, 4);

            final AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);

            manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() + 1000, AlarmManager.INTERVAL_DAY, pending);


            class downloadFinishedReceiver extends BroadcastReceiver {
                private  DownloadManager dManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                @Override
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();
                    if(DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                        long downloadID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                        DownloadManager.Query query = new DownloadManager.Query();
                        query.setFilterById(downloadID);
                        Cursor cursor = dManager.query(query);
                        if(cursor.moveToFirst()) {
                            int colIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
                            if (DownloadManager.STATUS_SUCCESSFUL == cursor.getInt(colIndex)) {
                                String uri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
                                File file = new File(Uri.parse(uri).getPath());
                                Log.e("passing", "success");

                                try {
                                    FileInputStream inputStream = new FileInputStream(file);
                                    FileOutputStream fileOutputStream = context.openFileOutput(databaseHelper.DB_NAME, Context.MODE_PRIVATE);
                                    byte[] buffer = new byte[1024];
                                    Log.e("passing", "try");
                                    int read;

                                    while ((read = inputStream.read(buffer)) > 0) {
                                        fileOutputStream.write(buffer, 0 , read);
                                    }

                                    fileOutputStream.close();
                                    inputStream.close();
                                    databaseHelper db = new databaseHelper(context);
                                    db.copyDB();
                                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

                                    Log.e("passing", "close");
                                } catch (Exception ex) {
                                    Log.e("Exception", ex.getMessage() + uri);
                                }
                            }



                        }
                    }
                }
            };


            registerReceiver(new downloadFinishedReceiver(), new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));


            Intent reminderHourlyIntent = new Intent(this, hourlyReminder.class);
            PendingIntent reminderHourly = PendingIntent.getActivity(this, 0,reminderHourlyIntent, 0);
            Calendar newCal = Calendar.getInstance();
            int nextHour = 60 - newCal.get(Calendar.MINUTE);
            newCal.add(Calendar.MINUTE, nextHour);
            // manager.setRepeating(AlarmManager.RTC_WAKEUP, newCal.getTimeInMillis() - (1000 * 60 * 10), 1000 * 60 * 60, reminderHourly);
            manager.setRepeating(AlarmManager.RTC_WAKEUP, 60000, 1500 * 60, reminderHourly );

            Intent reminderIntent = new Intent(this, reminder.class);
            PendingIntent reminder = PendingIntent.getActivity(this, 0, reminderIntent, 0);
            // manager.setRepeating(AlarmManager.RTC_WAKEUP, newCal.getTimeInMillis(), 1000 * 60 * 60 * 4, reminder );
            manager.setRepeating(AlarmManager.RTC_WAKEUP, 1000 * 60 * 3, 1000 * 60  * 3, reminder );


// redirect to set up

            Intent intent = new Intent(this, midamcorp.com.burgerkingapp.preferences.class);
            intent.putExtra("setUp", true);
            startActivity(intent);
            return;
        } else {
            Calendar cal = Calendar.getInstance();
            if (cal.get(Calendar.HOUR_OF_DAY) > 4 && cal.get(Calendar.HOUR_OF_DAY) < 10) // between 4 - 10 AM
            {

                Intent intent = new Intent(this, breakfastHome.class);
                startActivity(intent);
            } else if ((cal.get(Calendar.HOUR_OF_DAY) == 10 && cal.get(Calendar.MINUTE) < 28)) { // between 10 - 10:28 AM
                Intent intent = new Intent(this, breakfastHome.class);
                startActivity(intent);
            } else {
                Intent intent = new Intent(this, lunchHome.class);
                startActivity(intent);
            }
        }
    }

    protected void onResume() {
        super.onResume();
        this.onStart();
    }

}

bootReceiver

public class bootReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(final Context c, Intent i) {

        if(i.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
            Intent downloadIntent = new Intent(c, downloadReceiver.class);
            PendingIntent pending = PendingIntent.getBroadcast(c, 0, downloadIntent, 0);
            final Calendar cal = Calendar.getInstance();
            cal.setTimeInMillis(System.currentTimeMillis());
            cal.set(Calendar.HOUR_OF_DAY, 4);

            final AlarmManager manager = (AlarmManager)c.getSystemService(Context.ALARM_SERVICE);

            manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis() + 1000, AlarmManager.INTERVAL_DAY, pending);


            class downloadFinishedReceiver extends BroadcastReceiver {
                private DownloadManager dManager = (DownloadManager) c.getSystemService(c.DOWNLOAD_SERVICE);
                @Override
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();
                    if(DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                        long downloadID = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                        DownloadManager.Query query = new DownloadManager.Query();
                        query.setFilterById(downloadID);
                        Cursor cursor = dManager.query(query);
                        if(cursor.moveToFirst()) {
                            int colIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
                            if (DownloadManager.STATUS_SUCCESSFUL == cursor.getInt(colIndex)) {
                                String uri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
                                File file = new File(Uri.parse(uri).getPath());
                                Log.e("passing", "success");

                                try {
                                    FileInputStream inputStream = new FileInputStream(file);
                                    FileOutputStream fileOutputStream = context.openFileOutput(databaseHelper.DB_NAME, Context.MODE_PRIVATE);
                                    byte[] buffer = new byte[1024];
                                    Log.e("passing", "try");
                                    int read;

                                    while ((read = inputStream.read(buffer)) > 0) {
                                        fileOutputStream.write(buffer, 0 , read);
                                    }

                                    fileOutputStream.close();
                                    inputStream.close();
                                    databaseHelper db = new databaseHelper(context);
                                    db.copyDB();
                                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

                                    Log.e("passing", "close");
                                } catch (Exception ex) {
                                    Log.e("Exception", ex.getMessage() + uri);
                                }
                            }



                        }
                    }
                }
            };


            c.registerReceiver(new downloadFinishedReceiver(), new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));



            Intent reminderHourlyIntent = new Intent(c, hourlyReminder.class);
            PendingIntent reminderHourly = PendingIntent.getActivity(c, 0,reminderHourlyIntent, 0);
            Calendar newCal = Calendar.getInstance();
            int nextHour = 60 - newCal.get(Calendar.MINUTE);
            newCal.add(Calendar.MINUTE, nextHour);
            // manager.setRepeating(AlarmManager.RTC_WAKEUP, newCal.getTimeInMillis() - (1000 * 60 * 10), 1000 * 60 * 60, reminderHourly);
            manager.setRepeating(AlarmManager.RTC_WAKEUP, 60000, 1500 * 60, reminderHourly );

            Intent reminderIntent = new Intent(c, reminder.class);
            PendingIntent reminder = PendingIntent.getActivity(c, 0, reminderIntent, 0);
            // manager.setRepeating(AlarmManager.RTC_WAKEUP, newCal.getTimeInMillis(), 1000 * 60 * 60 * 4, reminder );
            manager.setRepeating(AlarmManager.RTC_WAKEUP, 1000 * 60 * 3, 1000 * 60  * 3, reminder );
        }

    }
}

and my Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="midamcorp.com.burgerkingapp"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <service
            android:name=".screenSaver"
            android:enabled="true"
            android:exported="true"
            android:label=""
            android:permission="android.permission.BIND_DREAM_SERVICE">
            <intent-filter>
                <action android:name="android.service.dreams.DreamService" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </service>

        <receiver android:name=".downloadReceiver" />
        <receiver android:name=".bootReceiver"
           >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"></action>
            </intent-filter>
        </receiver>
        <activity android:name=".launch_activity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".lunchHome"
            android:label="@string/title_activity_lunch_home"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".breakfastHome"
            android:label="@string/title_activity_breakfast_home"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".lunchLTOs"
            android:label="@string/title_activity_lunch_ltos"
            android:parentActivityName=".lunchHome"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="midamcorp.com.burgerkingapp.lunchHome" />
        </activity>
        <activity
            android:name=".lunchStandard"
            android:label="@string/title_activity_lunch_standard"
            android:parentActivityName=".lunchHome"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="midamcorp.com.burgerkingapp.lunchHome" />
        </activity>
        <activity
            android:name=".breakfastStandard"
            android:label="@string/title_activity_breakfast_standard"
            android:parentActivityName=".breakfastHome"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="midamcorp.com.burgerkingapp.breakfastHome" />
        </activity>
        <activity
            android:name=".breakfastLTO"
            android:label="@string/title_activity_breakfast_lto"
            android:parentActivityName=".breakfastHome"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="midamcorp.com.burgerkingapp.breakfastHome" />
        </activity>
        <activity
            android:name=".preferences"
            android:label="Preferences"
            android:parentActivityName=".launch_activity">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="midamcorp.com.burgerkingapp.launch_activity" />
        </activity>
        <activity
            android:name=".login"
            android:label="@string/title_activity_login"
            android:parentActivityName=".launch_activity"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="midamcorp.com.burgerkingapp.launch_activity" />
        </activity>
        <activity
            android:name=".buildImage"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:label="@string/title_activity_build_image"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".changePass"
            android:label="@string/title_activity_change_pass"
            android:parentActivityName=".preferences"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="midamcorp.com.burgerkingapp.preferences" />
        </activity>
        <activity
            android:name=".storePicker"
            android:theme="@style/Theme.AppCompat.Dialog" />
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity android:name=".hourlyReminder"
            android:theme="@style/Theme.AppCompat.Dialog.Alert"/>
        <activity android:name=".reminder"
            android:theme="@style/Theme.AppCompat.Dialog.Alert"></activity>
    </application>

</manifest>

This is something that has given me quite some trouble; I genuinely appreciate any help.

1条回答
地球回转人心会变
2楼-- · 2019-07-08 12:54

While this is quite old, I recently encountered a similar issue. the solution was to clean the project, rebuild and regenerate the APK. Not sure exactly is Android Studio caches an old APK, or if something gets messed up with successive builds, but that solved my issue.

Additionally, try manually restarting the app prior to rebooting the phone/issuing the BOOT intent to remove the app from the stopped state.

查看更多
登录 后发表回答