Android java get activity

Java android how to get activity code example

Note that the user won’t be able to press the OK button when trying to enable the accessibility service if an app has placed an overlay on the screen, such as Velis Auto Brightness or Lux. Solution 3: You may not own the «currently running Activity». Send a broadcast to the activity — here is a sample project demonstrating this pattern Have the activity supply a (e.g., via ) that the service invokes Have the activity register a callback or listener object with the service via , and have the service call an event method on that callback/listener object Send an ordered broadcast to the activity, with a low-priority as backup (to raise a if the activity is not on-screen) — here is a blog post with more on this pattern Solution 1: ( Note: An official API was added in API 14: See this answer https://stackoverflow.com/a/29786451/119733) DO NOT USE PREVIOUS (waqas716) answer. Add the name of the application in the manifest file: Your application class :Create a new Activity : So, now instead of extending Activity class for your activities, just extend MyBaseActivity.

Android: How can I get the current foreground activity (from a service)?

Update : this no longer works with other apps’ activities as of Android 5.0

Читайте также:  Php mysqli fetch columns

Here’s a good way to do it using the activity manager. You basically get the runningTasks from the activity manager. It will always return the currently active task first. From there you can get the topActivity.

There’s an easy way of getting a list of running tasks from the ActivityManager service. You can request a maximum number of tasks running on the phone, and by default, the currently active task is returned first.

Once you have that you can get a ComponentName object by requesting the topActivity from your list.

 ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE); List taskInfo = am.getRunningTasks(1); Log.d("topActivity", "CURRENT Activity ::" + taskInfo.get(0).topActivity.getClassName()); ComponentName componentInfo = taskInfo.get(0).topActivity; componentInfo.getPackageName(); 

You will need the following permission on your manifest:

Warning: Google Play violation

Google has threatened to remove apps from the Play Store if they use accessibility services for non-accessibility purposes. However, this is reportedly being reconsidered.

Use an AccessibilityService

  • You can detect the currently active window by using an AccessibilityService .
  • In the onAccessibilityEvent callback, check for the TYPE_WINDOW_STATE_CHANGED event type to determine when the current window changes.
  • Check if the window is an activity by calling PackageManager.getActivityInfo() .

Benefits

  • Tested and working in Android 2.2 (API 8) through Android 7.1 (API 25).
  • Doesn’t require polling.
  • Doesn’t require the GET_TASKS permission.

Disadvantages

  • Each user must enable the service in Android’s accessibility settings.
  • This isn’t 100% reliable. Occasionally the events come in out-of-order.
  • The service is always running.
  • When a user tries to enable the AccessibilityService , they can’t press the OK button if an app has placed an overlay on the screen. Some apps that do this are Velis Auto Brightness and Lux. This can be confusing because the user might not know why they can’t press the button or how to work around it.
  • The AccessibilityService won’t know the current activity until the first change of activity.
Читайте также:  Чем изменить файл php

Example

Service
public class WindowChangeDetectingService extends AccessibilityService < @Override protected void onServiceConnected() < super.onServiceConnected(); //Configure these here for compatibility with API 13 and below. AccessibilityServiceInfo config = new AccessibilityServiceInfo(); config.eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED; config.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC; if (Build.VERSION.SDK_INT >= 16) //Just in case this helps config.flags = AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS; setServiceInfo(config); > @Override public void onAccessibilityEvent(AccessibilityEvent event) < if (event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) < if (event.getPackageName() != null && event.getClassName() != null) < ComponentName componentName = new ComponentName( event.getPackageName().toString(), event.getClassName().toString() ); ActivityInfo activityInfo = tryGetActivity(componentName); boolean isActivity = activityInfo != null; if (isActivity) Log.i("CurrentActivity", componentName.flattenToShortString()); >> > private ActivityInfo tryGetActivity(ComponentName componentName) < try < return getPackageManager().getActivityInfo(componentName, 0); >catch (PackageManager.NameNotFoundException e) < return null; >> @Override public void onInterrupt() <> > 
AndroidManifest.xml

Merge this into your manifest:

Service Info

Put this in res/xml/accessibilityservice.xml :

Enabling the Service

Each user of the app will need to explicitly enable the AccessibilityService in order for it to be used. See this StackOverflow answer for how to do this.

Note that the user won’t be able to press the OK button when trying to enable the accessibility service if an app has placed an overlay on the screen, such as Velis Auto Brightness or Lux.

Is there a native android way to get a reference to the currently running Activity from a service?

You may not own the «currently running Activity».

I have a service running on the background, and I would like to update my current Activity when an event occurs (in the service). Is there a easy way to do that (like the one I suggested above)?

  1. Send a broadcast Intent to the activity — here is a sample project demonstrating this pattern
  2. Have the activity supply a PendingIntent (e.g., via createPendingResult() ) that the service invokes
  3. Have the activity register a callback or listener object with the service via bindService() , and have the service call an event method on that callback/listener object
  4. Send an ordered broadcast Intent to the activity, with a low-priority BroadcastReceiver as backup (to raise a Notification if the activity is not on-screen) — here is a blog post with more on this pattern

Android make callback to an Activity from java class, The solution I chose is as follows: Use BroadcastReceivers to communicate between Java classes and Activities. Example: public class SomeActivity extends Activity < private MyBroadcastReceiver receiver; @Override protected void onCreate (Bundle savedInstanceState) < super.onCreate …

How to get current foreground activity context in android?

