Saturday, October 27, 2012

Show Dialog in Android After Device Boot Is Finished

What to do if you want to show an alert dialog right after the device boot is finished? You receive ACTION_BOOT_COMPLETED but you can't show an alert dialog from the broadcast receiver if you don't have any activities. Thus, what you need is to create one. But if you want your users to see only the dialog, your activity must be completely transparent.

1. Transparent activity style.
First, you need to create a transparent activity. Add this style to styles.xml:

Any activity that has this style as a theme will be transparent.

2. Activity with a simple dialog.
Now lets create an activity that will show a simple dialog:
public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Message")
               .setTitle("Title")
               .setCancelable(false)
               .setPositiveButton("OK", new DialogInterface.OnClickListener()
               {
                   public void onClick(DialogInterface dialog, int id) 
                   {
                       MainActivity.this.finish();
                   }
               });
  
  
        AlertDialog alert = builder.create();
        alert.show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}
3. Broadcast receiver.
Obviously you need a broadcast receiver that handles ACTION_BOOT_COMPLETED broadcast (note that you need a permission to receive the broadcast):
public class OnBootReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {  
        Intent startIntent = new Intent(context, MainActivity.class);
        startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(startIntent);
    }
}
4. Android manifest
In your manifest you must assign the created style for your activity and register the broadcast receiver. It should look something like this (note that you need a permission to receive the broadcast):


    
    

    
        
            
                

                
            
        
        
        
            
                
            
        
    


That's pretty much all you need to show a dialog after the device's boot is complete. Source code can be obtained from Github.

Monday, October 22, 2012

Get the APK's Code Size in Android

In the early version of my DELTA Statistics application for Android I collected code size of an installed application. When a lot of statistics about an installed application is easy to get, code size slightly more complicated.

 Step by step:
  1. Download IPackageStatsObserver.aidl and PackageStats.aild. You can get them from here.
  2. Create new package in your project and name it android.content.pm.
  3. Add IPackageStatsObserver.aidl and PackageStats.aild to the created package. You can do it by right-clicking on the package name and choosing Import option. Then select File System and click Next. Browse to the folder where you downloaded .aidl files, check the files you need and click Finish.
  4. Check that Eclipse automatically generated IPackageStatsObserver.java in gen.android.content.pm. Mine has some warning but trying to fix them is just a waist of time.
  5. Now we can get code size of application. In the example below I collect code size of all the installed applications. When I first wrote it I got a weird bug. Sometimes code size was 0 for the last N applications. N was different practically all the time, so, I though that it was a concurrency issue. As I understand, getPackageSizeInfo() method is invoked in another thread and because of that for loop can end before all the values of code size have been computed. To solve this problem I included a semaphore that is acquired at each loop iteration and is released after code size has been computed. It guarantees that getPackageSizeInfo() will finish before the next loop iteration will start.
    context = getApplicationContext();
    final PackageManager packageManager = context.getPackageManager();
    List<ApplicationInfo> installedApplications = 
        packageManager.getInstalledApplications(PackageManager.GET_META_DATA);
    
    // Semaphore to handle concurrency
    final Semaphore codeSizeSemaphore = new Semaphore(1, true);
    
    // Code size will be here
    long codeSize = 0;
    
    for (ApplicationInfo appInfo : installedApplications)
    {
        try
        {
            codeSizeSemaphore.acquire();
        }
        catch (InterruptedException e)
        {
            e.printStackTrace(System.err);
        }
        
        // Collect some other statistics
        
        // Collect code size
        try 
        {
            Method getPackageSizeInfo = 
                packageManager.getClass().getMethod("getPackageSizeInfo", 
                                                    String.class,
                                                    IPackageStatsObserver.class);
            
            getPackageSizeInfo.invoke(packageManager, appInfo.packageName, 
                                      new IPackageStatsObserver.Stub()
            {
                // Examples in the Internet usually have this method as @Override.
                // I got an error with @Override. Perfectly works without it.
                public void onGetStatsCompleted(PackageStats pStats, boolean succeedded) 
                    throws    RemoteException
                {
                    codeSize = pStats.codeSize;
                    codeSizeSemaphore.release();
                }
            });
        }
        catch (Exception e)
        {
            e.printStackTrace(System.err);
        }
    }
    

Tuesday, October 16, 2012

Skype Icon Missing (Windows Default Icon Instead)

