Search code examples
androidservicebroadcastreceiversharedpreferences

The Service not lunching after device reboot ...!


hey i have service its wallpaper service (not live wallpaper) so when I enter the app i have 5 radio buttons every button decide the time that the wallpaper changes and I have a button that triggers the service and i got response from my server even when i close the app but.... when i restart the device i get 1 response only and the wallpaper not changing lets say i was choised for every 4 second to change just when i reboot it stops and like i said i receive just one response from my server and stops even the wallpaper don't change with this response take a look at my code you will understand more (I used receiver and boot primission but ... );

MainActivity;

private final static int INTERVAL = 4000; //10 min
private final static int INTERVAL2 = 1000*60*30; // 30 min
private final static int INTERVAL3 = 1000 * 60 * 120; // 2 hours
private final static int INTERVAL4 = 1000 * 60 * 360; // 6 hours min
private final static int INTERVAL5 = 1000 * 60 * 1440; // 1 day

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    rd1 = (RadioButton) findViewById(R.id.radioButton);
    rd2 = (RadioButton) findViewById(R.id.radioButton2);
    rd3 = (RadioButton) findViewById(R.id.radioButton3);
    rd4 = (RadioButton) findViewById(R.id.radioButton4);
    rd5 = (RadioButton) findViewById(R.id.radioButton5);

    radioGroup = (RadioGroup) findViewById(R.id.radiogroup);
    mHandler = new Handler();
    btn = (Button) findViewById(R.id.button);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(MainActivity.this , WallService.class);
            PendingIntent pintent = PendingIntent.getService(MainActivity.this, 0, intent, 0);
            AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
            alarm.cancel(pintent);
            if (rd1.isChecked()) {

                alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),INTERVAL, pintent);
            } else if (rd2.isChecked()) {
                alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),INTERVAL2, pintent);
            }else if (rd3.isChecked()) {
                alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),INTERVAL3, pintent);
            }else if (rd4.isChecked()) {
                alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),INTERVAL4, pintent);
            }else if (rd5.isChecked()) {
                alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), INTERVAL5, pintent);
            }
        }
    });
}

service

 String forecastJsonStr;

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onStart(Intent intent, int startId) {


    final Thread thread1 = new Thread(new Runnable() {
        @Override
        public void run() {
            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;


            try {

                URL url = new URL("yay.php");

                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("POST");
                urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                urlConnection.setDoInput(true);
                urlConnection.setDoOutput(true);
                urlConnection.connect();
                DataOutputStream wr = new DataOutputStream(
                        urlConnection.getOutputStream());
                wr.write("method=get_random_wallpaper".getBytes());
                wr.flush();
                wr.close();

                InputStream inputStream = urlConnection.getInputStream();
                StringBuffer buffer = new StringBuffer();
                if (inputStream == null) {
                }
                reader = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                while ((line = reader.readLine()) != null) {

                    buffer.append(line + "\n");
                    Log.d("hey", buffer.toString());

                }

                if (buffer.length() == 0) {
                }
                forecastJsonStr = buffer.toString();

            } catch (IOException e) {
                Log.e("PlaceholderFragment", "Error ", e);

            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();

                    } catch (final IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        }

    });
    thread1.start();

     Thread thread = new Thread(new Runnable() {

        @Override
        public void run() {

            WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
            try {

                Bitmap result = Picasso.with(getBaseContext())
                        .load(hostName + hostWallpaperName +   forecastJsonStr)
                        .get();
                wallpaperManager.setBitmap(result);
            } catch (IOException ex) {
                ex.printStackTrace();
            }

        }

    });
    thread.start();
}



@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
}

receiver

 public void onReceive(Context context, Intent intent) {
    if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
        Intent pushIntent = new Intent(context, WallService.class);
        context.startService(pushIntent);

manifest

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mike.lol8">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SET_WALLPAPER" />
<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">
    <receiver android:name=".BootCompletedIntentReceiver"
        android:enabled="true"
        android:exported="true"
        >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>
    <service android:name=".WallService"
        android:enabled="true"
        android:exported="true">

    </service>
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>


Solution

  • After device reboot alarms set in Alarm manager are cleared - docs

    You need to initialize Alarm manager again in your on BOOT_COMPLETED receiver. You can use sharedPrefference to store the time you need to set your alarms In onClick of the activity add SharedPreference preference = PreferenceManager.getDefaultSharedPreference(this); preference.edit.putInt("timeInterval",INTERVAL).apply;

    Then in onReceive in the receiver:

    SharedPreference preference = 
    
    PreferenceManager.getDefaultSharedPreference(this);
    int interval = preference.getInt("timeInterval", 4000);
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),interval, pintent);