Google Analytics v4 cannot be cast to Analytics - java

I try to implement the Google Analytics in my App.
The Problem is I get in LogCat the message:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.name.appname/com.name.appname.activity.MainActivity}: java.lang.ClassCastException: com.name.appname.misc.AppApplication cannot be cast to com.name.appname.activity.Analytics
global_tracker.xml
<integer name="ga_sessionTimeout">300</integer>
<!-- Enable automatic Activity measurement -->
<bool name="ga_autoActivityTracking">true</bool>
<!-- Enable verbose logging -->
<String name="ga_loglevel">verbose</String>
<!-- Screen names on the reports -->
<screenName name="com.name.appname.activity.MainActivity">
MainActivity ScreenView
</screenName>
<!-- Tracking ID -->
<string name="ga_trackingId">UA-xxxxxxx-2</string>
ANALytics.java:
public class Analytics extends Application {
public static int GENERAL_TRACKER = 0;
public enum TrackerName {
APP_TRACKER, // Tracker used only in this app.
GLOBAL_TRACKER, // Tracker used by all the apps from a company. eg: roll-up tracking.
ECOMMERCE_TRACKER, // Tracker used by all ecommerce transactions from a company.
}
HashMap<TrackerName, Tracker> mTrackers = new HashMap<TrackerName, Tracker>();
synchronized Tracker getTracker(TrackerName trackerId) {
if (!mTrackers.containsKey(trackerId)) {
GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
Tracker t = analytics.newTracker(R.xml.global_tracker);
mTrackers.put(trackerId, t);
}
return mTrackers.get(trackerId);
}
}
manifest:
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:name=".misc.AppApplication" >
<activity
android:name=".activity.Analytics"
android:allowBackup="true"
android:label="#string/app_name"
android:screenOrientation="portrait" >
</activity>
MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adView = (AdView) this.findViewById(R.id.adView);
// Get tracker.
Tracker tracker = ((Analytics)getApplication()).getTracker(Analytics.TrackerName.GLOBAL_TRACKER);
tracker.send(new HitBuilders.EventBuilder()
.setCategory("Use")
.setAction("Use Programm")
.setLabel("submit")
.build());
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
GoogleAnalytics.getInstance(MainActivity.this).reportActivityStart(this);
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
GoogleAnalytics.getInstance(MainActivity.this).reportActivityStop(this);
}
In my manifest i have already declared android:name=".misc.AppApplication" at application. there is my check for PremiumUsers.
Here is my misc.AppApplication:
import android.app.Application;
public class AppApplication extends Application {
private boolean mIsPremium;
public void setPremium(){
mIsPremium = true;
}
public boolean isPremium(){
return mIsPremium;
}
}
where is the problem?

You are setting the name attribute of your application element in the manifest to ".misc.AppApplication". That instructs Android to instantiate .misc.AppApplication class as application instead of the default Application. In your MainActivity class you try to cast .misc.AppApplication to Analytics and that will throw ClassCastException.
The correct setup is to replace the Application class with Analytics (the class that extends Android Application class) and keep MainActivity as the class implementing your main activity.
You should also not be logging events from onCreate override. Activity can be created for reasons other then starting the app. For example when the device changes from landscape to portrait mode Android will ask the activity to save its state to a bundle, tear it down and recreate it passing the saved state in savedInstanceState. onCreate will be called in this case again.

Related

How do you use a Google MapView inside of a Fragment?

