Use Application within Application on Android - android

I'm writing a program for the Android Platform and I would like to implement the code of a preexisting application found here .
There is a button in my application menu that says "Show Friends on Map" so I want this program to start from the button press.
For greater detail I will give a small diagram.
User Starts My application > User Presses "Menu" Key > User Presses "Show Friends on Map" > WAMF.apk (the application in the link above) is launched
Is there any way I can do this?

If I understand you correctly and all you want to do is launch WAMF, see this blog post.
In it is the following code, which will detect whether the OpenTable (or WAMF, in this question) is installed, and if so invoke it, otherwise take the user to the Android Market to download OpenTable:
public void showReserveButton() {
// setup the Intent to call OpenTable
Uri reserveUri = Uri.parse(String.format( "reserve://opentable.com/%s?refId=5449",
opentableId));
Intent opentableIntent = new Intent("com.opentable.action.RESERVE", reserveUri);
// setup the Intent to deep link into Android Market
Uri marketUri = Uri.parse("market://search?q=pname:com.opentable");
Intent marketIntent = new Intent(Intent.ACTION_VIEW).setData(marketUri);
opentableButton.setVisibility(opentableId > 0 ? View.VISIBLE : View.GONE);
opentableButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
PackageManager pm = getPackageManager();
startActivity(pm.queryIntentActivities(opentableIntent, 0).size() == 0 ?
opentableIntent : marketIntent);
}
});
}
As commonsware says, this is assuming that WAMF is available in the Android market. If not, you're out of luck.

(I'm hoping Reto Meier sees your question, as WAMF is his app)
Well, as I see it, you have two main choices.
Option #1 says that WAMF is installed as a separate application. That may be tricky, as it is unclear if this application is available for distribution anywhere (e.g., Android Market). But, assuming it is, and assuming the user has the app installed, when the user invokes your desired menu choice, you need to call startActivity(), using an Intent that will resolve to whatever in WAMF you would like to have displayed. You can also use PackageManager to detect if WAMF is installed (i.e., seeing if there are any activities that would match the Intent you want to use in startActivity()) -- that way, you can disable the menu choice, or have it pop up a dialog telling people to install WAMF, or something.
Option #2 says that, since WAMF is Free Software, you simply integrate the relevant portions of code straight into your app. On the plus side, there's no question whether the code is there. However, should Mr. Meier update the year-old WAMF, you would have to re-integrate his changes. Also, his application is released under GPLv3, which may or may not work with your own app's licensing scheme.

Related

Bring app back to foreground from code doesn't work on Android 12+

I made a Xamarin.Forms project to create and show local notifications, and it's supposed to be able to put the app back to the foreground when the notification is clicked.
The thing is, my code works on Android 11 and before, but on Android 12 & 13 the notification click is received by the app, if I have a callback for that notification it is called, but the app stays in background.
This is the part of the code that runs when I received a notification click and that I want to set the app in foreground (this is in the Xamarin Android project) :
var packageManager = Application.Context.PackageManager;
Intent launchIntent = packageManager.GetLaunchIntentForPackage(Constants.PackageName);
if (launchIntent != null)
{
launchIntent.AddCategory(Intent.CategoryLauncher);
Application.Context.StartActivity(launchIntent);
}
I have found a lot of posts on how to start/set to foreground an app, and the code I use is what's working for others, but all these posts where from 2020 and before, so no Android 12+ at the time and I can't find anything about a new way of doing this.
Does anyone have this functionality working on the newest Androids ?
I have found the solution so I'll post it here if someone needs it.
The code I use to put the application back to the foreground is correct, but I was missing the System_Alert_Window permission in my main application.
So to handle this permission I did :
Add it to my main application's manifest
Create a native method that checks if it is enabled
Create a native method that redirect the user to the overlay settings so they can allow the permission.
To check if the permission is enabled :
public bool HasOverlayPermission()
{
if (Build.VERSION.SdkInt < BuildVersionCodes.M)
return true;
return Android.Provider.Settings.CanDrawOverlays(Application.Context);
}
To redirect the user to their phone settings for AppOverlay (this permission can only be allowed from the settings) :
public void AskForOverlayPermission()
{
if (Android.Provider.Settings.CanDrawOverlays(Application.Context))
return;
var uri = Android.Net.Uri.Parse("package:" +
Application.Context.PackageName);
Intent intent = new Intent(
Android.Provider.Settings.ActionManageOverlayPermission, uri);
_mainActivity.StartActivityForResult(intent, 101);
}
The StartActivityFromResult method is only accessible in Activity classes, so you can either write it in you MainActivity or give your MainActivity as constructor parameter of another class.
This code will directly redirect the user to the settings page, so it's better if you ask them if they want to allow this permission in a popup or something beforehand (so they can understand why they're redirected).
I have found the code in this post : How to enable screen overlay permission by default

