Android

Push Notification to Foreground

This is an interesting case of having an Activity or Fragment to catch a notification going to the top notification area.

If you are using Otto from Square, you can let the holder of such notification know there is a subscriber ready to catch it.

Here is an example where a ServiceIntent finding out if there is a new subscriber via DeadEarsEvent object.

1
2
3
4
@Subscribe
public void deadEarsSubscriber( DeadEarsEvent event ){
    deadEarsEvent = event;
}

In the same intent, we have the condition to whether send the notification or notify the observer via Otto.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//if getDeadEars is false, then there is a subscriber.
if( deadEarsEvent.getDeadEars() ){

    //http://android-er.blogspot.com/2013/03/create-pendingintent-for-notification.html
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)....

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(NOTIFICATION_SERVICE);


    notificationManager.notify((int) System.currentTimeMillis(), builder.build());
}
else
{
    notificationEvent = new NotificationEvent( name, messageName + " " + strings[strings.length - 1], R.mipmap.ic_launcher, "title" );
    bus.post(notificationEvent);
}

You can read more about it from here.

Through the Commonsware book shows an example of having a temporary Broadcast Receiver prevent another one to catch the notification and in such way to show it in the current Activity. This is nice as well, but if you are in the mood for Otto go right ahead.

Android

Making ContentProvider be available for your Gradle Flavors

Are you planning to make your application in different flavors such as paid or free? Are you using a contentProvider? Then you need to update its authority uri depending on the flavor’s package.

In case you need to know how to flavor up your app, read article from developer.android.com

I have looked at several blogs and Stackoverflow, I gotta say the answers were very helpful, yet this is what I did and worked for the lates Android Studio 1.3. One thing I noticed is up to know I didn’t need to declare any suffixes at the build.gradle.

So first declare your flavors along with their packages.

build.gradle

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
apply plugin: 'com.android.application'

android {
   
    productFlavors{
        emulator{
            applicationId "info.juanmendez.app.magazine.emulator"
            versionName "1.0-emulator"
        }

        device{
            applicationId "info.juanmendez.app.magazine.device"
            versionName "1.0-device"
        }
    }
}

This is the content provider declaration.

AndroidManifest.xml

1
2
3
<provider
android:authorities="${applicationId}.service.provider.MagazineProvider"
android:name=".service.provider.MagazineProvider"/>

Content provider now has a dynamic authority uri.

1
public static final String AUTHORITY = BuildConfig.APPLICATION_ID + ".service.provider.MagazineProvider";

Now making calls elsewhere

1
Uri uri = Uri.parse("content://" + BuildConfig.APPLICATION_ID + ".service.provider.MagazineProvider/magazines/");

And that should be it. Good luck.

Android

Testing IntentService in Robolectric.

I was under the impression that testing an IntentService was more about testing the code within than from the service.

But just a few changes, and the service is working. ;)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class MagazineListService extends IntentService
{
    public MagazineListService() {

        super("magazine_list");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Uri uri = Uri.parse("content://" + MagazineProvider.AUTHORITY + "/magazines");
        Uri result;
        ContentResolver resolver = getContentResolver();
        RetroService service = MagazineService.getService();
        ArrayList<Magazine> magazines = service.getIssues();

        for( Magazine m: magazines ){

            result = resolver.insert( uri, MagazineParser.toContentValues(m));
            Logging.print("last segment " + result.getLastPathSegment());
        }
    }
}

The intentService runs by calling its methods rather than usual way from an activity. We create a mock subclass so that it forces to make a call to protected method onHandleIntent. You don’t have to use contentResolver, but for my demo I needed it and to my surprise the service is using the shadowed contentResolver so I didn’t have to replace it with my reference.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
@RunWith(RobolectricTestRunner.class)
@Config( constants = BuildConfig.class, manifest="app/src/main/AndroidManifest.xml", emulateSdk = 21 )
public class MagazineTest {

