I am developing an android app with Google+ API. I am having multiple activities which each require one instance of GoogleApiClient.
As I understand from this post it is possible to call the same instance of GoogleApiClient for each activity. My question is how do we create copies of the GoogleApiClient specifically?
Do we build one again with the .addApi(), .addscope() and implement onConnected method and OnConnectedFailedListener method again? Because it seems repetitive and inefficient. And wouldn't implementing these methods override the same methods from other activities too?
It's not expensive to create multiple instances of GoogleApiClient. In fact it will help with efficiency if you use more than just one API. Only the services you specifically request will be spooled up. So if one activity uses Plus and another uses Drive, the Plus service doesn't have to be spooled up when you're on the Drive activity.
To be clear, it is recommended that you create a separate instance of GoogleApiClient for each Activity, Fragment, Loader, Service, or Application that you create (maybe even some others that I forgot too).
If you really don't want to do that, use the application context instead of an activity or fragment to create the GoogleApiClient and hold a reference to it in an Application object.
I have just had this same dilema. To get round this I used the BaseGameUtil... not sure if your using that but if you are then it is simple you can just have each activity extend the BaseGameActivity, add the required methods and then create a GoogleApiClient obj and getApiClient which will then give you the means to use the GoogleApiClient in your second activity.
mGoogleApiClient = getApiClient();
If your not using the BaseGameUtil then i think you would have to create it like you do above which is a pain, at least the basegameutil does it for you, plus you can always change whats in the BGU as they are more examples than libraries.
Hope this helps.
Related
how do i access Googleapiclient in different activities?how do i make it global so that it can be used in all activities
Can we pass it through intent ?
No, you can't pass it via intent. If it needs to be used across activities you either need to make a new one for each Activity or you need to make it owned by a Service that the activities then query for results.
You could use an application class. Its a singelton based class which you can access from almost everywhere.
Documentation for application class : https://developer.android.com/reference/android/app/Application.html
Notify activity from service
I want to know if it is possible to do what the selected answer in the above post said, when your activity and service are in separate packages. Basically i have an object that is non-serializable (lets say a created view) and I want to send it from my service to my activity. Would be easy enough by using a custom binder, but as i've found out, you cant use custom binders when your service and activity are in separate packages.
I've been pondering this for a few weeks and it has really put a block in my project I am working on.
For those who will ask, I am trying to make a framework that allows "plugins" from other packages. But I am unsure how one would send non-serializable date back and forth between said service and activity.
It depends on the complexity of the object, If the object that you want to serialize is an object that comes from the Android SDK lets say a RelativeLayout or a Cursor I don't see that happening anyway, because those objects contains references to another objects that you don't have access to modify or make them implement the Serializable interface.
If your object is a class that you implemented and all references inside that class are also to another classes that you implementad (or to Serializable/Parceable objects) then sure you can. One way of doing so is, well, making them implement Serializable or making your own Parceable theres plenty of tools to achive this in a quick way like this or this one.
If no one of this answers satisfies you, then tell me what're you trying to send from the Service.
EDIT
Did you try to make a class implement both Serializable and OnClickListener and send it through the intent?
Sounds like you need some sort of Command pattern there.
I am trying to write an Android application which uses Bluetooth but ran into some problems. I succeeded in getting things working by following the guide on Android Developers portal. But i want to organize my code a bit and move everything related to Bluetooth to a separate class/src file. I run into a problem already when trying to turn on Bluetooth. As per above mentioned guide this is done with:
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
However my class is not an activity and startActivityForResult is not defined. I can pass my main activity's context to my Bluetooth class and call startActivityForResult on that. This works. But result is then returned to my main activity and again I have to write code into it, instead of my Bluetooth dedicated class.
Alternatively I can make my Bluetooth class extend the Activity class. But then startActivityForResult returns a nullPointer exception (I take it because my "Activity" is not initialized).
I am completely new in Android app development so I am hoping for some pointers about what to look at to help me solve my problem. I would really like to have everything related to Bluetooth in one class/src file so that I can reuse it in any future apps.
All ideas in how to achieve that will be greatly appreciated.
Thank you.
Composition, not inheritance.
Pass the Activity to your BluetoothGodClass as a contructor, store it in an instance variable, and use that to call the respective method. BUT.
What do you really need to do? Does the UI need to control bluetooth? Create a method turnOnBluetooth(Activity activity) and use that. Do you really need to receive the specific result of the activity you called? If not, use a Context or a BroadcastReceiver.
I have a simple Android application that uses an instance of a class, let's call it DataManager, to manage access to the domain classes in a Façade-like way. I initially designed it as a singleton which could be retrieved using static methods but I eventually got irritated with the messiness of my implementation and refactored to what I reckoned was a simpler and cleaner idea.
Now the idea is that for each file that is opened, one DataManager is created, which they handles both file I/O and modification of the domain classes (e.g. Book). When starting a new Activity, I pass this one instance as a Serializable extra (I haven't got on to using Parcelable yet, but expect I will when I have the basic concept working), and then I grab the DataManager from the Intent in the onCreate() method of the new Activity.
Yet comparison of the objects indicates that the object sent from one activity is not identical (different references) to the object retrieved from the Bundle in the second Activity. Reading up on Bundle (on StackOverflow, etc.) suggests that Bundles cannot do anything other than pass-by-value.
So what is likely to be the cleanest and safest strategy for passing an object between Activities? As I see it I could
Forget about passing by reference and live with each Activity having its own DataManager object. Pass back the new DataManager every time I close an activity so that the underlying activity can use it. (The simple solution, I think.)
Go back to using a singleton DataManager and use a static method to get it from each Activity. (Not keen on using singletons again.)
Extend Application to create a sort of global reference to DataManager. (Again, not keen on the idea of globals.)
Is that a fair summary? Is there some other healthy strategy I could use?
Another approach would be to create a service. The first activity would start the service and bind to it, when you launch a new intent, unbind the first activity and when second activity starts, bind to the service.
This way you don't have to ever stop the service or worry about passing data between activities.
Java does not have pass by reference so that option is out, I would suggest dependency injection for passing data between the activities. Otherwise definetely the singleton would be the way to go.
The prescribed one is Going by implementing Parcellable interface, thats the way to pass Objects between Activities.. and the 2nd and better choice is to make a Singleton to be sure its single Object.
Create your DataManager as a Singleton that implements Service. Bind the service to your application in the manifest xml (see the link), and you will have a persistent singleton your activities can access without issues.
Passing parcellable arguments can quickly get very messy if you need to get a lot of data. The singleton approach, although usually considered an anti-pattern, works like a charm in cases like these. Just remember to not create multiple singletons that interact with one another.
I would suggest using an Application Subclass. It allows you to hold a single reference to the DataManger class and is persistent as long as your app lives.
A singleton with a static field will also work, but there are some place in the documentation where it says that the content of static fields is not a safe place to store your data. As I understand static fields should persist as long as your ClassLoader stays in memory. Therefore a singleton should only vanish if the whole process leaves the memory and in that case the application class will also leave the memory, but it will call the onDestroy methods of the Application and that enables you to safely close your DataManager and persist important data to memory.
That said to your two variations.
The Android way to go would be to make your DataManager a ContentProvider. This will make it possible to access your Data from every Activity without holding a global reference. I'm not sure how you would build a caching Content Provider that stays in memory and is not reinstantiated too often.
I'm a little confused by the difference between Java and Android Java. Let's say I have an Activity class AndroidX. There is no main function and there is no AndroidX() constructor as we know it. I realize that onCreate() most probably initializes the AndroidX Activity, but why is there no main? What's the difference?
Consider that your activities are many *main*s and your manifest directs the execution to one of them.
Also consider that the constructor as we know it before is hidden and now it is always called onCreate()
Fair enough to keep going?
This graphic may help some.
http://developer.android.com/images/activity_lifecycle.png
In the Activity documentation they elaborate on what each function is meant for (i.e. onCreate(), onResume(), etc).
http://developer.android.com/reference/android/app/Activity.html
There is no "main" because that assumes that your app is either running or not running. But on android there are many other possible states your app could be in paused, stopped, started, etc...
Check out this link for an excellent overview of the Android Activity lifecycle.
How onCreate works is described in the Activity page of the Android Developer Reference. Specifically here:
onCreate(Bundle) is where you initialize your activity. Most importantly, here you will usually call setContentView(int) with a layout resource defining your UI, and using findViewById(int) to retrieve the widgets in that UI that you need to interact with programmatically.
In a sense you can consider this method the constructor for your Activity, as the initialization is handled there (see the Activity Lifecycle).
As for main, consider it hidden from you. Generally what you do is register listeners for UI elements such as buttons or text fields, then act on input from those UI elements. These listeners handle calls to your methods which might manipulate data or change how the UI displays.