Create Intent from Shortcut

I have installed Xposed and GravityBox Module on Android Oreo.
With Nova Launcher I created an action-shortcut to GravityBox in order to make my device go on Sleep.
I found the Intent in the shortcut-database of Nova Launcher, and the code is:
#Intent;action=gravitybox.intent.action.LAUNCH_ACTION;launchFlags=0x10008000;component=com.ceco.oreo.gravitybox/.shortcuts.LaunchActivity;S.action=gravitybox.intent.action.SLEEP;S.actionType=broadcast;end
Now I'm writing a small App in Android Studio and I want to use the same Intent in order to PowerOff screen quickly using GravityBox when I press a Button in my App. My button method will be like:
public void mPowerOFF(){
try {
Intent screenOffIntent = new Intent();
screenOffIntent.setAction("gravitybox.intent.action.LAUNCH_ACTION");
screenOffIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
screenOffIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
screenOffIntent.setComponent(new ComponentName("com.ceco.oreo.gravitybox", "com.ceco.marshmallow.gravitybox.shortcuts.LaunchActivity"));
screenOffIntent.putExtra("I believe others stuff goes here but I don't know how");
I found on a site that the unique launchflags=0x10008000 will split in
screenOffIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
screenOffIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
What I'm missing to complete my job?

How make a Android application that can't be closed

I'm developing an Android app for a company where those who will use it are the employees, for this reason the company asked me to develop an application that the user can not close, because if he will not use the smartphone for other purposes, but for this I need the Android native buttons do not interfere with the application.
I've deactivated the button to go back and put the application as Home.
#Override
     public void onBackPressed () {
         super.onBackPressed ();
     }
...
<category android: name = "android.intent.category.HOME" />
However if the user clicks the button that displays open applications, it can exit the application.
I researched a lot before creating resolve this question and realized several attempts to solve this problem.
One. I tried to create the same behavior as the MX Player has, when you use the lock to see a video, the MX Player is always on top of everything, leaving the user to see and click others places. However using this behavior does not i cant see My Dialogs nor Popup and also can not apply a thema, as in my case is not simply an activity is the entire application.
Reference links of my attempt
How to disable Home and other system buttons in Android?
http://www.piwai.info/chatheads-basics/
If anyone knows how to use that behavior MX Player, or if anyone knows any more how to make the user can not close the application, please help me, I know it's not just me who have this problem.
Any help is welcome!
My API is 16 - Android-4.1
Are your target devices rooted? If so, this article goes through the steps to make this possible. What you specifically ask about can be done by modifying the build.prop file to include the following line: qemu.hw.mainkeys=1. This will stop the soft-key navigation bar from ever showing up.
If the device you're running isn't rooted, I don't think that it's possible to do what you're asking.
The best way i found to the user can't access others apps, was to make a service that check which is the top activity, if don't is my then reopen my app.
ActivityManager manager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> runningTasks = manager.getRunningTasks(1);
if (runningTasks != null && runningTasks.size() > 0) {
ComponentName topActivity = runningTasks.get(0).topActivity;
if (!topActivity.getPackageName().startsWith("com.mypackage.")) {
Log.i("Top Activity", topActivity.getPackageName());
if (LocalCache.getInstance().isForceHome()) {
Intent intent = new Intent(HomeService.this, AuthLoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
handler.postDelayed(this, 500);
}
Old question, but I'm facing exactly same situation:
In-house App
Can't be close
I'm going to set App as a Launcher, and block top-dowm swipe to prevent status bar appear.
I think it's good enough for an in-house App ~

How to gracefully fall back to website when Deep Link can't be handled by app

The situation:
You have an extensive mobile website, m.somewhere.com
On Google Play you have an Android App that duplicates the key features of m.somewhere.com, but not all of them.
Your Client/Employer/Investor has asked you to implement deep-linking for those urls that can be handled by the app.
TL;DR - how do you implement this?
My Approach So Far:
First instinct: match only certain urls and launch for them. Problem: paucity of expression in the AndroidManifest intent-filter prevents this (e.g. http://weiyang.wordpress.ncsu.edu/2013/04/11/a-limitation-in-intent-filter-of-android-application/).
As a subset of the problem, suppose the server at m.somewhere.com knows that any url that ends in a number goes to a certain page on the site, and the marketing guys are constantly futzing with the seo, so e.g.
I want to launch the app for:
http://m.somewhere.com/find/abc-12345
https://m.somewhere.com/shop/xyz-45678928492
But not for
http://m.somewhere.com/find/abc-12345-xyz
https://m.somewhere.com/about-us
no combination of path, pathPrefix, or pathPattern will handle this.
Best practice on stackoverflow (Match URIs with <data> like http://example.com/something in AndroidManifest) seems to be to catch everything, and then handle the situation when you get to onCreate() and realize you shouldn't have handled this particular url:
Android Manifest:
...
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="http"
android:host="m.somewhere.com"
android:pathPattern=".*"/>
</intent-filter>
...
Activity onCreate():
Intent i = getIntent()
String action = i.getAction();
Uri uri = i.getData();
if (Intent.ACTION_VIEW.equals(action) && cantHandleUrl(uri)) {
// TODO - fallback to browser.
}
I have programmed something similar to the above that is working, but it leads to a very bad end-user experience:
While browsing m.somewhere.com, there is a hiccup on every url click
while the app is launched and then falls back.
There is a nasty habit for a Chooser screen to popup for each and every link click on m.somewhere.com, asking the user which they would like to use (and the Android App is listed along with the browsers, but clicking on the Android App just launches the chooser screen again). If I'm not careful I get in an infinite relaunch loop for my app (if the user selects "Always"), and even if I am careful, it appears to the user that their "Always" selection is being ignored.
What can be done?
(EDIT: Displaying the site in a WebView in the app for unhandled pages is NOT an option).
Late answer, but for future readers: if you're supporting a minimum of API level 15 then there's a more direct (less hacky) way of falling back to a browser for URLs you realize you don't want to handle, without resorting to disabling/re-enabling URL catching components.
nbarraille's answer is creative and possibly your only option if you need to support APIs lower than 15, but if you don't then you can make use of Intent.makeMainSelectorActivity() to directly launch the user's default browser, allowing you to bypass Android's ResolverActivity app selection dialog.
Don't do this
So instead of re-broadcasting the URL Intent the typical way like this:
// The URL your Activity intercepted
String data = "example.com/someurl"
Intent webIntent = new Intent(Intent.ACTION_VIEW, data);
webIntent.addCategory(Intent.CATEGORY_BROWSABLE);
startActivity(webIntent);
Do this
You would broadcast this Intent instead:
Intent defaultBrowser = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, Intent.CATEGORY_APP_BROWSER);
defaultBrowser.setData(data);
startActivity(defaultBrowser);
This will tell Android to load the browser app and data URL. This should bypass the chooser dialog even if they have more than one browser app installed. And without the chooser dialog you don't have to worry about the app falling into an infinite loop of intercepting/re-broadcasting the same Intent.
Caveat
You have to be okay with opening the URL (the one you didn't want to handle) in the user's browser. If you wanted to give other non-browser apps a chance to open the link as well, this solution wouldn't work since there is no chooser dialog.
Pitfalls
As far as I can tell, the only quirk from using this solution is that when the user clicks one of your deep links, they'll get to choose to open in your app or their browser, etc. When they choose your app and your internal app logic realizes it's a URL it doesn't want to intercept, the user gets shown the browser right away. So they choose your app but get shown the browser instead.
NOTE: when I say "broadcast" in this answer, I mean the general term, not the actual Android system feature.
There is a somewhat hacky way of doing this:
In the manifest, create an intent-filter for m.somewhere.com, to open a specific deeplink handler activity.
In that Activity, figure out if your app supports that URL or not.
If it does, just open whatever activity
If it doesn't, send a non-resolved ACTION_VIEW intent to be opened by your browser. The problem here, is that your app will also catch this intent, and this will create an infinite loop if your app is selected as the default handler for that URL. The solution is to use PackageManager.setComponentEnabledSetting() to disable your deeplink handler Activity before you send that intent, and re-enable it after.
Some example code:
public class DeepLinkHandlerActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
Uri uri = intent.getData();
Intent intent = makeInternallySupportedIntent(uri);
if (intent == null) {
final PackageManager pm = getPackageManager();
final ComponentName component = new ComponentName(context, DeepLinkHandlerActivity.class);
pm.setComponentEnabledSetting(component, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
Intent webIntent = new Intent(Intent.ACTION_VIEW);
webIntent.setData(uri);
context.startActivity(webIntent);
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void[] params) {
SystemClock.sleep(2000);
pm.setComponentEnabledSetting(component, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
return null;
}
};
task.execute();
} else {
startActivity(intent);
}
finish();
}
}
Hope that helps.
Note: It looks like you need to delay the re-enabling by a couple of seconds for this to work.
Note 2: For a better experience, using a Transparent theme for your activity will make it look like your app didn't even open.
Note 3: If for some reason your app crashes or gets killed before the component re-registers, you're loosing deep link support forever (or until next update/reinstall), so I would also do the component re-enabling in App.onCreate() just in case.
URX provides a free tool (urxlinks.js) that automatically redirects mobile web users into an app if the app is installed. The documentation is available here: http://developers.urx.com/deeplinks/urx-links.html#using-urx-links-js
If two apps are using same scheme then the chooser screen will be popped as android wont know which app the link is intended for. Using custom scheme for your app might solve this issue. But still you can't be sure no one else will use that scheme.
It sounds like you're trying to treat your mobile app and mobile website as extensions of the same experience. That's good practice, generally speaking, but at this point the two are simply not at parity. At least until they reach parity I would not recommend automatically pushing the end user into your mobile app because users who are deliberately using the mobile site in order to find the content your app is missing will find this incredibly frustrating.
Instead, it might make sense to use a smart banner to encourage users on the mobile website pages that do have an in-app equivalent to open the app instead. Those banners would be your deeplinks. You could create them yourself or integrate a tool like Branch ( https://branch.io/universal-app-banner/ ) that handles deep linking and smart banners both.
That last part of your question has to do with where to place the deep links. One advantage to using smart banners instead of redirects is that you can embed them into the appropriate templates on your CMS instead of needing to rely on url detection.
Good luck!
This was my solution to your second problem. PackageManager.queryIntentActivities() will give you the list of apps/activities that would appear in the chooser. Iterate through the list (which should at least include the browser) and find an activity whose package name doesn't match the current app, and set the intent class name to it, then launch an Activity with that intent and call finish();
public Intent getNotMeIntent(Uri uri) {
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
PackageManager manager = context.getPackageManager();
List<ResolveInfo> infos = manager.queryIntentActivities(intent, 0);
for (int i = 0; i < infos.size(); i++) {
ResolveInfo info = infos.get(i);
// Find a handler for this url that isn't us
if (!info.activityInfo.packageName.equals(context.getPackageName())) {
intent.setComponent(null);
intent.setClassName(info.activityInfo.packageName, info.activityInfo.name);
return intent;
}
}
// They have no browser
return null;
}
The Transparent theme (mentioned above) should be a good solution for the first problem.
In destination activity in onCreate set this code for Kotlin:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
handleIntent(intent)
}
‌private fun handleIntent(intent: Intent?) {
val appLinkAction: String? = intent?.action
val appLinkData: Uri? = intent?.data
showDeepLinkData(appLinkAction, appLinkData)
}
private fun showDeepLinkData(appLinkAction: String?, appLinkData: Uri?) {
if (Intent.ACTION_VIEW == appLinkAction && appLinkData != null) {
val promotionCode = appLinkData.getQueryParameter("exampleQueryString")
Log.e("TAG", "Uri is: $appLinkData")
}
}

re-prompt to choose default activity

is there a way to reprompt the user to choose a default activity for an intent? For example, user selects his default home apk and I want him to reconsider his choice once again.
I know how to do that on 2.1 and before, but is there a way to do that now on 2.2?
Famous Home Switcher, which did similar thing, does not work on 2.2 anymore thanks to google team
This is how I represent the Activity selection dialog:
It start the android default ResolverActivity for "HOME" Applications.
Intent selector = new Intent("android.intent.action.MAIN");
selector.addCategory("android.intent.category.HOME");
selector.setComponent(new ComponentName("android", "com.android.internal.app.ResolverActivity"));
startActivity(selector);
The above code is working for my 2.2 enabled tablets.
When executed, it displays the "Complete Actions with:" dialog with all possible Home applications in the list.
A way to detect which is currently set by default you could ask for all preferred activities. The lists "filters" and "comps" contain the data when calling .getPreferredActivities(...).
filters - contains the intent filter data, which you could query what type of data it is.
comps - contians the component which would be called if the intent filter matches
This way you could check if your application is the current "home" application set as preferred by the user.
List<IntentFilter> filters = new ArrayList<IntentFilter>();
List<ComponentName> comps= new ArrayList<ComponentName>();
getPackageManager().getPreferredActivities(filters, comps, null);
For example, user selects his default home apk and I want him to reconsider his choice once again.
That is no longer possible, unless your app is the preferred one. Then, I think you can use clearPackagePreferredActivities() to remove yourself as the preferred choice.
In other words, you are welcome to affect your own app, but you are not welcome to affect other apps.

Categories

Resources