    static{
        ShadowLog.stream = System.out;
    }


    @Before
    public void init(){

        ContentResolver resolver = RuntimeEnvironment.application.getContentResolver();
        ShadowContentResolver shadowResolver = shadowOf(resolver);
    }


    @Test
    public void testMagazineListService(){

        Intent intent = new Intent( RuntimeEnvironment.application, MagazineListServiceMock.class );

        MagazineListServiceMock service = new MagazineListServiceMock();
        service.onCreate();
        service.onHandleIntent( intent );
    }

    public class MagazineListServiceMock extends MagazineListService{

        public void onHandleIntent( Intent intent ){
            super.onHandleIntent( intent );
        }
    }
}

Here is a proof of the shadowed contentResolver within the service, and if you have any questions let me know.

shadowedResolver

Geek

Finding a bit of fun and inspiration creating icons for special folders

I find it very nice to see the different icons used in technology such as the case of Angular JS. Today it ocurred to me I should stylize important directories with their official icons or my own. I went on to search for logos and cropping them in my favorite editor which is Fireworks. I used this icon generator online.  Here is a tutorial on how to assign icons on windows and here for the apple desktop.

I think is also a great idea to quickly identify folders on your desktop by categories. It is a lot easier than reading every generic folder.

my_icons

Android

Simple demo using AndroidAnnotations in Android Studio 1.0.X

Over the weekend I went back to review some of Android, and wanted to catch up using Android Annotations. It was easily implemented last time in Eclipse but with the new Android Studio I found great material but run into several issues. I wanted others to have peace of mind into building a project on Android Studio. All the credits of this simple demo goes to JayWay’s article who went through the jar file route and helped immensely.

The demo is on github, and has two branches to compare it once Android Annotations is implemented. I really hope this can help anyone struggling to get this to work.

https://github.com/juanmendez/android-annotation-studio-demo

Android Javascript

Chrome DevTools no device found

When debugging a web page from a device to  your desktop using Chrome DevTools, besides having turned on the usb debugging feature on  your phone. You might want to use your command prompt and change to this directory your-android-bundle/sdk/platform tools and then type adb devices. This is going to force to turn on the daemon, find the device hooked, and finally get to see the device under chrome://inspect/#devices

Javascript

Angular Directive input using @ and =

A simple demo. It was funny first time I tried to get the static content via link’s attribute and assign it to a scope.
But this is a demo http://jsfiddle.net/juanmendez/k6chmnch/

A great explanation can be found here on stackoverflow

 

For more on Angular directives, I recommend this article with great insights.

Geek

My Experience Learning Technology

I think learning a new framework or technology is not as much as knowing how to make it work but discovering, finding the joy, and get a sense of confidence before you even start your first line of code.

There are great video tutorials out there. They want you to watch and code along. There are workshops wrapped in technical books. You follow along step by step through chapters until you complete a large exercise. I think of it as a salad of different chapters. And that reminds of a book called Adobe Flex 3:Training from the source.  That way of learning is based on following along and at the same time understanding the process of a framework or technology. But for very large subjects you can get trapped and look back and wonder how the project started, how it ended and what happened in the middle. As you can start to feel you have memory loss. You have been thrown in the  jungle and you are fighting for survival, and having no clue you depend on a technical master to work your way around and find a way to accomplish the mission.

There are other books such as the ones from O’reilly which are not intended to make large applications, but instead they give you each piece of the puzzle. Every demo is simple and focuses on the chapter you are in. You are in the scope of the chapter and that’s it. Maybe there is a final process in the book about a larger application using most of what you have learned from the rest of the book. I personally think this is a great way of learning. You might not know everything but you understand the basic concepts and be beneficial to follow along a larger demo. I would say that’s the best way I can learn.