( Note: An official API was added in API 14: See this answer https://stackoverflow.com/a/29786451/119733)

DO NOT USE PREVIOUS (waqas716) answer.

You will have memory leak problem, because of the static reference to the activity. For more detail see the following link http://android-developers.blogspot.fr/2009/01/avoiding-memory-leaks.html

To avoid this, you should manage activities references. Add the name of the application in the manifest file:

 public class MyApp extends Application < public void onCreate() < super.onCreate(); >private Activity mCurrentActivity = null; public Activity getCurrentActivity() < return mCurrentActivity; >public void setCurrentActivity(Activity mCurrentActivity) < this.mCurrentActivity = mCurrentActivity; >> 
public class MyBaseActivity extends Activity < protected MyApp mMyApp; public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); mMyApp = (MyApp)this.getApplicationContext(); >protected void onResume() < super.onResume(); mMyApp.setCurrentActivity(this); >protected void onPause() < clearReferences(); super.onPause(); >protected void onDestroy() < clearReferences(); super.onDestroy(); >private void clearReferences() < Activity currActivity = mMyApp.getCurrentActivity(); if (this.equals(currActivity)) mMyApp.setCurrentActivity(null); >> 

So, now instead of extending Activity class for your activities, just extend MyBaseActivity. Now, you can get your current activity from application or Activity context like that :

Activity currentActivity = ((MyApp)context.getApplicationContext()).getCurrentActivity(); 

I expand on the top of @gezdy’s answer.

In every Activities, instead of having to «register» itself with Application with manual coding, we can make use of the following API since level 14, to help us achieve similar purpose with less manual coding.

public void registerActivityLifecycleCallbacks (Application.ActivityLifecycleCallbacks callback) 

In Application.ActivityLifecycleCallbacks , you can get which Activity is «attached» to or «detached» to this Application .

However, this technique is only available since API level 14.

Update 3 : There is an official api added for this, please use ActivityLifecycleCallbacks instead.

Test your app’s activities, One key aspect of testing your app’s activities involves placing your app’s activities in particular states. To define this «given» part of your tests, use instances of ActivityScenario, part of the AndroidX Test library. By using this class, you can place your activity in states that simulate the device-level events …

Android make callback to an Activity from java class

The solution I chose is as follows:

Use BroadcastReceivers to communicate between Java classes and Activities.

public class SomeActivity extends Activity < private MyBroadcastReceiver receiver; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); receiver = new MyBroadcastReceiver(); this.registerReceiver(receiver, new IntentFilter(MyBroadcastReceiver.ACTION)); >@Override public void onDestroy() < super.onDestroy(); this.unregisterReceiver(receiver); >private class MyBroadcastReceiver extends BroadcastReceiver < public static final String ACTION = "com.example.ACTION_SOMETHING" @Override public void onReceive(Context context, Intent intent) < String test = intent.getStringExtra("dataToPass"); >> > public class TestClass < private String test = "TEST"; private Context context; public TestClass(Context context)< this.context = context; >private void sendToSomeActivity() < Intent intent = new Intent(); intent.setAction(SomeActivity.MyBroadcastReceiver.ACTION); intent.putExtra("dataToPass", test); context.sendBroadcast(intent); >> 
public class TestClass < interface Implementable< public void passData(String text); >Implementable imple; String text = "Test"; public TestClass(Context context) < startActivity(new Intent(context, SomeActivity.class)); >private void sendToSomeActivity() < if(imple != null)< imple.passData(text); >> public void setListener(Implementable im) < imple = im; >> class SomeActivity implements Implementable < new TestClass().setListener(this); @override public void passData(String text)< //here is your text >> 

In your java class create an interface like this

public class TestClass < private MyInterface myInterface; public interface OnSendSomething < public void onSending(String sendWhateverYouWant); >public void setOnSendListener(MyInterface myInterface) < this.myInterface = myInterface; >> private void sendToSomeActivity() < //Call some method of SomeActivity and pas text as string myInterface.onSending(sendWhateverYouWant); >

And in your activity do something like this:

TestClass tclass = new TestClass(context); tclass.setOnSendListener(new OnSendSomething () < @Override public void onSending(String sendWhateverYouWant) < //sendWhateverYouWant is here in activity >>); 

You can also visit these links for better understanding.

How to create our own Listener interface in android?

Observer Design Pattern in Java

Use onactivityresult android, Start the Activity: you do need to pass an additional integer argument to the startActivityForResult() method.You may do it by defining a constant or simply put an integer.The integer argument is a «request code» that identifies your request. When you receive the result Intent, the callback provides the same request …

Источник

How to get main Activity class or class name of my application?

Thanks to Lee for explaining how to get the classname, here’s the code:

String packageName = context.getPackageName(); Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(packageName); String className = launchIntent.getComponent().getClassName(); 

The application’s className would just output some garbage like com.android.tools.fd.runtime.BootstrapApplication

launchIntent.getComponent() could return null, because not all lauchend intents contains the respective component. developer.android.com/reference/android/content/…

getLaunchIntentForPackage 

On this Intent call getComponentName and from the returned CompomemtName call getClassName

This worked perfectly for me in Kotlin:

callingActivity::class.simpleName 
activity.getClass().getSimpleName() 

How to get the Activity class name in Kotlin:

val packageName = context.packageName val launchIntent = context.packageManager.getLaunchIntentForPackage(packageName) val className = launchIntent?.component?.className ?: return null 

How to get the Activity class from the class name in Kotlin:

return try < Class.forName(className) >catch (e: ClassNotFoundException)

I just set a variable in my main activity like so. public static Activity activity = this; then I can reference it from anywhere using: MainActivity.activity .

You can also set it in the onCreate() method, just set up the variable at the top of your main activity class like this public static Activity activity; then in the onCreate() method just add activity = this; anywhere.

This will work for any class that extends Activity, for example public class MainActivity extends Activity however you can call the variable from any class even if they don’t extend Activity.

Источник

Оцените статью