Finally got my hands on this annoying problem with the Skype's icon. Instead of Skype logo icon I had an ugly default Windows icon in the taskbar (I have Skype pinned to the taskbar). When I unpinned Skype, the icon came back but no for a long time. Default Windows icon appeared after the next right click on the taskbar icon.

It happened to be not a Skype's problem but a problem with Windows icon cache. I rebuilt it, restarted the computer and the problem was solved. So, that's what you need to do to rebuild the icon cache:
  1. Open Command Prompt (how? ehhh, type cmd in the search box in start menu).
  2. Type this commands (the last one will reboot the machine)
    taskkill /IM explorer.exe /F
    cd /d %userprofile%\AppData\Local
    del IconCache.db /a
    shutdown /r /f /t 00
After that your machine will reboot and the issue should be fixed.

Sunday, October 14, 2012

Delete Space After Link in HTML

Have you noticed that sometimes you have white space included in your link in the end when you use <a href=""><a/> tag?

Here is an example: Weird Link .

If you look closer you will see white space after the link although I didn't include any in HTML (sorry for the link formatting, it is probably hard to see). I wanted to fix it using CSS but after 15 minutes recognized that it goes away if you put the closing tag </a>  right after the text and not on the next line.

So, this is the same link but with the closing tag on the same line: OK Link.

May be it is intended to be like that but it is still strange that Next Line character is treated like a Space character.

Change Boot Order in GNU GRUB

If you installed Ubuntu then you probably got GNU GRUB 2 with it. It is this thing that allows you to choose what operating system (or tool) you want to boot. Default option is usually your new Ubuntu installation and you have 10 seconds by default to boot something else.

In case if you want to use Windows as your primary operating system and just got Ubuntu for some special case (e.g. I just wanted to play with EXT4 file system), booting Ubuntu by default is not the best option for you. Sometimes you are just not near your computer to choose another OS during this 10 seconds period (happened kind of a lot with me). So, let's change that.

  1. Count the number of the entry you want to boot by default (its row number in GNU GRUB) when you machine starts. 
  2. Load Ubuntu and start Terminal.
  3. Type sudo gedit /etc/default/grub.
  4. Change GRUB_DEFAULT to the number of the entry you want to boot by default (0 is the first entry (row), 1 is the second, etc.). I have 7 entries and want to load the last one, so  GRUB_DEFAULT=6.
  5. You can change GRUB_TIMEOUT to change how much time (in seconds) the system will wait before loading the default option.
  6. Type sudo update-grub in terminal to update GRUB configuration.
  7. Restart Ubuntu and enjoy.

Thursday, October 4, 2012

UNIX Permissions (chmod Tips)

Some basic useful stuff on UNIX permissions and chmod command:
  1. 'ls' command outputs permissions for the specified file. It outputs permissions for all the files and directories in the current directory if you don't specify FILE_NAME:
    ls -lg FILE_NAME
  2. If you want to set permission for particular files or directories then you can use find + exec. The first command will change permission of all the directories. The second one specifies the search pattern - all .HTM files.
    find . -type d -exec chmod 755 {} \;
    find . -type f -name '*.htm*' -exec chmod 755 {} \;
    755 here is the permissions code.

Saturday, September 29, 2012

Pause Console Application in the End

If you want to pause your Visual Studio console application in the end, there is no need to insert something like Console.ReadKey(). If you run your application with Ctrl-F5 (Run without Debug) then Visual Studio creates and runs a batch file that look something like that:
your_program.exe
@pause
So, command line will pause with "Press any key to continue..." message when your program is done and you will be able to examine the output.

Input Arguments for Console Application in VS

If you want to run your console application from Visual Studio (Ctrl-F5) and you need some input arguments that you need to specify them in Project -> Properties -> Debug -> Start Options -> Command line arguments.

Friday, September 28, 2012

Why science TV programs suck

We, all saw a lot of popular science programs on TV. BBC, Discovery and others show them all the time. And somehow all the programs about nature are interesting and amazing and all the science programs suck. They try to explain very interesting things but immediately fail because of stupid effects or science guys who look ridiculous trying to explain the universe looking at the spider web or playing a piano and saying: "OK, this has nothing to do with this web/piano, but I will still proceed." I understand that networks just need ratings and it causes weird decisions. But are there a lot of guys who would love to watch something solid and serious, who would love not to be treated like all they want is entertainment. I would totally pay extra for that.

