Invoking application activity from a library project in Android

Good,

So, I am doing an interface element library project. There are some actions in the library based on ActionBarSherlock , which is backward compatible for the action bar in android. In these actions, I would like to have a button in the action panel that will bring the user home no matter what activity they use in the library project.

Some terminology. "Library" refers to the Android UI library project I'm working on. β€œApplication” refers to any client that a developer can use with the library included.

Usually, when you do an operation and you want to call another, you would do something like this.

intent = new Intent(this, WhateverMyActivityName.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); 

Simple enough. But here is a difficult bit. Android libraries practically don't know which application uses them. Thus, "WhateverMyActivityName.class" is useless, as there is no way to predict what a development application will call by its actions.

I need to replace

 intent = new Intent(this, WhateverMyActivityName.class); 

with something like this

 intent = new Intent(this, getApplication().MainActivity().getClass()); 

or perhaps use some kind of intent action that will trigger the main activity in the application (Intent.ACTION_MAIN or Intent.CATEGORY_LAUNCHER)

So, briefly: how to get the main activity of applications from the library project?

+4
source share
3 answers

An application calls in your library some method that provides an Intent that is called or provides a Class for the action to be called. Your library stores this somewhere and uses it.

Your guess is that the correct answer: "Intent.ACTION_MAIN or Intent.CATEGORY_LAUNCHER" may be inaccurate. For example, in some applications there is a splash screen activity (which in itself is a problem, but this is not relevant), and this will not be the case where home access should go in the application.

+2
source

We can use reflection to get the class object.

Class.forName ("com.mypackage.myMainActivity")

Add this code to the library project to invoke,

 try { Intent myIntent = new Intent(this,Class.forName("com.mypackage.myMainActivity")); startActivity(myIntent ); } catch (ClassNotFoundException e) { e.printStackTrace(); } 

"com.mypackage.myMainActivity" is the activity present in the main project that we need to call from the library project.

+9
source

You can get a list of actions using the code provided in this message. After this loop through defineinfo and check the intenet filter to find the action with your desired action.

0
source

Source: https://habr.com/ru/post/1435486/


All Articles