In my first years of software development, I started learning C++. I remember very vividly an old friend who was ahead of me. He was intimidating me by telling me his and other classmates stories of failing the first course. That made me very scared. So each time the professor went over the blackboard and wrote the code, I wrote them in my notebook and headed after class to the computer lab. I was there testing her code and seeing what it was doing. I modified it at times to see what else would happen. This process has been great as examples are kept simple and can be used to make changes like if I wrote the code giving a sense of confidence.

It’s possible that if you were to learn an easy subject you are going to just follow along and get it straight forward. That was an experience I just had learning Emmet from Lynda.com. Here you are not working chunks of code but understanding how to write shortcuts so the editor can translate it to html and css. And that can also be the case of learning CSS straight from a video tutorial. No need to write large applications.  I was talking to a friend of mine who is learning AngularJS. She was telling me it was a bit hard to just watch and code along. I have already watched the video tutorial. I told her to concentrate more on watching than coding. Better is to understand than break the concentration by following along.

I used to also follow along and test everything I got from books and videos. Until I have realized there are things I will never get to do on that technology. I have felt as it is important and as professional to do the exercises and work on a few external demos. But it has turned out the applications won’t ever require me to do it. The key here is simply know about it. There was once an interview for a job. I remember being asked how well did I know a given technology. I was nervous and didn’t know how to answer as I simply didn’t remember it clearly. The person giving me the interview helped me by telling me you have to answer I don’t know but I can research and figure it out. That’s what is all about know the fundamentals of a technology, read as much and watch demos but until the day comes go back pick on it and apply it in your project.

I am currently learning Android. I am going over a book which has 2600 pages and its name is Commonsware. I think this book is giving me a lot of help as it focuses on the theory and simple exercises. It is quite large and as I already mentioned I don’t need to know everything. I know the first 800 pages were about the fundamentals and I got to read and do each exercise. The rest of the modules are more secondary but important as well. I am reading the book as much as I can. I feel like having a great broad understanding of what is possible to do is important. I cannot continue doing my own demos for each chapter anymore. As this can affect the feeling of fulfilling the understanding of what Android can offer. It’s like going to a concert and waiting in a long line to see a band your friends are telling you is great but you haven’t done your own research. We need to research the technology we are interested. Researching gives you confidence. Research is like reading through a travel book about a new distant city. Once you are there, you would be familiar with culture, and know how to go places of interest. The more you know about it the more you will enjoy your staying and feel more as a local where in technology would be more as a pro. :)

My case with Android is the same I read each chapter. I test the code and see what is going on. I write notes and graphs. Not only I follow the book blindly, I watch youtube videos regarding chapters and find libraries written by the community which can make the process less tedious. All of this is making me more passionate and getting me out of being intimidated as I can even discuss subjects which are more advanced to what I have done. It’s about a mental image of what you can be capable of doing. For several of those chapters, I know the day will come when I can pull out what is needed to be taken care such as knowing how to encrypt an existing database. I know how it works and I can go back to that chapter but it is not as important right now. So make the learning fun and keeping it simple. if a book is trying you to make a large application on your first time, my advice is keep watching and don’t do anything.  Think of it as a movie you are watching instead. You can tell the story but don’t need to be in it. Thereafter you can learn the subject one step at a time.

Android

Android Annotations demo

As I have gone over the fundamentals of the Commonsware series and found Android Annotations fascinating. I took one of the series app demos and converted it into an Android Annotation demo.

What I learned from this exercise:

  • Make sure to read thoroughly the documentation assuming from its intro the framework is easy to replace. I bumped myself a few times with their SharedPreferences injections. Best if you test your injections in a dummy activity.
  • The commonsware example has at times fragment-activities just adding fragments using the ID (R.id.content). For this to work with @fragment injections, I had to set the fragment-activity to have set a plain layout. See more at SimpleContentActivity
  • I had to look twice at referencing Services and Broadcast Receivers because you will see errors by the time you compile. Since the framework does its magic by the subclasses it creates. Even though, You are immediately told by Manifest.xml file when you are not referencing a subclass. Keep in mind subclasses are named the same except they have appended an underscore character.
  • I felt at times I was writing in another language, but I found this approach more elegant. I really enjoyed  replacing AsyncTask classes with injections of @background and @uithreads
  • I feel tired after spending a good amount of time doing this. But it was a great learning lesson, and I think I learned more replacing than doing examples from scratch.

