Search code examples
javaandroidservicebroadcastreceiveralarmmanager

Change ImageView picture inside BroadcastReceiver


quick question since I can't figure it out by myself.

First off, I don't want to come out as a begger so I will tell you what I DO know.

This piece of code works great:

package com.edip.splashwallpaper;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.WallpaperManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.Toast;

import com.squareup.picasso.Picasso;

import java.util.UUID;

public class MainActivity extends AppCompatActivity {

    ImageView mImageView;
    Switch mSwitch;
    Bitmap bitmap;

    public class AlarmReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

//                getImage();
                Toast.makeText(MainActivity.this, "AlarmReceiver Works", Toast.LENGTH_SHORT).show();

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        mImageView = (ImageView) findViewById(R.id.imageView);
        mSwitch = (Switch) findViewById(R.id.switch1);

        setAlarmManager(); //TODO zbog ovog mi se gasi AlarmManager. FIX IT!

    }

    private void setAlarmManager(){
        AlarmManager alrm = (AlarmManager) getSystemService(ALARM_SERVICE);
        final String IF_ACTION = "com.edip.splashwallpaper.AlarmReceiver";
        IntentFilter intentFilter = new IntentFilter(IF_ACTION);
        AlarmReceiver mReceiver = new AlarmReceiver();
        registerReceiver(mReceiver, intentFilter);
        Intent i2 = new Intent(IF_ACTION);
        PendingIntent pi = PendingIntent.getBroadcast(this, 2, i2, 0);
        alrm.setRepeating(AlarmManager.RTC, 5000, 60000, pi);
        Toast.makeText(this, "Alarm Started", Toast.LENGTH_SHORT).show();
    }

    public void getImage() {

        String mRandomKey = UUID.randomUUID().toString(); //Generates random string

        Picasso.with(MainActivity.this)
                .load("https://source.unsplash.com/category/nature/1920x1080/")
                .placeholder(R.drawable.placeholder)
                .error(R.drawable.error_placeholder)
                .stableKey(mRandomKey) //new key is new picture
                .into(mImageView);

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                bitmap = ((BitmapDrawable) mImageView.getDrawable()).getBitmap();
                setAsWallpaper(bitmap);
            }
        }, 5000); //adding 5 sec delay

    }

    public void setAsWallpaper(Bitmap bitmap) {
        try {
            WallpaperManager wm = WallpaperManager.getInstance(MainActivity.this);

            wm.setBitmap(bitmap);
            Toast.makeText(this, "New Wallpaper Set", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "Failed to set Wallpaper", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Code is running without error and background image is being changed every XY minutes. Problem is, the BroadcastReceiver class is inside MainActivity class and if the user cleans "recent apps" (or any other type of memory cleaning, i.e. CleanMaster) - AlarmManager Stops.

Now, I tried to make BroadcastReceiver class separately and tested it with Toast, and it works - AlarmManager is not stopped. Problem is, I get NullPointerException when calling getImage() function from MainActivity. My guess is, BroadcastReceiver can't update ImageView of another Activity.

I also tried to put getImage() function in BroadcastReceiver, but then again, I can't set up findViewById(R.id.imageView) in it.

The same thing goes for Service class. Toast works, but can't run getImage() function.

At this point, I really don't know what else to try. Any ideas?


Solution

  • Thank you Selvin for helping me out. The question is now answered.