Call the function only once when opening - java

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"
......
....>

Related

BroadcastReceiver not called at launch

I need to detect when wired headset or a bluetooth one is plugged/connected so I create and register two BroadcastReceiver(s) like the following:
file ReceiverHeadsetWired.java
public class ReceiverHeadsetWired extends BroadcastReceiver {
ActivityMain main;
public ReceiverHeadsetWired(
ActivityMain activityMain
){
main = activityMain;
}
#Override
public void onReceive(
Context context,
Intent intent
) {
if (TextUtils.isEmpty(intent.getAction())) { return; }
if (Objects.equals(intent.getAction(), "android.intent.action.HEADSET_PLUG")) {
Log.d("[ReceiverHeadsetWired]", "onReceive()");
...
}
}
}
file ReceiverHeadsetBluetooth.java
public class ReceiverHeadsetBluetooth extends BroadcastReceiver {
ActivityMain main;
public ReceiverHeadsetBluetooth(
ActivityMain activityMain
){
main = activityMain;
}
#Override
public void onReceive(
Context context,
Intent intent
) {
if (TextUtils.isEmpty(intent.getAction())) { return; }
if (Objects.equals(intent.getAction(), "android.bluetooth.headset.profile.action.CONNECTION_STATE_CHANGED")) {
Log.d("[ReceiverHeadsetBluetooth]", "onReceive()");
...
}
}
}
Both of them are dynamically registered in onCreate method of MainActivity's Fragment and unregisterd onDestroy.
#Override
public void onCreate(
Bundle savedInstanceState
) {
super.onCreate(savedInstanceState);
ActivityMain main = (ActivityMain) getActivity();
...
registerHeadsetWiredReceiver();
registerHeadsetBluetoothReceiver();
...
}
private void registerHeadsetWiredReceiver() {
wiredHeadsetReceiver = new ReceiverHeadsetWired(main);
IntentFilter hwFilter = new IntentFilter("android.intent.action.HEADSET_PLUG");
main.registerReceiver(wiredHeadsetReceiver, hwFilter);
}
private void registerHeadsetBluetoothReceiver() {
bluetoothHeadsetReceiver = new ReceiverHeadsetBluetooth(main);
IntentFilter hbFilter = new IntentFilter("android.bluetooth.headset.profile.action.CONNECTION_STATE_CHANGED");
main.registerReceiver(bluetoothHeadsetReceiver, hbFilter);
}
Now the point is that at launch only the onReceive of ReceiverHeadsetWired is called (Logcat shows the textline), but after app started both of them work as expected except a strange behaviour: the first time I connect a Bluetooth headset the related Log is written twice.
In other words when app is launched if a wired headset is plugged it will be detected but a connected bluetooth one won't.
Does anybody knows what's the problem?
Thanks in advance

How to call a method from android library class

I want to call a method from a android library class which i have imported as a androidlib.jar. As i am able to call a whole class of library but i dont want it, but i want to call a particular method of library class.
I tried something like this, but it is showing java.lang.Nullpointer exception
This is my library class (AndroidLiB.class), where i have imported its jar file
public class AndroidLiB extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.android_li_b);
startGPS();
}
public void startGPS()
{
Toast.makeText(getApplicationContext(),"Your GPS started",Toast.LENGTH_LONG).show();
}
}
This is my application class where i want to call a method from above class
public class AndLib1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.and_lib1);
AndroidLiB abc = new AndroidLiB();
abc.startGPS();
}
}
But it is not working
If you want simply a method from jar, then why you need to extends Activity. My suggestion is remove extends Activity will fix the NPE error.
Try this,
public class AndroidLiB {
Activity activity;
AndroidLiB(Activity activity){
this.activity = activity;
}
public void startGPS()
{
Toast.makeText(activity,"Your GPS started",Toast.LENGTH_LONG).show();
}
}
And In your main class call like
AndroidLiB lib = new AndroidLiB (this);
lib.startGPS();
I would do something like this:
public class Tool {
private Tool() {
// no direct instantiation
}
public static void startGPS(final Context context) {
Toast.makeText(context, "Your GPS started", Toast.LENGTH_LONG).show();
}
}
then
public class AndroidLiB extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.android_li_b);
Tool.startGPS(this);
}
}
and
public class AndLib1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.and_lib1);
Tool.startGPS(this);
}
}
You can extend library class. For example:
public class YourActivity extends AndroidLib
{
super.onCreate(savedInstanceState);
setContentView(R.layout.and_lib1);
startGPS();
}
What you're trying to do isn't really the best way to do things, but I'm assuming that the question being asked is how to import the jar correctly. If so:
If using eclipse,
Make sure the androidlib.jar file is in the libs folder.
Right click on androidlib.jar and select Build Path > Add to Build Path
Right click on your project folder, go to Properties > Java Build Path > Order and Export and then make sure androidlib.jar is selected.
The problem with your current code is that when you call getApplicationContext(), the Activity hasn't been started yet, therefore there is no context. A quick and dirty solution would be to rewrite the startGPS() method like this:
public static void startGps(Context context, String message) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
But I would much rather put that method inside some sort of Utilities class or even inside a parent Activity class.

