I am a little bit confused about the ComponentName class in Android.
There are different ways to get to a component name object, but I don't know when to use which... and why!
Example:
Application package is de.zordid.sampleapp
but widget provider class is de.zordid.sampleapp.widget.WidgetProvider
Using
ComponentName cn = new ComponentName("de.zordid.sampleapp.widget",
"WidgetProvider");
I got this component info: ComponentInfo{de.zordid.sampleapp.widget/WidgetProvider}, but I could not use this - the component is unknown!
But the JavaDoc says I should give the package and the class within that package - and that is what I did, didn't I??
Using
ComponentName cn = new ComponentName(context, WidgetProvider.class);
yields ComponentInfo{de.zordid.sampleapp/de.zordid.sampleapp.widget.WidgetProvider} - and that works fine!!
There is even another way to get a ComponentName - by context and a string.
Which one should be used where and when??
Thanks!
The ComponentName constructor taking two Strings can be used to refer to a component in another application. But, the first argument is not the package name of the class; it is the package name of the application---the package attribute of the manifest element in that application's AndroidManifest.xml. So your first example should be
ComponentName cn = new ComponentName("de.zordid.sampleapp",
"de.zordid.sampleapp.widget.WidgetProvider");
That constructor could certainly be used to refer to components in your own application, but since you already have hold of a Context from your own application you might as well use it and use one of the other constructors. In my opinion, the one taking a Class should be preferred whenever usable. You could use the one taking a String if you only know the class dynamically for some reason; in that case, it should take the fully-qualified class name as above.
Robert Tupelo-Schneck's answer is right about preferring objects against Strings. Here's how I see it with details on how all the different prefixes work.
To refer to your own components, use:
new ComponentName(getApplicationContext(), WidgetProvider.class);
To refer to some dynamically referenced component in your own app, use:
// values/strings.xml: <string name="provider">de.zordid.sampleapp.widget.WidgetProvider</string>
String fqcn = getResources().getString(R.string.provider);
new ComponentName(getApplicationContext(), fqcn);
This is useful when you want to use Android's resource qualifiers to decide which component to use, you can override the default string in values-*/strings.xml.
To refer to another application's component, use:
int componentFlags = GET_ACTIVITIES | GET_PROVIDERS | GET_RECEIVERS | GET_SERVICES;
PackageInfo otherApp = context.getPackageManager().getPackageInfo("com.other.app", componentFlags);
ComponentInfo info = otherApp.activities[i]; // or providers/receivers/...
new ComponentName(info.packageName, info.name);
#About .Names and <manifest package="
There may be some confusion here because I think historically Robert's statement was true:
it is the package name of the application---the package attribute of the manifest element in that application's AndroidManifest.xml
but not any more. Since the new Gradle build system was introduced there has been some changes around here, and then they changed it again in AGP 7.3, and made it mandatory in AGP 8.0.
If you have an android.defaultConfig.applicationId specified in your build.gradle that'll be the app package name, and then package attribute in manifest (or later namespace in build.gradle) is a separate thing when building your app. The first argument of ComponentName now refers to applicationId + applicationIdSuffix. The tricky thing is that after the final manifest merge and packaging the APK will have <manifest package=applicationId + applicationIdSuffix and all the .Names will be expanded to FQCNs.
Example app for learning name resolution
Here's an example structure based on the structure of one of my apps. Consider the following classes in a hypothetical app called "app":
net.twisterrob.app.android.App
net.twisterrob.app.android.GlideSetup
net.twisterrob.app.android.subpackage.SearchResultsActivity
net.twisterrob.app.android.subpackage.Activity
net.twisterrob.app.android.content.AppProvider
on the server side backend of the app and/or some shared model classes:
net.twisterrob.app.data.*
net.twisterrob.app.backend.*
net.twisterrob.app.web.*
in my Android helper library:
net.twisterrob.android.activity.AboutActivity
other libraries:
android.support.v4.content.FileProvider
This way everything is namespaced in net.twisterrob.app. The android app being just a single part of the whole inside it's own subpackage.
AndroidManifest.xml (irrelevant parts omitted)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.twisterrob.app.android">
<!--
`package` above defines the base package for .Names
to simplify reading/writing the manifest.
Notice that it's different than the `applicationId` in build.gradle
and can be independently changed in case you want to refactor your packages.
This way you can still publish the same app with the same name.
-->
<!-- Will be expanded to net.twisterrob.app.android.App in the manifest merging phase. -->
<application android:name=".App">
<!-- meta-data needs FQCNs because the merger can't know if you want to expand them or not.
Also notice that name and value both can contain class names, depending on what you use. -->
<meta-data android:name="net.twisterrob.app.android.GlideSetup" android:value="GlideModule" />
<meta-data android:name="android.app.default_searchable" android:value="net.twisterrob.app.android.subpackage.SearchResultsActivity" />
<!-- Will be expanded to net.twisterrob.app.android.subpackage.Activity in the manifest merging phase. -->
<activity android:name=".subpackage.Activity" />
<!-- Needs full qualification because it's not under the package defined on manifest element. -->
<activity android:name="net.twisterrob.android.activity.AboutActivity" />
<!-- Will be expanded to net.twisterrob.app.android.content.AppProvider in the manifest merging phase. -->
<provider android:name=".content.AppProvider" android:authorities="${applicationId}" />
<!-- Needs full qualification because it's not under the package defined on manifest element. -->
<provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.share" />
</application>
<!-- ${applicationId} will be replaced with what's defined in `build.gradle` -->
</manifest>
build.gradle
android {
defaultConfig {
// this is what will be used when you upload it to the Play Store
applicationId 'net.twisterrob.app'
// in later AGP versions, move manifest's package here:
// namespace 'net.twisterrob.app.android'
}
buildTypes {
debug {
// The neatest trick ever!
// Released application: net.twisterrob.app
// IDE built debug application: net.twisterrob.app.debug
// This will allow you to have your installed released version
// and sideloaded debug application at the same time working independently.
// All the ContentProvider authorities within a system must have a unique name
// so using ${applicationId} as authority will result in having two different content providers.
applicationIdSuffix '.debug'
}
}
}
To check out what your final manifest will look like after all the merging open build\intermediates\manifests\full\debug\AndroidManifest.xml.
Or you can use like this inside BroadcastReceiver :
ComponentName smsReceiver = new ComponentName(this, SMSReceiver.class);
Related
I am having trouble creating a widget configuration activity using Xamarin Forms. What I think is going on is, when compiled, the name of the package gets replaced by a random #/string for the main activity and whatnot. However, if I inspect the resulting APK, I can see that the <appwidget-provider ... android:configure="my.package.myClass".../> does not get updated. I think it should be <appwidget-provider ... android:configure="randomstring.myClass".../>. So I believe this is preventing the configuration screen from appearing. Is there a way to force the package name on this attribute to be updated using Xamarin? Or is there a way to set this attribute in code before it gets called during widget placement?
Here is my configuration (package name has been simplified to help debug):
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="288dip"
android:minHeight="72dip"
android:resizeMode="horizontal"
android:minResizeWidth="144dip"
android:updatePeriodMillis="1000"
android:initialLayout="#layout/Widget"
android:previewImage="#drawable/previewImage"
android:configure="quickclip.QuickClipConfigActivity"
/>
namespace quickclip
{
[Activity(Label = "QuickClipConfigActivity", Name= "quickclip.QuickClipConfigActivity", Exported=true )]
[IntentFilter(new string[] { "android.appwidget.action.APPWIDGET_CONFIGURE" })]
public class QuickClipConfigActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Setup);
SetResult(Result.Canceled);
// Create your application here
}
}
}
The name field of the [Activity] attribute was just added for debug purposes. With or without it, placing the widget does not display the config screen, nor does it enter the activity class (verified by breakpoints), nor does the widget display. However, if I remove the android:configure="my.package.myClass" I can get the widget to appear normally.
If you don't explicitly specify it, Xamarin.Android will calculate some MD5 and use that to prefix all Android Callable Wrappers with that MD5 for the namespace.
To avoid that you can use the RegisterAttribute on your types:
[Register("my.cool.namespace.MyType")]
public class MyType : SomeJavaType
{
}
For an Activity or Service you can use the Name property in the ActivityAttribute or ServiceAttribute like so:
[Activity(Label = "My Activity", Name = "my.cool.namespace.MyActivity")]
public class MyActivity : Activity
{
}
Or you can combine the ActivityAttribute with the RegisterAttribute:
[Register("my.cool.namespace.MyActivity")]
[Activity(Label = "My Activity")]
public class MyActivity : Activity
{
}
This should produce a nice entry in your AndroidManifest which is easy to use from either layout files or other Apps/Widgets.
I tried make android studio template like activity template by this instruction
Current package set in globals.xml.ftl
<global id="srcOut" value="${srcDir}/${slashedPackageName(packageName)}" />
and create template file
<instantiate from="src/app_package/LifecycleFragment.java.ftl"
to="${escapeXmlAttribute(srcOut)}/${className}.java" />
It force my template file to src/main/java/myPackageName
But my current package is kotlin
How can i create template in current selected folder?
Sorry if I'm late with my answer, but maybe it will be useful for someone.
To change the source package from java to kotlin try add this line to globals.xml.ftl:
<global id="kotlinMainSourceSet" value="${srcOut?replace('java','kotlin') />
Use it in your receipt.xml.ftl as following:
! Replace SomeClass.kt.ftl with your class in app_package;
! Replace your_needed_path with path, in which you would like to put the file
! Replace someClassName with the id of the className from template.
<instantiate
from="src/app_package/SomeClass.kt.ftl"
to="${escapeXmlAttribute(kotlinMainSourceSet)}/${your_needed_path}/${someClassName}.kt" />
In addition I'll answer on the #AlexeiKorshun question with which I've faced too: applicationIdSuffix is added, while creating a directory. This can be easily fixed by overriding srcOut in your globals.kt.ftl with following:
<global id="srcOut" value="${srcDir}/${slashedPackageName(packageName?replace('.dev|.qa2|.stage', '', 'r'))}" />
.dev/.qa2/.stage are added as an example,please replace them with yours.
Is it possible to specify multiple keys for Google Maps Android API in the same code base?
It looks like I have to change the key in manifest file each time I change keystore. It's not very convenient, imho, if you need to test the app signed with keys form debug and release keystores.
I added both keys in the manifest at once. Like this
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
..
android:versionCode="1"
android:versionName="1.0" >
<!-- RELEASE key -->
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="my-release-keu" />
<!-- DEBUG key -->
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="my-debug-key" />
</application>
</manifest>
Apparently, this works. Looks like Google code is smart enough to use relevant key automatically.
I don't think this is what you want to do. You should add both debug and release SHA1 key to API key on Google Developer API Console. Take a look at this answer
AFAIK, there is no programmatical form on doing this. For comodity, you can define API keys in strings.xml, and retrieve it from the manifest
String debugMapKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
String releaseMapKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
String mapKey = BuildConfig.DEBUG ? debugMapKey : releaseMapKey;
MapView mv = new MapView(this, mapKey);
I have a problem that I just cannot figure out. I am using Eclipse to create my own Content Provider but keep getting the following error:
[..] ERROR/ActivityThread(1051): Failed to find provider info for
my.package.provider.countrycontentprovider
Code found here: http://codepad.org/Rx00HjHd
Main parts:
public class CountryContentProvider extends ContentProvider {
public static final String PROVIDER =
"my.package.provider.countrycontentprovider";
public static final Uri CONTENT_URI =
Uri.parse("content://" + PROVIDER + "/country");
// ...
#Override
public boolean onCreate() { return true; }
// ...
}
// from my activity
ContentResolver resolver = getContentResolver();
Cursor c = resolver.query(CountryContentProvider.CONTENT_URI,
null, null, null, null);
// AndroidManifest.xml
<provider
android:name="my.package.provider.CountryContentProvider"
android:authorities="my.package.provider.countrycontentprovider" />
I have added the provider to the manifest and return true from the onCreate function. I use the CountryContentProvider.CONTENT_URI in my activity to get the Content from my provider, but I just keep getting that error message. I have removed and added the code three times (in case of eclipse melt down) to no avail.
I must be missing something. Can someone point me in the right direction?
I was able to reproduce your problem when I moved <provider> out of the <application>...</application> tag. Eclipse didn't say anything like error or warning.
Fortunately this issue is detected by Android Lint starting from ADT 20.
It worked for me only after specifying full path in Authorities tag in manifest file (see SearchableDictionary sample code in SDK).
<provider android:name=".DictionaryProvider"
android:authorities="com.example.android.searchabledict.DictionaryProvider">
Inside your B-app which has the contentresolver, add this in the AndroidManifest.xml, outside application-tag
<queries>
<provider android:authorities="com.authoritiesname.in.contentprovider.app" />
</queries>
Setting the exported attribute to true in the provider tag in the manifest worked for me :
android:exported="true"
According to the documentation(http://developer.android.com/guide/topics/manifest/provider-element.html#exported), export is required only if the provider is to be available for other applications. But this is the only solution that worked for me.
The android:authorities= in the XML file is the content authority that is located in the contract class that you probably built. The content authority is added to the scheme to make the base content URI. Plain English, the reverse domain you used to make your app no caps here com.domain.sub.appName.
The android:name is the folder plus class your provider is named, do not forget the dot .folder.ProviderClassContentAuthorityIsIn.
Hope this helps :)
you have a capital letter and on the other line, one lowercase letter.
android:name= "my.package.provider.-C-ountryContentProvider"
android:authorities="my.package.provider.-c-ountrycontentprovider"
it must be the same everywhere.
public static final String PROVIDER =
"my.package.provider.countrycontentprovider";
Register your provider in the Android Manifest
<provider
android:authorities="your_content_authority"
android:name="yourProviderClass"/>
I am having a problem in running Android unit test. I got this error when I tried to run a simple test.
Here's the log:
Blockquote
java.lang.RuntimeException: Unable to resolve activity for: Intent { act=android.intent.action.MAIN flg=0x10000000 cmp=com.wsandroid.Activities/.SplashActivity }
at android.app.Instrumentation.startActivitySync(Instrumentation.java:371)
at android.test.InstrumentationTestCase.launchActivityWithIntent(InstrumentationTestCase.java:120)
at android.test.InstrumentationTestCase.launchActivity(InstrumentationTestCase.java:98)
at android.test.ActivityInstrumentationTestCase2.getActivity(ActivityInstrumentationTestCase2.java:87)
at com.wsandroid.test.activity.TestEULA.setUp(TestEULA.java:15)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:430)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1447)
This error occurs for Android less than 2.2. It works fine for Android 2.2 emulator. Yet Android 2.2 emulator has a bug of sending a key twice even though we only press it one. Application to be tested runs on Android 2.2 platform.
Appreciate if anyone of you can help me.
Dzung.
This can also be cause by a missing
Make sure you have a corresponding entry in your manifest.
<activity android:name=".SplashActivity" ...
I had a similar problem with a simple test project for an app that was just a splash screen. I found that I had implemented the constructor wrong. My initial implementation of the constructor was this...
public SplashScreenTest(){
super("com.mycomp.myapp.SplashScreen", SplashScreen.class);
}
After some beating my head against the wall, I somehow decided to remove the SplashScreen from the pkg argument of super(). My successful implementation is now like this...
public SplashScreenTest() {
super("com.mycomp.myapp", SplashScreen.class);
}
I hope that this helps you or others solve the problem.
Try to check your Manifest.xml file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tablet.test"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<uses-library android:name="android.test.runner" />
</application>
<uses-sdk android:minSdkVersion="8" />
<!-- This line below! -->
<instrumentation android:targetPackage="com.tablet.tablet"
android:name="android.test.InstrumentationTestRunner" />
</manifest>
You need to check the following line:
<instrumentation android:targetPackage="com.tablet.tablet"
android:name="android.test.InstrumentationTestRunner" />
So the targetPackage must be the same as in your code.
I had specific similar problem while using the AndroidAnnotations lib.
Later, I found out it was due to forgetting to use the generated class (MyActivity_ instead of MyActivity).
In my case the problem was that TestFragmentActivity, meaning the Activity used in our test
extends ActivityInstrumentationTestCase2<TestFragmentActivity>
must be available in the package defined in Manifest.xml as targetPackage:
<instrumentation
android:name="android.test.InstrumentationTestRunner"
android:targetPackage="de.my.androidhd" />
My solution was to move TestFragmentActivity into tested application package.
For the keys being sent twice issue, are you sure you're not now getting both the Down and Up actions? I had this issue when using Robotium, and generated this to make things easier:
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.widget.EditText;
import com.jayway.android.robotium.solo.Solo;
public static void type(Solo robot, EditText edit, String text) {
int index = 0;
//Find the index of this control, as Robotium doesn't seem to like R.id
for (int i = 0; i < robot.getCurrentEditTexts().size(); i++) {
if (robot.getCurrentEditTexts().get(i).getId() == edit.getId()) {
index = i;
}
}
robot.clickOnEditText(index);
KeyCharacterMap map = KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD);
KeyEvent[] events = map.getEvents(text.toCharArray());
for (int event = 0; event < events.length; event++) {
if (events[event].getAction() == KeyEvent.ACTION_DOWN) {
robot.sendKey(events[event].getKeyCode());
}
}
}
I've had two activities with same name in different packages. Issue was about importing from the wrong package. I spend much time on it maybe it will save someone some time.