Desired Behavior
In case it affects any answers or suggestions, what I would like to ultimately see in this app is a navigation UI where one of the Fragment is a map. I used a template to start with a navigation UI, which gave me several Fragments, one for each tab. Currently, I'm trying to use the Google API to put a MapView inside of one of those Fragments.
Current Behavior
Generally, this isn't working (obviously). I have everything up and running, but when I pull up the tab with the map in it, the map is blank. Nothing crashes, and no errors are output:
I/Google Maps Android API: Google Play services client version: 12451000
I/Google Maps Android API: Google Play services package version: 201516040
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
I/DynamiteModule: Considering local module com.google.android.gms.googlecertificates:0 and remote module com.google.android.gms.googlecertificates:4
Selected remote version of com.google.android.gms.googlecertificates, version >= 4
Other Details/Troubleshooting
I know that my API key works because I have another app in which the maps work as expected. I doubt I need a second API key, but I looked anyway and since it wasn't overly obvious how to create a second API key, I think that hunch is correct. Most of the code I'm using was copied from that working example; the primary difference is that other example uses a SupportMapFragment and it has a class MapsActivity extends FragmentActivity. Here, since I don't really want to deal with nesting fragments, I'm trying to use a MapView inside that fragment.
What bits of my code that weren't copied largely came from online sources. None of what I've tried has produced better results.
MapView inside fragment is answering a different problem
Creating google maps v2 in a fragment using Navigation Drawer contains only things I already have
android MapView in Fragment gave me the idea to use MapsInitializer.initialize(this.getActivity()); but that didn't help
Mapview in separate fragment android has nothing new
how do i solve integrating google map in fragment in android uses a Fragment not a MapView
I also know that onMapReady is being called. Inside of that, I move the camera and that subsequently calls onCameraMoveStarted. However, it does not enter onCameraMove or onCameraIdle.
Code
This is the code as it is, which uses some of the ideas from the above links. I tried to cut out anything that's unrelated (other fragments, etc)
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.retailtherapy">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:windowSoftInputMode="stateVisible|adjustResize" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
</manifest>
activity_main.xml
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/nav_view"
app:menu="#menu/bottom_nav_menu" />
<fragment
android:id="#+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
app:defaultNavHost="true"
app:navGraph="#navigation/mobile_navigation"
tools:context=".MainActivity" />
</androidx.constraintlayout.widget.ConstraintLayout>
mobile_navigation.xml
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/mobile_navigation"
app:startDestination="#+id/navigation_map">
<fragment
android:id="#+id/navigation_map"
android:name="com.example.retailtherapy.ui.map.MapFragment"
android:label="Map"
tools:layout="#layout/fragment_map" />
</navigation>
fragment_map.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.map.MapFragment" >
<com.google.android.gms.maps.MapView
android:id="#+id/googleMap"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
MapFragment.java
public class MapFragment extends Fragment implements OnMapReadyCallback, LocationListener {
/*************************************************************************
*
* M E M B E R S
*
*/
// Location manager for getting current location
private LocationManager mLocationManager = null;
// The map object for reference for ease of adding points and such
private GoogleMap mGoogleMap = null;
private MapView mMapView = null;
// The camera position tells us where the view is on the map
private CameraPosition mCameraPosition = Constants.GetDefaultCameraPosition();
// Current latitude and longitude of user
private LatLng mCurrentLatLong = new LatLng(0.0, 0.0);
// These are flags that allow us to selectively not move the camera and
// instead wait for idle so the movement isn't jerky
private boolean mCameraMoving = false;
private boolean mPendingUpdate = false;
/*************************************************************************
*
* F R A G M E N T
*
*/
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View root = inflater.inflate(R.layout.fragment_map, container, false);
// The google map...
MapsInitializer.initialize(getActivity());
mMapView = (MapView) root.findViewById(R.id.googleMap);
mMapView.onCreate(savedInstanceState);
mMapView.getMapAsync(this);
// The required permissions...
final String[] REQUIRED_PERMISSIONS = {
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.INTERNET,
};
requestPermissions(REQUIRED_PERMISSIONS, 0);
return root;
}
#Override
public void onStart() throws SecurityException {
super.onStart();
// Location manager for getting info current location
mLocationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onDestroyView() {
super.onDestroyView();
mMapView.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mMapView.onSaveInstanceState(outState);
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
/*************************************************************************
*
* G O O G L E M A P S
*
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
// Assuming if here that we have permissions okay. Dangerous sure
// but I'm lazy...
mGoogleMap.setMyLocationEnabled(true);
// Store the location of the camera for UI purposes so we can go
// back to where we were
mGoogleMap.setOnCameraMoveListener(new GoogleMap.OnCameraMoveListener() {
#Override
public void onCameraMove() {
mCameraPosition = mGoogleMap.getCameraPosition();
}
});
mGoogleMap.setOnCameraMoveStartedListener(new GoogleMap.OnCameraMoveStartedListener() {
#Override
public void onCameraMoveStarted(int i) {
mCameraMoving = true;
}
});
mGoogleMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
#Override
public void onCameraIdle() {
mCameraMoving = false;
if (mPendingUpdate) {
centerCameraOnLocation(false);
}
}
});
// Start with user centered in view
centerCameraOnLocation(true);
}
/*************************************************************************
*
* L O C A T I O N
*
*/
#Override
public void onLocationChanged(Location location) {
// Store the current location so if we start auto-center but aren't
// already, we know where to pan to
LatLng newLatLng = new LatLng(location.getLatitude(), location.getLongitude());
if (!newLatLng.equals(mCurrentLatLong)) {
mCurrentLatLong = new LatLng(location.getLatitude(), location.getLongitude());
centerCameraOnLocation(false);
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
/*************************************************************************
*
* M A P C A M E R A
*
*/
/*
* Updates the camera position based on current state. If the camera is
* already moving, then wait.
*/
private void centerCameraOnLocation(boolean animate) {
if (mGoogleMap == null) {
return;
}
if (mCameraMoving) {
mPendingUpdate = true;
return;
}
// Get the CameraPosition to update to based on whether we are auto
// centering or not.
if (mCameraPosition == null) {
mCameraPosition = Constants.GetDefaultCameraPosition();
}
// If this is the same as it was before, then don't reset it
if (mCameraPosition.equals(mGoogleMap.getCameraPosition())) {
return;
}
// Make the update so we can move the camera
CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(mCameraPosition);
// Move the camera with or without animation. The time we don't want
// animation is when we're setting the position initially
if (animate) {
mGoogleMap.animateCamera(cameraUpdate);
}
else {
mGoogleMap.moveCamera(cameraUpdate);
}
mPendingUpdate = false;
}
}
FINALLY I found the answer in a comment at https://stackoverflow.com/a/51464293/3038157.
Basically, it seems there was something stale. Without changing any code, I uninstalled the app, cleaned the build, rebuilt, and voila it worked.
You must forward all the life cycle methods from the Activity or Fragment containing this view to the corresponding ones in this class.
View this official guide
or example code
// *** IMPORTANT ***
// MapView requires that the Bundle you pass contain _ONLY_ MapView SDK
// objects or sub-Bundles.

ClassCastException android

This is my Main App
public class MainApp extends Application {
private MainComponent component;
private static Context context;
public MainApp() {
this.component = initDagger();
context = getApplicationContext();
}
public MainComponent getComponent() {
return component;
}
public static Context getContext() {
return context;
}
private MainComponent initDagger() {
return DaggerMainComponent.builder().build();
}
}
In main activity I use these codes below and receive an error
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
unbinder = ButterKnife.bind(this);
((MainApp) getApplication()).getComponent().inject(this);
// presenter = new MainActivityPresenter();
presenter.attachView(this);
}
This is the error that I received. It said that I cannot cast Application to MainApp. But I follow dagger example and I see that they do this and it works.
What is the problem with my code
Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to com.example.huytrinh.sampledagger.MainApp
at com.example.huytrinh.sampledagger.MainActivity.onCreate(MainActivity.java:39)
at android.app.Activity.performCreate(Activity.java:5360)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2336)
In Manifest add your name to application tag
<application
android:name=".MainApp"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
1.Your are getting exception because you dint include the custom application class in manifest.Add the class in manifest like this.
<application
android:name=".MainApp"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
2.Create dagger class and other things only after application is created i.e in oncreate of the application class
#Override
public void onCreate() {
super.onCreate();
this.component = initDagger();
context = getApplicationContext();
}
Try this.
First
To get MainApp
private static MainApp instance;
public
static MainApp getInstance() {
return instance;
}
#Override
public void onCreate() {
super.onCreate();
instance = this;
}
Second
MainApp.getInstance().getComponent().inject(this);
Edit
<application
android:name=".MainApp"
... />

Add list item in RecyclerView Adapter on receiving Firebase message

I'm using the firebase messaging service for messaging and notifications. I can't seem to be able to pass an incoming message from the service to the adapter so that when the message is received it can be inserted into the RecycleView List.
I tried using BroacastIntent as follows :
public class messaging extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage m) {
store(m.getData());
broadcastIntent();
}
public void broadcastIntent() {
Intent intent = new Intent();
intent.setAction("com.myApp.CUSTOM_EVENT");
sendBroadcast(intent);
}
}
and in the Adpter
public class ConvoAdapter extends RecyclerView.Adapter<ConvoHolder> {
private List<Message> list;
private Activity A;
public ConvoAdapter(List<Message> data) {
}
#Override
public ConvoHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(layout, parent, false);
return new ConvoHolder(v);
}
#Override
public void onBindViewHolder(ConvoHolder h, int Position) {
final Message M = list.get(Position);
h.config(A, M);
}
#Override
public int getItemCount() {
return list.size();
}
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Intent Detected.", Toast.LENGTH_LONG).show();
}
}
}
And manifest.
<receiver android:name=".fragments.chats.ConvoAdapter$MyReceiver"
android:enabled="true"
android:exported="false" >
<intent-filter>
<action android:name="android.intent.action.CUSTOM_EVENT">
</action>
</intent-filter>
</receiver>
As is, the broadcast receiver is not receiving any messages.
I'd also use any other method that doesn't involve using broadcast receivers.
The flow or architecture of your is not a standard practice.
The standard flow should be
Firebase service
Some activity or fragment with BroadcastReceiver using LocalBroadcastManager
1. Firebase Service
public class messaging extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage m) {
store(m.getData());
broadcastIntent();
}
public void broadcastIntent() {
Intent intent = new Intent();
intent.setAction("com.myApp.CUSTOM_EVENT");
// We should use LocalBroadcastManager when we want INTRA app
// communication
LocalBroadcastManager.getInstance(YOUR_CONTEXT).sendBroadcast(intent);
}
}
2. Activity
Registering Receiver for broadcast from Service
public void onCreate(Bundle savedInstance) {
// REST OF YOUR CODE
IntentFilter if= new IntentFilter("com.myApp.CUSTOM_EVENT");
LocalBroadcastManager.getInstance(this).registerReceiver(onMessage, if);
}
Writing the Receiver in Activity
private BroadcastReceiver onNotice= new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Update your RecyclerView here using notifyItemInserted(position);
}};
Summary: The Service sends local broadcast to Activity which in turn receives it and updates or add items using RecyclerView instance
if in case you don't want to use BroadCaseReceiver for your task.Follow below steps:
There are two things to note here.
Firstly,Check whether the Activity is open(Activel visible) or not.
i. When your screen is active.(screen is visible).
1.In your onMessageReceived() store the received message in SQLiteDataBase with time.
2.create a method in your adapter which will update the screen by fetching the data from SQLiteDB.
3.Now whenever a new message is received call this method in Adapter class.
ii.in case the screen is not active:
1.store the received message in sqliteDb and show it as a notification.
note:
1.make sure you write all these in a try catch block.
2.make sure to sync your SQLiteDB on opening the screen for the first time.
3.in case if this does not help you please try this way.. Refreshing activity on receiving gcm push notification
I think the above code didnt worked because the action name above given and the one registered in manifest is different
<action android:name="com.myApp.CUSTOM_EVENT">
</action>
intent.setAction("com.myApp.CUSTOM_EVENT");
give same name i think the above code will work