Download or fork my EmPubLite demo and compare

Android

Making Android coding more elegant with Dependency Injection

When I jumped into Javascript, I was very happy to hear about JQuery. It made things easier and less code to write. I still find it a way to cut corners and works great among different browsers and their versions. It is elegant to write in JQuery, I would say and plays greatly with Javascript frameworks. The reason why I write this is because I see an analogy with Android framework injections. These frameworks use hints to brief code and let the framework “inject” code for us. So that way we don’t have to always rewrite the same lines of code when we create an Activity, Fragment or for Fragments, BroadcastReceivers or Services. It is also elegant as it takes away redundant code leaving just the lines that make sense to write.

As I am a big fan of Commonsware book series, I am going over the ActionBarSherlock library. So at the time I got into the fundamentals I wanted to start writing less code, yes I am lazy. I don’t like writing the same code over and over again. So I first went over RobotGuice. It was a framework I heard from a long time ago, but as I started to use it I became aware I was moving my classes into subclasses whose parent classes were made now of the RobotGuice flavor. I was at first okay with it, but once I wanted to use again the ActionBarSherlock library, I realized I had to make use of another layer in between my activity and its parent class SherlockActivity and for that there is a robotguice-sherlock library. I started to notice I was going to go through more than I have to do with just writing plain code for Android. Like other Android developers I went over other frameworks, and I found Dagger. Which states it is very similar without having to slow the process of an application. But still if I were forced to use the ActionBarSherlock library, I would have to play funky and make a move similar to robotguice-sherlock.

Finally I started to read more about Android Annotations. I was blown away, I do not have to extend my activities to another flavor of the frameworks mentioned. This time my activities are sub-classed and that takes to do the magic. I only have to make sure the rest of the application references the subclasses instead. The trick is subclasses are named alike appending an underscore character. So MyActivity is known as MyActivity_ in the Manifest.xml file and for the rest of the application.

This examples shows an activity with plain code using ActionBarSherlock library

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class MainActivity extends SherlockActivity
{

     TextView textView;
     String guice;
     Vibrator vibrator;

     @Override
     protected void onCreate(Bundle savedInstanceState)
     {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);

          textView = (TextView) findViewById(R.id.textView1);
          guice = getResources().getString(R.string.hello_guice);
          vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

          textView.setText( guice );
          vibrator.vibrate(1000l);
     }
}

This examples shows an activity with Robotguice via robotguice-sherlock using ActionBarSherlock library

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@ContentView(R.layout.activity_main)
public class MainActivity extends RoboSherlockActivity
{

     @InjectView(R.id.textView1) TextView textView;
     @InjectResource (R.string.hello_guice) String guice;
     @Inject Vibrator vibrator;

     @Override
     protected void onCreate(Bundle savedInstanceState)
     {
          super.onCreate(savedInstanceState);
          vibrator.vibrate(1000l);
          textView.setText( guice );
     }
}



This examples shows an activity with Android Annotations using ActionBarSherlock library

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@EActivity(R.layout.activity_main)
public class MainActivity extends SherlockActivity
{
     @ViewById(R.id.textView1) TextView textView;
     @StringRes(R.string.hello_guice) String guice;
     @SystemServices Vibrator vibrator;

     @AfterInject //handles injections
     void doAfterInject()
     {
     vibrator.vibrate(1000l);
     }

     @AfterViews //after views are bound to the application
     void doAfterViews()
     {
          textView.setText( guice );
     }
}

I hope this post was valuable and if you would like to share your thoughts or suggestions, please feel free to do so.