Do I need to put FacebookSdk.sdkInitialize(getApplicationContext()); in every activity? Or just the first activity?
They are asking to initialize it in Application class onCreate() Method.
public class MyApplication extends Application {
// Updated your class body:
#Override
public void onCreate() {
super.onCreate();
// Initialize the SDK before executing any other operations,
FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(this);
}
Link to the original answer
Related
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
When I see this basic source code in MyActivity.java,
onCreate() method is overriding just. but When I run the app, I can see that overrided method "onCreate()" runs. how is this possible?
If its possible to run the onCreate method in that code, I thought there should be a code like
onCreate();
We can always override these functions and add more to it but the Question is how are these functions called automatically when no one is calling them? We haven’t written any code to call them.
This is where the concept of CALLBACK FUNCTIONS comes in.
The concept of callbacks is to inform a class synchronous / asynchronous if some work in another class is done. Some call it the Hollywood principle: "Don't call us we call you".
Here's a example:
class A implements ICallback {
MyObject o;
B b = new B(this, someParameter);
#Override
public void callback(MyObject o){
this.o = o;
}
}
class B {
ICallback ic;
B(ICallback ic, someParameter){
this.ic = ic;
}
new Thread(new Runnable(){
public void run(){
// some calculation
ic.callback(myObject)
}
}).start();
}
interface ICallback{
public void callback(MyObject o);
}
Class A calls Class B to get some work done in a Thread. If the Thread finished the work, it will inform Class A over the callback and provide the results. So there is no need for polling or something. You will get the results as soon as they are available.
In Android Callbacks are used f.e. between Activities and Fragments. Because Fragments should be modular you can define a callback in the Fragment to call methods in the Activity. copied from here
for more study follow this link please :
link 1
link 2
The onCreate method is called during the Activity Lifecycle. The docs regarding this method state
You must implement this callback, which fires when the system first creates the activity
So the point of this method is for you to initialize anything specific to your activity that needs to be done when it is first created, and call super to propagate this to it's superclasses, allowing them to perform their initialization sequence as well. You should not be invoking this method yourself.
Fresco is not working when I am initializing it in the OnCreate or OnCreateView of the fragment. Is there something I am doing wrong?
You have to initialize Fresco only once, in your custom Application.
Example:
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
Fresco.initialize(this);
}
}
More info: http://frescolib.org/docs/
Just to make it clear, this is not I want. I want to access another Activity's context.
Suppose I've two activities, MainActivity and WebActivity. In MainActivity I used oAuth2 login, and after login I start the WebActivity. In WebActivity I need to logout with the function mTencent.logout(MainActivity.this);, the question is how can I access MainActivity from WebActivity?
If I do this directly, I get the error,
MainActivity is not an enclosing class?
Considering I'm a starter of android, here may be not the exact way to implement it.
Will someone help? Thank you!
The API : void com.tencent.tauth.Tencent.logout(Context context)
Use Application context in your login and logout methods. As they will be managed at Application level.
So change mTencent.logout(MainActivity.this); to mTencent.logout(getApplicationContext());.
Also change your login method to work in application context.
Instead of using context of one activity in other which may result in crashes sometimes.
u can use libraries like EventBus to link the code.
Define a class which implements event u want to perform eg:LogOutEvent.java
public static class LogOutEvent { /* Additional fields if needed */ }
U can post events like logout from WebViewActivity.java using following command
EventBus.getDefault().post(new LogOutEvent());
and in MainActivity you first need to register event bus
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
and then in MainActivity you can subscribe for events like this
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(LogOutEvent event) {/* Do log out here */};
There is a good practice solution to your problem which involves certain steps to be performed:
1- Define an interface:
public interface LogOutInterface {
public void logout();
}
2- Have your MainActivity implement this interface:
public class MainActivity extends ???? implements LogOutInterface {
...
#Override
public void logout(){
//your logout procedure
}
}
3- Have a public method for your WebActivity and allow it to accept LogOutInterface:
public class WebActivity ... {
private LogOutInterface logoutInterface;
...
public void setLogOut(LogOutInterface logoutInterface) {
this.logoutInterface = logoutInterface;
}
}
4- call setLogOut from MainActivity:
public class MainActivity ... {
public void yourmethod() {
...
webActivity.setLogOut(this);
}
}
5- call logout function from your WebActivity:
public class WebActivity ... {
...
public void yourmethod() {
logoutInterface.logout();
}
}
hope this helps.
This is a workable one.
In the MainActivity, public static Activity thisActivity; & thisActivity = this; then in the WebActivity mTencent.logout(MainActivity.thisActivity);
or just can put the logout function as public static function of MainActivity,
public static void logout() {
if (mTencent.isSessionValid()) {
mTencent.logout(thisActivity);
}
}
then call MainActivity.logout() from WebActivity.
I have an Android application that is binding to a persistent service (once started with startService()).
The service is an integral part of the application and thus is used in almost every Activity. Hence I want to bind to the service just once (instead of binding/unbinding in every Activity) and keep the binding during the lifetime of my application.
I've extended from Application and bind to the service in Application#onCreate(). However I now have the problem that I don't know when my application exists since Application#onTerminate() is never called, see JavaDoc:
This method is for use in emulated process environments. It will never
be called on a production Android device, where processes are removed
by simply killing them; no user code (including this callback) is
executed when doing so.
So how do I cleanly unbind from a service bound in Application?
I solved this problem by counting the references to the service binding in the Application. Every Activity has to call acquireBinding() in their onCreate() methods and call releaseBinding() in onDestroy(). If the reference counter reaches zero the binding is released.
Here's an example:
class MyApp extends Application {
private final AtomicInteger refCount = new AtomicInteger();
private Binding binding;
#Override
public void onCreate() {
// create service binding here
}
public Binding acquireBinding() {
refCount.incrementAndGet();
return binding;
}
public void releaseBinding() {
if (refCount.get() == 0 || refCount.decrementAndGet() == 0) {
// release binding
}
}
}
// Base Activity for all other Activities
abstract class MyBaseActivity extend Activity {
protected MyApp app;
protected Binding binding;
#Override
public void onCreate(Bundle savedBundleState) {
super.onCreate(savedBundleState);
this.app = (MyApp) getApplication();
this.binding = this.app.acquireBinding();
}
#Override
public void onDestroy() {
super.onDestroy();
this.app.releaseBinding();
}
}
From Sven's answer:
I solved this problem by counting the references to the service
binding in the Application. Every Activity has to call
acquireBinding() in their onCreate() methods and call releaseBinding()
in onDestroy(). If the reference counter reaches zero the binding is
released.
I agree, BUT you shouldn't do it in onDestroy - that will often not get called.
Instead I suggest the following (based on your code sample)...
// Base Activity for all other Activities
abstract class MyBaseActivity extend Activity {
protected MyApp app;
protected Binding binding;
#Override
public void onCreate(Bundle savedBundleState) {
super.onCreate(savedBundleState);
this.app = (MyApp) getApplication();
this.binding = this.app.acquireBinding();
}
#Override
protected void onPause() {
super.onPause();
// Pre-HC, activity is killable after this.
if ((11 > Build.VERSION.SDK_INT) && (isFinishing()))
onFinishing();
}
#Override
protected void onStop() {
super.onStop();
if ((10 < Build.VERSION.SDK_INT) && (isFinishing()))
onFinishing();
}
protected void onFinishing() {
// Do all activity clean-up here.
this.app.releaseBinding();
}
}
BUT, my use of isFinishing() is just a thought - I'm not certain that it is reliable. Perhaps onPause/onStop get called with isFinishing() false, but then the activity gets killed - and your releaseBinding() never gets called.
If you get rid of the isFinishing check I think you need to move the acquireBinding() call from onCreate to onStart/onResume (depending on sdk version), to ensure that your ref count doesn't get messed up.
Who knew that releasing your app's service would be so complicated!
Is unbinding necessary at all in this case? The application gets killed anyway. I tried implementing a sample application doing this without unbinding and it seems to work properly.
Actually i have created an singleton class. Now my singleton class extends Activity, and i have write onCreate() and onStart() method on this class. But it is never called.The code i have used is shown below. If anyone knows help me to solve these out.
Code
public class cycleManager
{
private static CycleManager m_cycleManagerObj;
private CycleManager()
{
// Initialise Variable
onInitialization();
readData(this); // show error when call from here
}
public static synchronized CycleManager getSingletonObject()
{
if (m_cycleManagerObj == null)
{
m_cycleManagerObj = new CycleManager();
}
return m_cycleManagerObj;
}
public Object clone() throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
}
public void writeData(Context c)
{
SharedPreferences preferencesWrite = c.getSharedPreferences("myPreferences", 0);
SharedPreferences.Editor editor = preferencesWrite.edit();
// work to be done
}
public void readData(Context c)
{
SharedPreferences preferencesRead = c.getSharedPreferences("myPreferences", 0);
// work to be done
}
}
The thing is Android manages activities in its own manner: from calling a constructor to calling all lifecycle methods. So if you declare your Activity's constructor as private then Android will not be able to manage this activity.
Why do you need singleton Activity-class? Consider different launch modes
check your activity in the AndroidManifest.xml.
<activity
android:configChanges="orientation|keyboardHidden"
android:name=".ActivityName">
They are not public method.They are protected method.You should override existing method.try like the following.
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
The key here is that Android is supposed to be managing your activity lifecycle, not you.
onCreate and onStart (along with onPause, onDestroy and all the other android activity lifecycle functions) are called by the looper on Android's main thread.
How did you start this activity? Was it declared in your manifest as your main activity and launcher? Did you call startActivity and pass the class name?
The fact that you are creating a singleton instance of your activity, and that its constructor is private, suggests to me that Android would be unable to start this activity when you want it to, though some function for passing an existing activity to be managed may exist, and I've just never seen it.
If onCreate and onStart are never being called, it means Android doesn't know it is supposed to be running your activity.
You get an error because your class is not a subclass of Context. Add Context attribute to getSingletonObject(Context context) method and pass it to CycleManager(Context context) constructor.