Windows Command Prompt Tips

1. Copy/Past to the Command Prompt
Not very convenient but still easy. You can Right-click on top of the command prompt window (top window bar) and choose Edit menu. There you can copy text from the command prompt and past into it.

2. Open Command Prompt in Current Directory
Discovered this feature only recently. It made my life much easier. Right-click somewhere in directory (not on the file or menu) with the Shift button down. You will see a new option "Open command windows here" that will open Command Prompt in the current directory. This feature does not work inside Libraries (Documents, Pictures, etc.) in Windows 7. Don't really know why. May be path to the directory is ambiguous because you can add a lot of directories to your library. Although, paths in sub directories are well defined but this feature still does not work.

DELTA Statistics

I really want to write about my new Android applications that collects statistics for my DELTA research project at the USF. It is my first serious experience with Android (before I worked more with JNI and native code) and especially with Beta testing. What I want to do is to cover some Android features that I used and also to talk about my application's design.

So, that what comes to mind:
  1. Alarms in Android (how to schedule alarms and do something when you receive them).
  2. Background services and WakeLocks.
  3. Alerts in Android.
  4. Text file handling (saving, etc.).
  5. Sending data with HTTP post request.
  6. Custom notifications.
  7. How to catch when device goes asleep (doesn't look very big but I am really exited about this because I did not find any information on in).
I think I will just divide everything in 8 posts (don't know how I will write all this...): these seven above and one about general design ideas I had in mind when I wrote the application.

Tuesday, September 4, 2012

Get Cause of Exception

Got a weird InvocationTargetException in Android. Why nobody told me to call getCause() method first and not to google it for half an hour? Happened to be a security violation (did not have a required permission) and a simple fix.

Saturday, July 28, 2012

Pass NULL to the Contains Method in C#

I wanted to use FirstOrDefault method inside of the Contains method for List<T>. FirstOrDefault(...) method returns the first appearance of the element (defined by the expression in the brackets) or the default element. Default element is the result of default(SomeClass) and is NULL for all user-defined classes. Thus, my concerns was what would happen if I will pass NULL to the Contains method. It happens that Contains just returns FALSE wherever it has NULL as an input parameter. It does not depend on whether are any elements in the collection.

Sunday, July 22, 2012

Wrath of the Titans

Why can't they make a good movie based on the Greek mythology? As I recall Troy with Brad Pitt was the only one worth noting. The only thing Wrath of the Titans has is effects. They are really good. No credit for good characters in the plot ad they are all were created long long ago. They tried to merge several myths and obviously failed. Worst of all, the movie is totally meaningless. I don't get why they fight, for what and who are they. Why not just follow the myth then? They have a lot of sense.

Wednesday, June 27, 2012

GUID in C#

I always forget useful stuff about GUID.

1. How to create GUID from string?

Guid newGuid = new Guid(Guid_As_String);

2. How to compare to GUID values?

Guid a;
Guid b;
if (a == b)
{
      // Do something
}

You can compare them with == operator because it is overloaded for Guid type (see here).

3. How to get new Guid?

Guid a = Guid.NewGuid();

Saturday, May 26, 2012

My New Project

Two weeks have passed since my arrival to Samara and I am finally all into my new project (well, no mine actually). I will write a formulas descriptor for a bank software. It will allow one to create new formulas for various coefficients in IronPython. The scripts will be connected to .NET C# code using Microsoft DLR. 

So far I spent a week digging into the source code and realized that it is extremely difficult without any comments and documentation (my case). I actually do not understand how my project manager (who wrote all 100,000 lines of code) remembers all the design principles and how he plans to do it in 3 years... I assume he is  just much smarter than me. So, one thing I understand very clearly now is that comments and documentation matter and are very important. The clearest and the best-written code in the world is practically unsupportable and very hard to understand without them.


Spaces in Windows Command Line

Oh dear! How silly I feel now... I spent years playing with spaces in Windows Command Line and always used the rule: "make sure that there are no spaces in your path". But only now I realized that one can just use quotes and all the command will work even with spaces in paths.

So, to call pscp.exe for the file in c:\Program Files\My Web Sites\ just print:
pscp "c:\Program Files\My Web Sites\"
and everything will work perfectly correct.

Thursday, April 5, 2012

Project Presentation

Just did a presentation about my project and it does not feel good. The project is great, flaws in implementation are undetectable))) It was nominated as the best project also. But it still does not feel right.

