Unable to find explicit activity class when open deeplink - c#

I had Xamarin.Android App with deeplinks on API32. After I updated API to 33, Deeplinks has broken. I had this exception in my logs:
Time Device Name Type PID Tag Message
02-14 08:25:48.878 OnePlus IN2015 Error 16453 AcceptInvitation android.content.ActivityNotFoundException: Unable to find explicit activity class {PACKAGENAME/crc645ff435851f1c2612.MainActivity}; have you declared this activity in your AndroidManifest.xml, or does your intent not match its declared <intent-filter>?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2184)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1831)
at android.app.Activity.startActivityForResult(Activity.java:5555)
at hcm.platform_startActivityForResult(:com.google.android.gms#230413045#23.04.13 (190408-505809224):2)
at hcl.startActivityForResult(:com.google.android.gms#230413045#23.04.13 (190408-505809224):2)
at com.google.android.chimera.android.Activity.startActivityForResult(:com.google.android.gms#230413045#23.04.13 (190408-505809224):2)
at hgx.startActivityForResult(:com.google.android.gms#230413045#23.04.13 (190408-505809224):2)
at hcl.public_startActivityForResult(:com.google.android.gms#230413045#23.04.13 (190408-505809224):2)
at hcm.startActivityForResult(:com.google.android.gms#230413045#23.04.13 (190408-505809224):3)
at android.app.Activity.startActivityForResult(Activity.java:5508)
at hcm.platform_startActivityForResult(:com.google.android.gms#230413045#23.04.13 (190408-505809224):1)
at hcl.startActivityForResult(:com.google.android.gms#230413045#23.04.13 (190408-505809224):1)
at com.google.android.chimera.android.Activity.startActivityForResult(:com.google.android.gms#230413045#23.04.13 (190408-505809224):1)
at hgx.startActivityForResult(:com.google.android.gms#230413045#23.04.13 (190408-505809224):1)
at hcl.public_startActivityForResult(:com.google.android.gms#230413045#23.04.13 (190408-505809224):1)
at hcm.startActivityForResult(:com.google.android.gms#230413045#23.04.13 (190408-505809224):1)
at android.app.Activity.startActivity(Activity.java:6011)
at hcm.platform_startActivity(:com.google.android.gms#230413045#23.04.13 (190408-505809224):2)
at hcl.startActivity(:com.google.android.gms#230413045#23.04.13 (190408-505809224):2)
at com.google.android.chimera.android.Activity.startActivity(:com.google.android.gms#230413045#23.04.13 (190408-505809224):2)
at hcl.public_startActivity(:com.google.android.gms#230413045#23.04.13 (190408-505809224):2)
at hcm.startActivity(:com.google.android.gms#230413045#23.04.13 (190408-505809224):3)
at android.app.Activity.startActivity(Activity.java:5978)
at hcm.platform_startActivity(:com.google.android.gms#230413045#23.04.13 (190408-505809224):1)
at hcl.startActivity(:com.google.android.gms#230413045#23.04.13 (190408-505809224):1)
at com.google.android.chimera.android.Activity.startActivity(:com.google.android.gms#230413045#23.04.13 (190408-505809224):1)
at kmv.x(:com.google.android.gms#230413045#23.04.13 (190408-505809224):4)
at kmw.onPostExecute(:com.google.android.gms#230413045#23.04.13 (190408-505809224):3)
at android.os.AsyncTask.finish(AsyncTask.java:771)
at android.os.AsyncTask.-$$Nest$mfinish(Unknown Source:0)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:788)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:240)
at android.os.Looper.loop(Looper.java:351)
at android.app.ActivityThread.main(ActivityThread.java:8355)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:584)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1013)
I tried to google a solution to this problem, tried a lot:
Changed ProGuard settings,
I checked various variations of calling MainActivity with the name of the assembly and just with a dot,
Updated my libraries and SDK,
I tried to prescribe other activities,
I checked the assemblies work both in debug and in release,
Analyzed dex files.
Nothing really helps.
Own analysis showed that the problem is that there are two MainActivities in
the list of activities.
I am also attaching AndroidManifest:
...
<application android:requestLegacyExternalStorage="true"
android:allowBackup="true" android:icon="#mipmap/icon"
android:largeHeap="true" android:supportsRtl="true"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:localeConfig="#xml/locales_config"
android:name=".MyApplication">
...
<activity android:name=".MainActivity" android:exported="true">
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="https" />
<data android:scheme="http" />
<data android:host="SITE.com" />
<data android:host="OWN.LINK" />
</intent-filter>
</activity>
...
</application>
MainActivity class has MainLauncher attribute.
Help me please! I spent a day on this and I'm afraid that without help I can be stuck for a long time. Seems like the error might be obvious.
[Activity(ScreenOrientation = ScreenOrientation.Portrait, NoHistory = true, MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
...
}
UPD:
Sometimes I had this exception:
Time Device Name Type PID Tag Message
02-14 08:38:29.150 OnePlus IN2015 Info 28812 MonoDroid Caused by: java.lang.ClassNotFoundException: Didn't find class "PACKAGENAME.MainActivity" on path: DexPathList[[zip file "/data/app/~~jXWlqXqgllqjZ1bi2qN5dg==/PACKAGENAME-gqSZGEIemXo6mh-lUysz-w==/base.apk"],nativeLibraryDirectories=[/data/app/~~jXWlqXqgllqjZ1bi2qN5dg==/PACKAGENAME-gqSZGEIemXo6mh-lUysz-w==/lib/arm64, /data/app/~~jXWlqXqgllqjZ1bi2qN5dg==/PACKAGENAME-gqSZGEIemXo6mh-lUysz-w==/base.apk!/lib/arm64-v8a, /system/lib64, /system_ext/lib64]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:259)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(SourceFile:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1347)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3745)
... 12 more

From the generated Manifest.xml file you posted, I couldn't find the following intent-filter:
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
so, you can recheck if you have set the MainLauncher = true correctly for your Activity.
You can refer to my setting,just as follows:
[Activity(Label = "SearchBarDemos", Icon = "#mipmap/icon", Theme = "#style/MainTheme", MainLauncher = true,Exported =true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
[
IntentFilter
(
new[] { Android.Content.Intent.ActionView },
Categories = new[]
{
Android.Content.Intent.CategoryDefault,
Android.Content.Intent.CategoryBrowsable
},
DataSchemes = new[] { "myapp" }
)
]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
}
And you can refer to a similar thread here: Navigate from one app to another using Xamarin.
Note:
If you have set ActivityAttribute MainLauncher = true for your MainActivity, you don't need to set it on fileManifest.xml,which easily leads to generating two MainActivitys you said.
On other words,you don't need to add any code into the generating Manifest.xml file.
For more information,please check:Working with the Android Manifest.

The "ActivityNotFoundException" error generally occurs when an Android app is trying to launch an Activity using an Intent, but the specified Activity class cannot be found or does not exist. You can try below some hit and trial methods:
Issue can be because of incorrect activity class name so make sure that the activity class name in your Intent is correct, including the package name.
Also make sure that the activity class must be declared in your AndroidManifest.xml file, or it will not be recognized by the Android system.
If the Activity class is present in your code, but you still encountering this error, it could be because the Activity class is not being included in your APK file. This can happen if the class is not being referenced properly in your code, or if the build process is excluding the class from the APK.
If the Activity class is being launched through a deep link, just make sure that the correct Intent filters are set up for the Activity in your AndroidManifest.xml file.
It's also possible that the update from API 32 to API 33 could have caused changes in the Android framework that are affecting your deep links. You may want to check the Android Developer documentation for any changes in the way that deep links are handled in API 33, and make any necessary updates to your code accordingly.
I hope these findings may help you out to rectify your doubt.
Thanks.

Related

Android Intent BroadcastReceiver Example

I am using a Zebra Android Scan-Gun and need to capture the hard-keyboard (not soft) keystrokes for P1, P2, F1, F2, etc... keys. Since Maui doesn't have events for KeyUp/KeyDown/KeyPressed there is nothing to inform me of a special keys being pressed. Not to mention I also have to put an Entry field on screens where there are only buttons because you can't catch a TextChanged event without an Entry.
My current solution involves Zebra StageNow to remap the P1 key to the "+" key and then strip it out of the Entry/TextBox (which is not a very elegant solution)
What I'm trying now is using the Windows app Zebra StageNow in Admin mode to remap the F11 key to send an Intent, OnKeyUp, Broadcast as seen in this screenshot.
Then I generate the bar-codes to program the scan-gun.
In the Android Scan-gun I then run StageNow and scan the bar-codes which programs the F11 key.
Then within my android app I added a class in the Platforms\Android folder called SpecialKeypress.cs
namespace myapp.Platforms.Android
{
[BroadcastReceiver(Enabled = true, Exported = true)]
[IntentFilter(new[] { "com.mycompany.myapp.F11" })]
public class SpecialKeypress : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
var value = intent.GetStringExtra("Key"); // <-- I set a breakpoint here
throw new NotImplementedException();
}
}
}
Then I added the following to my AndroidManifest.xml
<application android:allowBackup="true" android:icon="#mipmap/appicon" android:roundIcon="#mipmap/appicon_round" android:supportsRtl="true">
<activity android:exported="true" android:name="com.mycompany.myapp.F11" >
<intent-filter>
<action android:name="com.mycompany.myapp.F11" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
</application>
I debug the app on the device and press F11 but alas my breakpoint is not hit in the OnReceive function.
I expect I'm missing something fundamental but I tried to keep it as simple as possible for this example. Also, there are no good examples of how to do this with Maui on the internet (yet).
You may need to register a receiver in your AndroidManifest.xml, and put some intent filters that define what type of messages this receiver will get.
For example:
<receiver android:name=".SpecialKeypress">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>

Xamarin C# , I Cant Run Plugin.BLE Codes

I'm trying to make a very simple and basic mobile app for controlling my Arduino with Bluetooth.
Don't have many C# experiences, but it was going well until the Bluetooth part comes.
I've searched everywhere and found this https://github.com/xabre/xamarin-bluetooth-le
and started to do instructions in the readme. But I've got errors every time.
first, I copied these codes to androidmanifest.xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
after that, I added these codes to mainpage.xml.cs
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
var ble = CrossBluetoothLE.Current;
var adapter = CrossBluetoothLE.Current.Adapter;
var state = ble.State;
}
}
But that caused 2 errors: Error CS0103 The name 'CrossBluetoothLE' does not exist in the current context BlueT
and I added using Plugin.BLE; so errors disappeared. and I continued to write;
adapter.DeviceDiscovered += (s,a) => deviceList.Add(a.Device);
await adapter.StartScanningForDevicesAsync();
after I paste these, I got that errors:
Error CS4033 The 'await' operator can only be used within an async
method. Consider marking this method with the 'async' modifier and
changing its return type to 'Task
Error CS0103 The name 'deviceList' does not exist in the current
context
I tried everything but couldn't solve this problem, and I'm sorry like I said, don't have many # or Android programming experiences, just want to send these slider and button data to my Arduino:
This is my mobile controller app

Xamarin run activity from other project in same solution

I have a xamarin solution with two android projects. I would like to run android activity in project1 from project2. I ‘ve seen threads related to this topic (like How to call an activity in another project?
Call activity from another project) and tried many suggested solutions but In the end I always get „Android.Content.ActivityNotFoundException: 'Unable to find explicit activity class {companyname.project2/companyname.project2.Droid.View.LoginView}; have you declared this activity in your AndroidManifest.xml?'” error. Is this possible in xamarin if yes how? Am I doing something wrong? Here is my source code:
Project1:
namespace BigAppManager {
    [Activity (MainLauncher = true, Name = "com.companyname.bigappmanager.MainActivity", Label = " Logowanie", ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, NoHistory = true, LaunchMode = LaunchMode.SingleInstance)]
    public class MainActivity : MvxActivity<MainActivityViewModel> {
        protected override void OnCreate (Bundle savedInstanceState) {
            base.OnCreate (savedInstanceState);
            Xamarin.Essentials.Platform.Init (this, savedInstanceState);
            
            SetContentView (Resource.Layout.activity_main);
            Button button = FindViewById<Button> (Resource.Id.button);
            button.Click += ClickButton;
        }
        private void ClickButton (object sender, EventArgs e) {
  
            //Intent intent = new Intent("companyname.project2.Droid.View.LoginView");
            //StartActivity(intent);
            Intent intent = new Intent (Intent.ActionMain);
            intent.AddCategory (Intent.CategoryLauncher);
            // intent.SetClassName("companyname.project2", "companyname.project2.Droid.View.LoginView");
            intent.SetComponent (new ComponentName ("companyname.project2", "companyname.project2.Droid.View.LoginView"));
            StartActivity (intent);
        }
        public override void OnRequestPermissionsResult (int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults) {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult (requestCode, permissions, grantResults);
            base.OnRequestPermissionsResult (requestCode, permissions, grantResults);
        }
    }
}
Project2:
    
[Activity(Name = "companyname.project2.Droid.View.LoginView", Label = " Logowanie", ConfigurationChanges = ConfigChanges.Orientation | ConfigChanges.ScreenSize, NoHistory = true, LaunchMode = LaunchMode.SingleInstance)]
    public class LoginView : MvxActivity<LoginViewModel>
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.LoginView);
        }
    }
Project 2 android manifest intent filter:
<activity android:name="companyname.project2.Droid.View.LoginView">
<intent-filter>
<action android:name="companyname.project2.View.LoginView"></action>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
I don't think Manifests are merged by default. So if you look at the resulting AndroidManifest.xml in obj/Debug/android when building, you will probably notice that the LoginView entry is missing.
You can try adding the following NuGet package to your App project and see if that will merge the manifests: https://www.nuget.org/packages/Xamarin.Android.ManifestMerger/1.0.0-preview03
Otherwise, you will need to add the same entry manually in your Apps manifest for the LoginView.
EDIT:
Make sure you use the correct intent. This works fine for me:
var intent = new Intent(this, typeof(LoginView));

MvvmCross.Exceptions.MvxException: Failed to create setup instance

I'm upgrading from MvvMCross 5.7 to 6.0.0.
When I try to run the app, it shows the splash screen and just after that, vs2017 gives me the following error:
MvvmCross.Exceptions.MvxException: Failed to create setup instance
The error always is in the same line, no matter which file I set as mainlauncher.
Example:
using Android.App;
using Android.OS;
using MvvmCross.Droid.Support.V7.AppCompat;
using MvvmCross.Platforms.Android.Views;
namespace ClaveiSGApp.Droid.Views
{
[Activity(Label = "App", MainLauncher = true)]
public class MainView : MvxAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.MainView);
}
}
}
The error always is in base.OnCreate(bundle);
Do you have any ideas?
(Let me know if you need more info/code about something)
From the error you're getting, it looks like something bad is happening in CreateSetup method in MvxSetupSingleton (GitHub). I'm guessing here a bit, but I would assume that there's something wrong with how the RegisterSetupType<TMvxSetup> is being called (or it's not being called at all) - you can find this method in MvxSetup (GitHub). Tracking down where the registration happens, it gave me two possible places: MvxSplashScreenActivity<TMvxAndroidSetup, TApplication> and MvxAndroidApplication<TMvxAndroidSetup, TApplication>.
Going forward with this thinking, and assuming you do use SplashScreen in your app. I would suggest updating your SplashScreen activity to inherit from MvxSplashScreenActivity<TMvxAndroidSetup, TApplication> and check if that helps - you would also need to make your SplashScreen is MainLauncher. Your code could look like this:
[Activity(Label = "FirstDemo.Forms.Splash", Theme = "#style/MainTheme", MainLauncher = true, NoHistory = true)]
public class SplashScreen : MvxFormsSplashScreenAppCompatActivity<MvxFormsAndroidSetup<Core.App, App>, Core.App, App>
{
public SplashScreen()
: base(Resource.Layout.SplashScreen)
{
}
protected override void RunAppStart(Bundle bundle)
{
StartActivity(typeof(MainActivity));
base.RunAppStart(bundle);
}
}
If the above is not clear, check out blog post by Nick Randolph (a contributor to MvvmCross), that writes about setting up a brand new project with MvvmCross v6. I know you're upgrading - so it's not the same, but you can at least check if you have made all the changes that are required to run the app. Here's his GitHub repo, with the sample code that I pasted in
After I few days, searching, seeing gihub files and talking with Nick Randolph as #Ale_lipa suggested.
I noticed that the problem was on the .csproj file under the .Droid project. It was trying to compile files that I manually removed from the project and didn't even exist.
I changed it to match the file that Nick has in his repository.
This is the final look:
<ItemGroup>
<Compile Include="SplashScreen.cs" />
<Compile Include="MainApplication.cs" />
<Compile Include="Resources\Resource.Designer.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Views\FirstView.cs" />
</ItemGroup>
Now everything works fine.
I followed the exact steps on the blog post series by Nick Randolph referenced in other answers, and received the same problem as the question specifies [Failed to create setup instance] but in the Xamarin.Forms article. This was due to mixing code from a different part of the example. My specific issue was because the ActivityAttribute that declared MainLauncher=true derived from MvxFormsAppCompatActivity<TViewModel> instead of MvxFormsAppCompatActivity<TMvxAndroidSetup, TApplication, TFormsApplication, TViewModel> Looks like the OP #Brugui sample code may have had the same flaw.

Xamarin.Android - Getting Location Providers returns empty every time

I'm learning to develop for Android through Xamarin right now and I'm following this basic tutorial on Xamarin's website. I created a class-level variable LocationManager _mgr; and call InitializeLocationManager(); inside of my OnCreate(Bundle bundle) method. InitializeLocationManager() is implemented as follows:
public void InitializeLocationManager()
{
_mgr = (LocationManager)GetSystemService(LocationService);
Criteria locCriteria = new Criteria { Accuracy = Accuracy.Coarse, PowerRequirement = Power.Medium };
IList<string> acceptableLocationProviders = _mgr.GetProviders(false);
if (acceptableLocationProviders.Any())
{
locationProvider = acceptableLocationProviders.First();
}
else
{
locationProvider = string.Empty;
}
Console.WriteLine($"Using {locationProvider} as our location provider.");
}
The line Criteria locCriteria = new Criteria { Accuracy = Accuracy.Coarse, PowerRequirement = Power.Medium }; differs from the tutorial because along my troubleshooting journey, someone said that it worked for them. When I simply use Accuracy = Accuracy.Fine I get the same exact results.
The line that is written to the console every single time is Using as our location provider", obviously meaning the empty string.
The class (MainActivity) extends from Activity and implements ILocationListener correctly. The codefile is declared to use System.Linq, so IList methods .Any() and .First() both work correctly.
Why is this not working? I've followed the tutorial nearly identically, save for some variable names. I have ensured that I have location turned on with my testing device. I am not on WiFi, and when I was, it still did not work. I'm on 4G LTE, and it does not work.
Any ideas would be much appreciated.
Thanks so much.
EDIT: UPDATE: I added the following piece of code to my OnCreate() method:
if( ContextCompat.CheckSelfPermission(this, Manifest.Permission.AccessFineLocation) == Android.Content.PM.Permission.Granted )
{
Console.WriteLine($"We've got permission!");
}
else
{
Console.WriteLine($"We don't have permission you idiot!");
}
And the line written is We don't have permission you idiot! every time. My AndroidManifest.xml has these lines:
<uses-sdk android:minSdkVersion="24" android:targetSdkVersion="27" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.LOCATION_HARDWARE" />
<uses-feature android:name="android.hardware.location.gps" />
<application android:allowBackup="true" android:label="#string/app_name"></application>
My AssemblyInfo.cs file has these lines, just like the tutorial:
[assembly: UsesPermission(Manifest.Permission.Internet)]
[assembly: UsesPermission(Manifest.Permission.AccessFineLocation)]
[assembly: UsesPermission(Manifest.Permission.AccessCoarseLocation)]
My application does not request permissions on startup. What is going on?
If LocationManager.GetProviders returns an empty Java ArrayList when requesting provider even if they are turned off/unavailable, then you have not requested permission to course|fine location.
First, either manually add the permission to the manifest:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Or even better, use the Build / Android application / Required Permissions options panel:
Second, if targeting Marshmallow/API-23 or later, make sure you are requesting runtime location permission (and still include the permission entries in the manifest).
https://blog.xamarin.com/requesting-runtime-permissions-in-android-marshmallow/
Note: That you are not using the location criteria that you are defining, you need pass it into the GetProviders method:
IList<string> acceptableLocationProviders = _mgr.GetProviders(locCriteria, false);

Categories