Check if app is open during a GCM onMessage event?

I am wondering how to check if my application is open and currently visible to the user when receiving an onMessage() from GCM. At first, I was just using my own boolean isVisible, but then I realized this isn't reliable, because if the app isn't open, the object I use to access that flag is null. While this in itself could be used to see if the app is open, it seems a little bit messy. Is there a way in Android from a system level to somehow check if the application is currently open, and if the user is viewing the app? Keep in mind an app could technically be running, but not be visible, because a user has recently pressed the "home" button sending it to the background.
#Override
protected void onMessage(Context arg0, Intent arg1) {
String turn = intent.getExtras().getString("turn");
if (turn.equals("yours"){
if (/*app is open*/){ <------------------ what can go here?
// dont generate a notification
// display something in the game instead
}
else{
// generate notification telling player its their turn
}
}
}
I would use order broadcasts to do that.
In your onMessage method:
Intent responseIntent = new Intent("com.yourpackage.GOT_PUSH");
sendOrderedBroadcast(responseIntent, null);
In your Activity:
public class YourActivity extends Activity {
final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Right here do what you want in your activity
abortBroadcast();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//.....
}
#Override
protected void onPause() {
unregisterReceiver(mBroadcastReceiver);
super.onPause();
}
#Override
protected void onResume() {
IntentFilter filter = new IntentFilter("com.yourpackage.GOT_PUSH");
filter.setPriority(2);
registerReceiver(mBroadcastReceiver, filter);
super.onResume();
}
}
The other BroadcastReceiver
public class SecondReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//In this receiver just send your notification
}
}
Manifest:
<activity
android:name=".YourActivity"
android:label="#string/app_name">
<intent-filter>
<action
android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".SecondReceiver">
<intent-filter
android:priority="1">
<action
android:name="com.yourpackage.GOT_PUSH" />
</intent-filter>
</receiver>
Basically in the onMessage method you send an Intent which is first received by the BroadcastReceiver registered inside YourActivity if it is running and in foreground, otherwise it is received by the SecondReceiver.
Use SharedPreferences saving the boolean isVisible, and when you get the value from the preference you can add a default value.
SharedPreferences settings = context.getSharedPreferences("NAME_XXX", Activity.MODE_PRIVATE);
settings.getBoolean("visible", false);
What I always do is have a reference to the current Activity.
I set the current Activity in every onResume to this and set it to null in every onPause.
If the current Activity is null then the app is not open. If it's not null you can see if the correct Activity is open and deliver it to that Activity.
GCMIntentService:
public static Activity currentActivity;
public static final Object CURRENTACTIVIYLOCK = new Object();
#Override
protected void onHandleIntent(Intent intent) {
synchronized(CURRENTACTIVIYLOCK) {
if (currentActivity != null) {
if (currentActivity.getClass() == CorrectActivity.class) {
CorrectActivity act = (CorrectActivity)currentActivity;
act.runOnUiThread(new Runnable() {
public void run() {
// Notifiy activity
}
});
} else {
// show notification ?
}
} else {
// show notification
}
}
}
CorrectActivity:
#Override
protected void onResume() {
synchronized (GCMIntentService.CURRENTACTIVITYLOCK) {
GCMIntentService.currentActivity = this;
}
}
super.onResume();
}
#Override
protected void onPause() {
synchronized (GCMIntentService.CURRENTACTIVITYLOCK) {
GCMIntentService.currentActivity = null;
}
super.onPause();
}
The thing that worked for me:
Create a final Class Constants, inside it, create static varaiable:
public final class Constants{
public static AppCompatActivity mCurrentActivity;
}
Now, on each on resume of your activties say:
#Override
protected void onResume() {
super.onResume();
Constants.mCurrentActivity = this;
}
When receieving notification, check if current activity is null, if its null, application is not opened, if activity isn't null, you can check things like:
if(Constants.mCurrentActivity instanceof MainActivity){
((MainActivity) Constants.mCurrentActivity).yourPublicMethodOrStaticObject;
}

Call the function only once when opening

Need your help!
How do I in my application to call the function only once when opening?
I do:
private boolean is_first = true;
#Override
public void onCreate(Bundle savedInstanceState) {
if ( is_first ) {
MyFirstFunction();
}
}
public void onResume(Bundle savedInstanceState) {
super.onResume();
is_first = false;
}
Also in the manifest file added to the activity android:configChanges="orientation" but still function when you turn the device restarts
I hope for your help!
you can use Application class to do that in the onCreate method you can call your function
public class MyApp extends Application {
#Override
public void onCreate() {
//this will be called each time you open the application
super.onCreate();
//call you function here
}
}
then add this class to the manifest
<application
android:name=".MyApp or your class name"
......
....>

Categories