Bad Ookami
Wednesday, January 22, 2014
Wednesday, December 18, 2013
Android Studio, Gradle, and JARs
Everything seemed a bit easier in Eclipse when I first started programming for Android. I knew all my shortcuts and where to find things, and everyone was using Eclipse, so all it took was a quick search on Google to find anything that was unclear.
But then I moved to Android Studio, and of course, I was completely lost.
We had to move over to Android Studio when I was in the training phase of my new job, as that's what my instructor used. It was a welcome change, though, as I knew that's the direction Android was moving to eventually. I was just a bit hesitant because it wasn't even at version 1 yet... hell, it wasn't even at 0.5. But, I've learned to love it. I actually tried to go back to Eclipse just yesterday... I forgot all my shortcuts, and it looked funny.
One of those things I had to get used to was using JAR files instead of the library projects I was used to. In Eclipse, when I made a library, I just referenced the project in my other projects. Maybe I hadn't gotten far enough, but I never had to make a JAR file to use it in other projects. Of course, it's completely different in Android Studio. In our projects, all of the libraries we used had to be from JARs, and had to be included with many little steps and Gradle... I won't expand on my dislike for Gradle right now, but it was very annoying to have to learn this weird thing in order to make my Android apps.
This post is about making JARs for your libraries, something I had to learn how to do for the previous blog post. Took me two whole days to figure out everything I needed. Was even tempted to learn how to code with Gradle, but luckily I didn't have to too much.
Making a library project into a JAR
The library project I made only has two classes in it, so it was pretty simple for me. I'm hoping the process is pretty similar if your project has more complexities to it.
In your build.gradle file, there's a line towards the beginning that should say
You want to change this to
To be honest, I'm not 100% sure this is needed, but one of the many MANY tutorials I came across had this, so this was in my build.gradle from the beginning. (Hindsight Note: I remember which tutorial. It's in the section about creating AARs)
Another bit I had to add to my build.gradle is this snippet of code from this StackOverflow Q/A:
Because my project only had classes, this was all that's needed, but according to another question/answer (which I also used for making the JAR), if you used other resources, you might want yours to look something like:
That's it. If/once it's completed, navigate to your project and you'll find that in your build/libs folder if your JAR file.
Making Javadoc and Source JARs
This was a bit difficult for me to understand, and is the part that made me consider trying to learn to do a bit of programming with Gradle. I had gotten the JAR to work in the original project and was excited! But when I hovered over a method, no Javadocs were shown, even though I made sure to document it. Apparently, you have to include SEPARATE JAR files if you want to include Javadocs, and another one if you want the source to be available (trying to look at the source of the original JAR in another project will simply show global variables and method names, everything else masked with "compiled code").
I finally found this StackOverflow answer which I was able to use, but of course it caused some confusion for me: this question and answer aren't related to Android.
I had to cheat to get the javadocJar task to work, as I could not figure out how to properly format the from using the code from before. It's okay, though... it worked, lol. If anyone has any tips on how to get it to work properly with proper code, PLEASE let me know.
The from in the task is essentially just a string to the actual location, so I hard coded it. I'm not sure what classifier is for. I thought it was the a folder name, but the folder name for the sourcesJar is NOT sources, it is in fact source in my project... All I know is that with these two JARs, I have my Javadocs on hover and the source is included. I'm not sure exactly how it works, all I know is that it does. Ah, the life of a programmer.
Once again, I'm not sure of the naming convention, but upon looking at the GSON library, their Javadoc and Sources were named by the lowercase, hyphen-seperated way, adding -javadoc or -sources to the associated name before the .jar (mine looked like nfc-utility-javadoc.jar and nfc-utility-sources.jar)
Bonus: AAR!
I was going to wrap up here, and then I remembered about AAR files. I never actually got it to work in my project, but the actual creation is VERY simple. No new code, really. This blog post is what caused me to change the apply-plugin from android to android-library. Just find your gradlew and run these commands:
Not sure if you have to clean it, but it's probably best to. Your AAR file will be in your build/libs folder.
Again?: Renaming outputed JARs with Gradle!
I'm quite surprised at myself. I went to update the JAR files with some new code and was annoyed that I had to rename the javadoc and source JARs each time. So... I wrote some Gradle code to do it for me, AND move it! Needless to say, I'm a bit excited. I used the sample code in the Gradle docs.
The code isn't difficult to understand, really. The from looks in that directory, include-ing whatever file or files you specify. The ability to rename is there as well, and I rename my files to the appropriate names. And finally, I say into where I want them placed. I tried a lot of combinations in order to find out how to place them in my current directory, come to find out I just had to use my command-line knowledge. And I call it with
Another edit!: This Gradle scripting this is actually pretty cool. By making the very first line of the renameJars task look like this
You only need to run this ONE command, and it will not only make your JARs but it will rename and move them as well. I think I'm going to have to make another blog post about this soon...But then I moved to Android Studio, and of course, I was completely lost.
We had to move over to Android Studio when I was in the training phase of my new job, as that's what my instructor used. It was a welcome change, though, as I knew that's the direction Android was moving to eventually. I was just a bit hesitant because it wasn't even at version 1 yet... hell, it wasn't even at 0.5. But, I've learned to love it. I actually tried to go back to Eclipse just yesterday... I forgot all my shortcuts, and it looked funny.
One of those things I had to get used to was using JAR files instead of the library projects I was used to. In Eclipse, when I made a library, I just referenced the project in my other projects. Maybe I hadn't gotten far enough, but I never had to make a JAR file to use it in other projects. Of course, it's completely different in Android Studio. In our projects, all of the libraries we used had to be from JARs, and had to be included with many little steps and Gradle... I won't expand on my dislike for Gradle right now, but it was very annoying to have to learn this weird thing in order to make my Android apps.
This post is about making JARs for your libraries, something I had to learn how to do for the previous blog post. Took me two whole days to figure out everything I needed. Was even tempted to learn how to code with Gradle, but luckily I didn't have to too much.
Making a library project into a JAR
The library project I made only has two classes in it, so it was pretty simple for me. I'm hoping the process is pretty similar if your project has more complexities to it.
In your build.gradle file, there's a line towards the beginning that should say
apply plugin: 'android'
apply plugin: 'android-library'
Another bit I had to add to my build.gradle is this snippet of code from this StackOverflow Q/A:
sourceSets {
main {
java {
srcDir 'src/main/java'
}
}
}
Because my project only had classes, this was all that's needed, but according to another question/answer (which I also used for making the JAR), if you used other resources, you might want yours to look something like:
sourceSets {
main {
java {
srcDir 'src/main/java'
}
resources {
srcDir 'src/../lib'
}
}
}
}
This setup is required to use the tasks that come next.
task clearJar(type: Delete) {
delete 'build/libs/ProjectName.jar'
}
task makeJar(type: Copy) {
from('build/bundles/release/')
into('build/libs/')
include('classes.jar')
rename ('classes.jar', 'ProjectName.jar')
}
makeJar.dependsOn(clearJar, build)
All I did for my own library was substitute ProjectName for the name I wanted the JAR file to be. I'm not completely sure of the naming convention, but all the library JARs I've seen were lowercased and hyphen-separated, so I named mine "nfc-utility."
That's it (for just the library JAR). In order to actual get your JAR, in a terminal, navigate to your project where the gradlew file is and type the following line:
./gradlew makeJar
Making Javadoc and Source JARs
This was a bit difficult for me to understand, and is the part that made me consider trying to learn to do a bit of programming with Gradle. I had gotten the JAR to work in the original project and was excited! But when I hovered over a method, no Javadocs were shown, even though I made sure to document it. Apparently, you have to include SEPARATE JAR files if you want to include Javadocs, and another one if you want the source to be available (trying to look at the source of the original JAR in another project will simply show global variables and method names, everything else masked with "compiled code").
I finally found this StackOverflow answer which I was able to use, but of course it caused some confusion for me: this question and answer aren't related to Android.
task sourcesJar(type: Jar, dependsOn: classes) {
classifier = 'sources'
from sourceSets.main.allSource
}
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier = 'javadoc'
from javadoc.destinationDir
}
artifacts {
archives sourcesJar
archives javadocJar
}
Of course, this will NOT work in our Android project. I was able to rewrite the task for sourcesJar, using hints from the previous makeJar task. And some of the comments on the answer stated that the dependsOn wasn't needed (which is good, as it never ran with those included).
task sourcesJar(type: Jar) {
classifier = 'sources'
from android.sourceSets.main.java.srcDirs
}
task javadocJar(type: Jar) {
classifier = 'docs/javadoc'
from 'build/docs/javadoc'
}
Once again, I'm not sure of the naming convention, but upon looking at the GSON library, their Javadoc and Sources were named by the lowercase, hyphen-seperated way, adding -javadoc or -sources to the associated name before the .jar (mine looked like nfc-utility-javadoc.jar and nfc-utility-sources.jar)
Bonus: AAR!
I was going to wrap up here, and then I remembered about AAR files. I never actually got it to work in my project, but the actual creation is VERY simple. No new code, really. This blog post is what caused me to change the apply-plugin from android to android-library. Just find your gradlew and run these commands:
./gradlew clean
./gradlew aR
Again?: Renaming outputed JARs with Gradle!
I'm quite surprised at myself. I went to update the JAR files with some new code and was annoyed that I had to rename the javadoc and source JARs each time. So... I wrote some Gradle code to do it for me, AND move it! Needless to say, I'm a bit excited. I used the sample code in the Gradle docs.
task renameJars(type: Copy){
from('build/libs'){
include 'nfc-utility.jar'
}
from('build/libs'){
include 'NfcUtility-sources.jar'
rename 'NfcUtility-sources.jar', 'nfc-utility-sources.jar'
}
from('build/libs/NfcUtility-docs'){
include 'javadoc.jar'
rename 'javadoc.jar', 'nfc-utility-javadoc.jar'
}
into '../'
}
./gradlew renameJars
task renameJars(type: Copy, dependsOn:makeJar){
Another!: Including JARs in your project
Your project more than likely has a libs folder in it already; if not, create one on the same level as java and res. In this folder, add the library jar you want included in your project. Right click and select "Add as library".
In your build.gradle, add the following line in your dependencies:
compile files('path/to/the/lib.jar')
To add sources and javadocs to the library, find the associated JAR files. I added them to my project in the libs folder, though inside of a new folder called docs (the name doesn't matter). This StackOverflow question/answer has another method of doing it (one I tried first with no success) but it states that you should NOT put the javadoc and source JARs in the same folder as the library JAR, so I didn't. Android Studio provides a VERY easy way to include the javadoc and source JARs.
In File -> Project Stucture, select your library. At the bottom, there are four icons: a plus, a plus with a globe, a folder, and a minus. Click on the plus, and add your javadoc and source JARs. If they're correct, Android Studio will know what they are and label them accordingly. Very, very simple.
Conclusion
I felt like I needed to document this all in one space, as I took a combination of two or three different StackOverflow questions/answers in order to get the full effect I was looking for. Once again, if anyone reading this has any improvements or suggestions for me, please let me know!
Tuesday, December 17, 2013
The Android NFC Utility Library
The library can only do but so much, considering it’s written for communication between a device an NFC tag. As a result, this limits it to three basic functionalities: reading a tag, writing to a tag, and handling intents from a tag. But that doesn't mean there's only way to to do all of those things (well.. one of them only have one way, but there's some variations available for the others!)
From the manifest
The first thing an app using this library is going to want to do is properly handle intents from an NFC tag. Most of this work is going to happen inside the AndroidManfiest file. One of the very things to include in your manifest will be the permissions to allow NFC.
<uses-permission android:name="android.permission.NFC" />
<uses-feature android:name="android.hardware.nfc" android:required="true" />The first permission is required for NFC to work at all in your project. The second, however, is only needed if you only want this app to be available to devices that can perform NFC; essentially, making NFC required for a user. If your app only have NFC as a bonus feature and isn't required, I wouldn't include that second permission.
After that, you need to actually handle the different intents given off by NFC. There are three basic types: NDEF_DISCOVERED, TECH_DISCOVERED, and TAG_DISCOVERED. The Android Developer's Guide for NFC explains these three intents and how to filter for each of them so I won't go in to too much detail. I will say that the app that originated this library filtered for all three intents. We used one Activity whose soul purpose was to catch and handle the intents (when fired when the app was closed*), redirecting wherever needed and showing what was asked for.
<activity android:name=".ui.activities.HandleNfcIntentActivity"I'll go over briefly what we did. The activity was given a label ("Create a MoochItem"). Every time a blank or previously-written-to-by-another-app NFC tag was scanned, a chooser (made by Android) would pop up, allowing a user to choose whatever app on their device could handle NFC; because of this, the label was made specific to the action that would happen if selected. In the first intent-filter, you'll see we're filtering for a specific mimeType, a custom one. I'll get more in to that in the section about writing to a tag. Everything else filtered for the most general of things; we wanted our app to be available regardless of what type of tag was scanned. You can, of course, filter for something more specific if you need to.
android:theme="@android:style/Theme.Holo.NoActionBar"
android:label="Create a MoochItem">
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="application/vnd.com.mobiquityinc.mooch.beam" />
</intent-filter>
<intent-filter>
<action android:name="android.nfc.action.TECH_DISCOVERED"/>
</intent-filter>
<meta-data android:name="android.nfc.action.TECH_DISCOVERED"
android:resource="@xml/nfc_tech_filter" />
<intent-filter>
<action android:name="android.nfc.action.TAG_DISCOVERED"/>
</intent-filter>
</activity>
In your application
The example from above has one Activity to handle all intents from when the app is closed... kind of. There is where BaseNfcActivity comes in. BaseNfcActivity enables foreground dispatching, which will allow your activity to "hijack" NFC-related intents while your app is open. I put an asterisk earlier in relation to this: all of our Activities were set up like this, but none of them actually caught outside intents because they didn't need to (at our current stage of development). Only one actually did, which wrote to an NFC tag.
The best way to use this is to have your base Activity extend BaseNfcActivity, have that implement it's required method (setIntentFilters, and probably have it return new IntentFilter[0]), and then have all of your Activities extend your base Activity. When an Activity of yours needs to enable foreground dispatching, have it override setIntentFilters and use the constants in BaseNfcActivity. Also, that Activity would have to override Activity's onNewIntent. In the project where this library was developed, the activity to make use of this functionality looks a bit like this:
public class SaveMoochItemToNfcActivity extends MoochActivity {
private String uuid;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.save_to_nfc_activity);
uuid = getIntent().getStringExtra("uuid");
}
@Override
public IntentFilter[] setIntentFilters() {
return BaseNfcActivity.INTENT_FILTER_NDEF_AND_TECH_AND_TAG;
}
@OverrideSaveActivity's (I refuse to write out that entire name) only function was to write to an NFC tag. MoochActivity was our base Activity, which extended BaseNfcActivity. SaveActivity had it's onCreate do some simple things, prepping for the new intent. It overrode MoochActivity's setIntentFilters, passing it a static IntentFilter array from BaseNfcActivity, allowing it to filter for all three NFC-intents (NDEF, Tech, and Tag). Finally, it overrode Activity's onNewIntent, called super, and did what it needed to do. Pretty simple and straightforward. If you need to, you can have your onNewIntent filter for a specific intent (have the NDEF intent do something different than the Tech intent). To do this, you'd check intent.getAction(), and checking the constants in NfcAdapter (ACTION_NDEF_DISCOVERED, ACTION_TECH_DISCOVERED, ACTION_TAG_DISCOVERED).
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
intent.putExtra("uuid", uuid);
if(MoochNfcUtility.writeToTag(intent)){
//SUCCESS!!! WH000T!!!
finish();
}
else{
//WHY'D IT FAIL!?!?!?
}
}
}
>> Read an NFC tag
I want to say that most of the functionality you need for reading and writing from tags are done in BaseNfcUtility, but I could be wrong; when I took out the code for the library, I had to remove app-specific things and make a new utility which extended the library's. To read from an NFC tag, simply call BaseNfcUtility.readFromTag(), passing in the intent fired from when the activity was scanned. If all goes well, you'll get an array of NdefRecords, which you can do whatever you want with. If you don't know, to actually get a message off of an NdefRecord, call record.getPayload() (you'll get byte[]), and make a new String out of that.
That's pretty much it for reading. Really.
>> Write to an NFC tag
>> Write to an NFC tag
Writing has more complexities to it. There are four static writeToTag methods, all with slightly different parameters. All of them require the Intent from the scanned tag, and you have a choice of sending one or more NdefRecords or a single NdefMessage, allowing you freedom in how you construct your objects, as well as allowing for a boolean so you can write-protect the tag if you so desire (though, it's permanent... very permanent). The library does, however, provide a method for creating MIME NdefRecords: createMimeRecord(), which you can simply pass just your message for a default MIME type, or a custom MIME type and a message (the original application uses the latter, passing it the MIME type you saw in the manifest as well as a UUID for the item we were tracking). Future versions of this library will add methods to easily create other types of NdefRecords.
To give an idea of what Mooch's own utility class looks like:
public class MoochNfcUtility extends BaseNfcUtility {
public static String MIME_TYPE = "application/vnd.com.mobiquityinc.mooch.beam";
public static byte[] generateUUID(){
return ("MOOCH-" + UUID.randomUUID()).getBytes(Charset.forName("US-ASCII"));
}
public static boolean writeToTag(Intent intent){
return writeToTag(intent, createMimeRecord(MIME_TYPE, intent.getStringExtra("uuid")));
}
public static List<String> readTag(Intent intent){In our writeToTag method, all it needs is the Intent, which as you saw in the SaveActivity call to this, we gave the Intent the UUID we needed. This utility uses BaseNfcUtility's writeToTag, passing it the Intent (for the tag) as well as an NdefRecord created from the createMimeRecord, constructed of the custom MIME type and the UUID. For a bit of bonus, the readTag method is here, too, showing what we did with those NdefRecords we get back, making it specific for our app.
NdefRecord[] records = readFromTag(intent);
List<String> messages = new ArrayList<String>();
for(NdefRecord record : records){
messages.add(new String(record.getPayload()));
}
return messages;
}
}
>> Conclusion
So, there you have it. I tried to make the library as simple and easy to use as possible. If you have any questions, feel free to let me know!
Wednesday, November 20, 2013
Patterns
Android is, apparently, very bad at MVC. The setup is there: Activities act as our Controllers, the view XML files are our Views (even though you can create a view programmatically), and the models we write ourselves. But in MVC, input has to go directly into a Controller; with Android, they’re entered in the views and you’d have to retrieve input from the views. While it could work, Android is a bit more suited towards MVVM.

With this pattern, we can get out input from our View (say, an EditTextView) using our ViewModel (our Activity), which in turn would pass that information to our Model (some class we’ve written to handle the data). Our Model can update it’s information and pass that back to the ViewModel from there.
With this pattern, we can get out input from our View (say, an EditTextView) using our ViewModel (our Activity), which in turn would pass that information to our Model (some class we’ve written to handle the data). Our Model can update it’s information and pass that back to the ViewModel from there.
Subscribe to:
Posts (Atom)