I am using Android Room to store my application data. After device reboot I need to retrieve them and do some functions. I am using LiveData for getting data from database. But I cannot bind Broadcast Reciever as owner. How should I resolve this problem?
public class BootReciever extends BroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
if (context != null) {
ProductUIRepository mRepository = new ProductUIRepository(context.getApplicationContext());
mRepository.findAllProducts().observe(this, new android.arch.lifecycle.Observer<List<ProductUI>>() {
#Override
public void onChanged(#Nullable List<ProductUI> productUIS) {
NotificationMan.setAlarmForProducts(context, productUIS);
}
});
}
}
}
using "this" makes that applications isn't compiling.
Related
I am developing an Android app. In my app, I am deleting data from database when app is closed. So I open broadcast receiver onDestroy and delete data inside receiver. When I call delete method of database helper inside Activity, it is working. But when I call it inside receiver, it is not working.
This is my receiver:
public class InspectDataReceiver extends BroadcastReceiver {
private DatabaseHelper dbHelper;
#Override
public void onReceive(final Context context, Intent intent) {
}
public void refreshData(final Context context,String type)
{
dbHelper = new DatabaseHelper(context);
dbHelper.deleteCategories();
} }
This is delete method of database helper:
public void deleteCategories()
{
db = getWritableDatabase();
db.delete(CATEGORY_TABLE,null,null);
db.close();
}
This is how I delete data in the onDestroy event of my activity:
#Override
protected void onDestroy() {
super.onDestroy();
updateCacheData();
}
private void updateCacheData()
{
InspectDataReceiver receiver = new InspectDataReceiver();
receiver.refreshData(getBaseContext(),getResources().getString(R.string.data_receiver_type_category));
}
But data are not deleted.It is not throwing error as well. When I delete within activity. Delete method is working. How can I fix it?
you are not doing anything inside onReceive(), you need to call refreshData():
#Override
public void onReceive(final Context context, Intent intent) {
refreshData(context);
}
or call deleteCategories() method directly:
#Override
public void onReceive(final Context context, Intent intent) {
dbHelper = new DatabaseHelper(context);
dbHelper.deleteCategories();
}
in second case you dont need to define refreshData() in the receiver class
I am trying to implement an architecture similar to the one presented at the Android Developer Summit 2015: https://github.com/yigit/dev-summit-architecture-demo. My application has a simple class that handles the network requests. The class uses Retrofit 2 for the requests. I am also using Dagger 2 for dependency injection.
I am trying to achieve something very simple. My activity tells a controller to fetch data. The controller then makes a call to my REST client to perform a network request. When the request completes successfully I want to broadcast an event to my Activity so that it can update the UI. However, the event is not being broadcast.
I am using the LocalBroadcastManager to broadcast events. My activity registers/unregisters for broadcasts in the onResume/onPause methods. My REST client has an instance of the application context which is provided through dependency injection. The REST client uses the application context to send the broadcast.
My first suspicion was that the broadcasts were not being sent because the network requests are executed on a worker thread whereas the activity is expecting broadcasts on the main thread. However, this type of scenario shouldn't be a problem if the Android documentation is correct.
This is my activity.
public class BaseActivity extends AppCompatActivity {
private ApplicationComponent mApplicationComponent;
private EventBroadcastReceiver mEventBroadcastReceiver = new EventBroadcastReceiver();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mApplicationComponent = getMovieManagerApplication().getApplicationComponent();
}
#Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("now_playing");
LocalBroadcastManager.getInstance(this).registerReceiver(mEventBroadcastReceiver, intentFilter);
}
#Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mEventBroadcastReceiver);
}
protected MovieManagerApplication getMovieManagerApplication() {
return (MovieManagerApplication) getApplication();
}
protected ApplicationComponent getApplicationComponent() {
return mApplicationComponent;
}
protected void update(Intent intent) {
}
private class EventBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
update(intent);
}
}
}
And this is my REST client.
public class MovieRestClient extends BaseRestClient implements Callback<MovieResponse> {
#Inject
public MovieApiService mMovieApiService;
#Inject
public Context mApplicationContext;
public MovieRestClient(ApplicationComponent applicationComponent) {
super(applicationComponent);
getApplicationComponent().inject(this);
}
#Override
public void onResponse(Response<MovieResponse> response) {
if (response.isSuccess()) {
Parcelable parcelable = Parcels.wrap(response.body());
MovieResponse movieResponse = Parcels.unwrap(parcelable);
Intent intent = new Intent("now_playing");
intent.putExtra(MovieResponse.class.getName(), parcelable);
LocalBroadcastManager.getInstance(mApplicationContext).sendBroadcast(intent);
}
}
#Override
public void onFailure(Throwable t) {
}
public void getNowPlaying() {
mMovieApiService.getNowPlaying(API_KEY).enqueue(this);
}
public void getPopular() {
mMovieApiService.getPopular(API_KEY).enqueue(this);
}
public void getTopRated() {
mMovieApiService.getTopRated(API_KEY).enqueue(this);
}
public void getUpcoming() {
mMovieApiService.getUpcoming(API_KEY).enqueue(this);
}
}
Any help would be greatly appreciated.
I have a class structure as below
public class Admin extends DeviceAdminReceiver
{
public static class PubSub extends Activity
{
protected void onCreate(Bundle savedInstanceState) {
messageIntentReceiver = new MQTTMessageReceiver();
IntentFilter intentCFilter = new IntentFilter(MQTTService.MQTT_MSG_RECEIVED_INTENT);
registerReceiver(messageIntentReceiver, intentCFilter);
}
#Override
protected void onDestroy()
{
unregisterReceiver(messageIntentReceiver);
super.onDestroy();
}
public class MQTTMessageReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Bundle notificationData = intent.getExtras();
String newTopic = notificationData.getString(MQTTService.MQTT_MSG_RECEIVED_TOPIC);
String newData = notificationData.getString(MQTTService.MQTT_MSG_RECEIVED_MSG);
Log.e("Received Message on",newTopic+"- "+newData);
}
}
}
}
The receivers are dynamically registered and unregistered. The broadcast receiver works while PubSub activity stays on the screen. How to make it work from outside of activity?
I tried to do it in static way by registering in manifest.xml, but that dint work as MQTTMessageReceiver is a non static inner class. Cant able to instantiate the receiver runtime error I get.
I cant change the MQTTMessageReceiver class static as i need to access outer class members.
I've set up a class called NetworkStatus that monitors the network status of the device. Within NetworkStatus I've defined a BroadcastReceiver that monitors if there has been a connectivity change, i.e., if the internet has been switched off or on. I want to 'expose' this method (i.e. onReceive) to the activity that instantiated the instance of NetworkStatus.
I'm trying to achieve this by setting up an interface in the NetworkStatus class, but I'm not sure how to call the interface from the onReceive method of the BroadcastReceiver i.e.,
public class NetworkStatus {
public static interface NetworkStatusCallbacks {
void onReceive();
}
public static class ConnectivityChange extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
// need to call NetworkStatusCallbacks onReceive here
}
}
}
Then in the main activity I would do something like,
public class MyActivity extends Activity implements NetworkStatus.NetworkStatusCallbacks {
#Override
public void onReceive() {
// Do stuff here
}
}
Would really appreciate some pointers. Thanks.
Possible Solution
Think I have found a solution. As Selvin pointed out, to do this requires the Activity. I therefore obtained the Activity by casting it from the activity context that is passed to a constructor for the NetworkStatus class, i.e., setting a constructor for the class as
private static nsc NetworkStatusCallbacks;
public NetworkStatus (Context context) {
Activity activity = (Activity) context;
nsc = (NetworkStatusCallbacks) activity;
}
I can then call the interface from the onReceive method of the BroadcastReceiver as follows:
public void onReceive(Context context, Intent intent) {
nsc.onReceive();
}
Try something like this:
public class NetworkStatus {
public static interface NetworkStatusCallbacks {
void onReceive();
}
private final NetworkStatusCallbacks m_cb;
NetworkStatus(NetworkStatusCallbacks cb)
{
m_cb=cb;
}
public static class ConnectivityChange extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
// need to call NetworkStatusCallbacks onReceive here
m_cb.onReceive()
}
}
}
I want to dynamically control location tracking (registering / unregistering location broadcast receiver). This is how I am planning to do it. I have two questions :
What are the mistakes in the implementation below because all this concept is still very theoretical to me as I am very new to android/java dev. Still building concepts!
How do I pass some EXTRA_INFO from my location library class to the location receiver.
IMPLEMENTATION:
I have a library class LocationLibrary.java which consists of two methods. They do as the name suggest. The location tracking should start when I call startTracking(). Plz note the extraInfo that needs to be passed to myLocationReceiver. The tracking should stop when stopTracking() is called.
Code snippet:
public class LocationLibraray
{
private static BroadcastReceiver myLocationReceiver;
public LocationLibraray(Context context)
{
this.ctx = context;
myLocationReceiver = new MyLocationReceiver();
}
public void startTracking(Context context, String extraInfo)
{
IntentFilter filter = new IntentFilter();
filter.addAction("com.app.android.tracker.LOCATION_READY");
context.registerReceiver(myLocationReceiver, filter);
// NEED TO PASS extraInfo to myLocationReceiver for some processing, but HOW?
}
public void stopTracking(Context context)
{
context.unregisterReceiver(locationReceiver);
}
}
MyLocationReceiver.java
public class MyLocationReceiver extends BroadcastReceiver {
public void onReceive(final Context context, Intent intent) {
if ((intent.getAction() != null) &&
(intent.getAction().equals("com.app.android.tracker.LOCATION_READY")))
{
//GET THAT EXTRA INFO FROM LocationLibrary class and process it here
}
}
}
Please help me out. Thnx!
Why not add a constructor to MyLocationReceiver?
public class MyLocationReceiver extends BroadcastReceiver {
String info = "";
public MyLocationReceiver(String extraInfo)
{
this.info = extraInfo;
}
........
public void onReceive(final Context context, Intent intent) {
if ((intent.getAction() != null) &&
(intent.getAction().equals("com.app.android.tracker.LOCATION_READY")))
{
if (info.contains("Hi"))
//do some stuff
}
}
}
And you would instantiate it like this:
myLocationReceiver = new MyLocationReceiver(new String("Hello!"));