Probably the problem is my presentation. I did not prepare good enough. Come on! I know this project from the first line of UI code to the last problems in the threads model. I can make a good presentation easily, right? NOOOOO! It seems that I can't. Even if you are an expert in something, you still need to prepare presentation to make a good impression. And this impression about your project matters. You can have an amazing interface, efficient clear code and great user experience but your audience is not your users. People have not tried your application and they do not know that it is good or bad. You must convince them that you did a great work. You must amaze them with a presentation of your features and the technologies you used.

Monday, March 5, 2012

Code Signing

1. http://en.wikipedia.org/wiki/Code_signing
An article from Wikipedia. Not very good and does not provide a lot of information. But explains the general concepts of application signing and its purposes.

2. http://msdn.microsoft.com/en-us/library/ms537361.aspx
Introduction to code signing by Microsoft. General, no specifics, formal words.... Microsoft style. But one can understand some global purposes of signing from that.

Have not found anything useful yet....

Friday, March 2, 2012

Timsort

http://www.drmaciver.com/2010/01/understanding-timsort-1adaptive-mergesort/
Very good and clear article about the ideas under Timsoft algorithm.

http://svn.python.org/projects/python/trunk/Objects/listsort.txt
Original Tim Peterson description of the proposed algorithm and its evaluation.

http://warp.povusers.org/SortComparison/
Good and colorful comparison of standard sort algorithms (without optimization) but does not include Timsort.

Minus of the algorithm is that it uses O(n) space while normal merge sort algorithm uses only O(ln(n)) additional space in the stack (because it uses recursion). May be unsatisfying with really big N.

List Sort

A very simple programming problem gave me the idea to look what modern search algorithm is the best. At the moment, I know and have used only merge sort and insertion sort. But I have never tried to compare their performance in different cases (different list lengths, different data, etc.).

After several minutes of search, I found that the insertion sort performs better on small array while merge soft performs better on large arrays and is theoretically better. It takes O(n*ln(n)) time comparing to O(n^2) time for the insertion cost. BUT! Python introduced TimSort in 2002 and have been using it since. As I understood, Android uses it since API Level 5 and a discussion about Java sort algorithm started in 2009 leaded to Java using TimSort now too.

From Wikipedia I understood that Timsort (invented by Tim Tim's_Lastname but described in some paper in 1990s) is an adaptive search algorithm that uses the idea that real world data is usually not random but partially sorted. Thus, it explores different data features and adapt to them. It achieves O(ln(n)) result on partially sorted data and is only 1.5% slower that optimized merge sort on the completely random data.

To be continued....

Monday, February 27, 2012

End of Synchronization

Finally finished my Operating Systems project on threads synchronization. Baboons are happily on the right sides. The  task was a "Baboons on two sides" problem with a FIFO order requirement. Used classic Readers/Writers solution for the baboons problem and conditions variables to ensure the FIFO order. After the assignment is done it seems so easy))))

By the way, if you are new to synchronization, then check Little Book of Semaphores. It is easy to read and has a lot of solutions to the classic synchronization problems. Although, it is not very high-technology. For example, it does not use conditional variables to guarantee the FIFO order. Instead, it uses tricky constructed queue, which is much harder.

Source code: https://docs.google.com/open?id=0B150EMF9ZCuUbVdtZUU2cW9TNnVQX1B4Yk9zbHRDUQ

Sunday, February 26, 2012

How to Port PThread-Win32

Finally got it!
  1. Put your .h files (pthread.h, semaphore.h, sched.h) into $Visual_Studio/VC/include.
  2. pthreadVC1.dll goes to C:/Windows. Not the best idea but I am out of time and this works.
  3. pthreadVC1.lib goes to $Visual_Studio/VC/lib. Also, include it in the Linker. Project Properties -> Configuration Properties -> Linker -> Input -> Additional Dependencies. Add there pthreadVC1.lib.
These actions should eliminate all external linking errors. Although, you may still have problems when you run the application. I got the error: pthreadVC1.dll missing. In this case, put pthreadVC1.dll into C:/Windows/SysWOW64 where all other dlls are (like kernel32.dll). Probably it is a better solution to start with.

Also, use Sleep() for Windows (add #include <Windows.h>) and sleep() (add #include <unistd.h>) for UNIX-based systems.