Force asynctask to exeute every time app is opened

I need execute the async task every time the app is opened or executed, because I use this Asyntask to fetch some json data from http and in every app execution Must be fresh data.
Any idea how to force this?
Thanks
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etResponse = (TextView)findViewById(R.id.etResponse);
etdia = (TextView)findViewById(R.id.dia);
etmes = (TextView)findViewById(R.id.mes);
// check if you are connected or not
if(isConnected()){
}
new HttpAsyncTask().execute("URL TO EXECUTE");
}
Place the execute method in your onResume() method.
#Override
protected void onResume() {
super.onResume();
new HttpAsyncTask().execute("URL TO EXECUTE");
}
I saw you solved your issue. Anyway i'll put here the method for exec the asynctask for EVERY activity of the app:
public class myActivity extends Activity {
private String mLastUrl = "";
public void execAsync(String url) {
new HttpAsyncTask().execute(url);
mLastUrl = url;
}
#Override
protected void onResume() {
super.onResume();
execAsync(mLastUrl);
}
//your asynctaskcode
On all the other activities you would like to run the asynctask just do this:
public class activityName extends myActivity {

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;
}

Automatically log Android lifecycle events using ActivityLifecycleCallbacks?

I am trying to automatically capture and log Android lifecycle events using ActivityLifecycleCallbacks, however documentation on this matter is scarce, to say the least:
public void registerActivityLifecycleCallbacks (Application.ActivityLifecycleCallbacks callback)
I don't want to have to extend the Activity class or override the existing lifecycle methods (onCreate, onResume, etc...) I'm looking to have a separate class listening for these events and acting accordingly.
Does anyone have any experience in this, or have links to good solid documentation or tutorials on how this works? Specifically, how to register for ActivityLifecycleCallbacks, and how to handle them?
I don't have any firsthand experience but judging from the API you can just write your own class that implements the Application.ActivityLifecycleCallbacks interface and register that class on the provided Application class instance
getApplicaton().registerActivityLifecycleCallbacks(yourCustomClass);
This class will receive the same callbacks as your individual activities. Good luck.
PS. This is API level 14 btw, so it won't work on older phones.
I did my own implementation of Application.ActivityLifecycleCallbacks. I'm using SherlockActivity, but for normal Activity class might work.
First, I'm creating an interface that have all methods for track the activities lifecycle:
public interface ActivityLifecycleCallbacks{
public void onActivityStopped(Activity activity);
public void onActivityStarted(Activity activity);
public void onActivitySaveInstanceState(Activity activity, Bundle outState);
public void onActivityResumed(Activity activity);
public void onActivityPaused(Activity activity);
public void onActivityDestroyed(Activity activity);
public void onActivityCreated(Activity activity, Bundle savedInstanceState);
}
Second, I implemented this interface in my Application's class:
public class MyApplication extends Application implements my.package.ActivityLifecycleCallbacks{
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onActivityStopped(Activity activity) {
Log.i("Tracking Activity Stopped", activity.getLocalClassName());
}
#Override
public void onActivityStarted(Activity activity) {
Log.i("Tracking Activity Started", activity.getLocalClassName());
}
#Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
Log.i("Tracking Activity SaveInstanceState", activity.getLocalClassName());
}
#Override
public void onActivityResumed(Activity activity) {
Log.i("Tracking Activity Resumed", activity.getLocalClassName());
}
#Override
public void onActivityPaused(Activity activity) {
Log.i("Tracking Activity Paused", activity.getLocalClassName());
}
#Override
public void onActivityDestroyed(Activity activity) {
Log.i("Tracking Activity Destroyed", activity.getLocalClassName());
}
#Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
Log.i("Tracking Activity Created", activity.getLocalClassName());
}
}
Third, I'm creating a class that extends from SherlockActivity:
public class MySherlockActivity extends SherlockActivity {
protected MyApplication nMyApplication;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
nMyApplication = (MyApplication) getApplication();
nMyApplication.onActivityCreated(this, savedInstanceState);
}
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
nMyApplication.onActivityResumed(this);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
nMyApplication.onActivityPaused(this);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
nMyApplication.onActivityDestroyed(this);
}
#Override
protected void onStart() {
super.onStart();
nMyApplication.onActivityStarted(this);
}
#Override
protected void onStop() {
super.onStop();
nMyApplication.onActivityStopped(this);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
nMyApplication.onActivitySaveInstanceState(this, outState);
}
}
Fourth, all class that extend from SherlockActivity, I replaced for MySherlockActivity:
public class MainActivity extends MySherlockActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Now, in the logcat you will see the logs programmed in the Interface implementation made in MyApplication.
UPDATE
This implementation was tested from API Level 9 (Gingerbread), API Level 12 (Honeycomb) and API Level 17 (Jelly Bean) and works fine. Might works in Android's older versions.
Try this: http://engineering.meetme.com/2015/04/android-determine-when-app-is-opened-or-closed/#comment-202
It proposes an AppForegroundStateManager to which each activity reports through its onStop() and onStart() functions like this:
#Override
protected void onStart() {
super.onStart();
AppForegroundStateManager.getInstance().onActivityVisible(this);
}
#Override
protected void onStop() {
AppForegroundStateManager.getInstance().onActivityNotVisible(this);
super.onStop();
}
Your Application class implements a listener like this:
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
AppForegroundStateManager.getInstance().addListener(this);
}
#Override
public void onAppForegroundStateChange(AppForegroundStateManager.AppForegroundState newState) {
if (AppForegroundStateManager.AppForegroundState.IN_FOREGROUND.equals(newState)) {
// App just entered the foreground. Do something here!
Log.i(TAG, "App Just Entered the Foreground with launch mechanism of: " + mLaunchMechanism);
} else {
// App just entered the background. Set our launch mode back to the default of direct.
mLaunchMechanism = LaunchMechanism.DIRECT;
}
}
}
It also includes tips and tricks for determining how the app was opened - from a notification, a URL opening your app or directly from the Apps menu. This is done through an Enum in the Application class:
public enum LaunchMechanism {
DIRECT,
NOTIFICATION,
URL,
BACKGROUND
}
private LaunchMechanism mLaunchMechanism = LaunchMechanism.DIRECT;
public void setLaunchMechanism(LaunchMechanism launchMechanism) {
mLaunchMechanism = launchMechanism;
}
In our implementation of this, we have flags for when we start an activity that will launch a third-party activity, like if the user makes a phone call from our app or if a browser is launched. In the launching activity's onStop() we then do a check like this to only report the activity's not-visibility when those flags are false:
if(!flag_userLaunchedThirdPartyActivity){
AppForegroundStateManager.getInstance().onActivityNotVisible(this);
}
For checking whether or not the application goes into the background - for example when the device's screen goes dark or the user receives a phone call - it works like this:
public static boolean isApplicationGoingToBackground(final Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
setLaunchMechanism(LaunchMechanism.BACKGROUND);
return true;
}
}
setLaunchMechanism(LaunchMechanism.DIRECT);
return false;
}
This solution is not dependent on an API level, so it should work all the way back to API level 1.
#Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(MyApplication.this/*(Your Application Name)*/);
}
Only add this line on Application class and all works well.

Categories