Pages

Friday, August 23, 2013

Controlled Environment

You are building a library of some sort, and you want to have a primary class with additional "extender" classes which all should be accessed through your primary one. Why? Don't know, hopefully you do since your the one making it. However, what is to stop anyone from accessing your "extender" classes directly? You could add your "extender" classes as sub-classes to the primary and make your constructors private or protected. But if your planing on expanding this library a great deal, you will end up with a pretty large file at the end. And splitting your "extender" classes into single files with private and protected constructors will just ensure that not even your primary class will be able to create instances of them. So what's left? I know that some languages actually has a feature which allows you to lock a class and define whom has access to create an instance. I have not worked with Java for long, so I don't know whether or not this feature exists in Java. But there are other ways of doing this, which will actually work in other OOP capable languages as well.

The trick here is Data Types. This is something that Java is very strict about, which makes this so much easier. What you need to do, is have a small class that only your primary can create an instance from. The easiest way is to place this as a sub-class to the primary class. This small class will be used to parse along as an argument to a static method in each "extender" class, who’s job is to return an instance of themselves. Meanwhile we will keep each "extender" constructor private, so that no other can access it. And we will make each class final, so that they cannot be extended in order to bypass this protection.

This is our primary class:
public final class MyPrimary {
    public MyExtender extender(String param) {
        MyTransport transport = new MyTransport();
        transport.arguments = new Object[] { (Object) param };

        return (MyExtender) MyExtender.getInstance( transport ).instance;
    }

    public final static interface MyDataType {}

    public final static class MyTransport {
        private MyTransport() {}

        Object[] arguments;
        MyDataType instance;
    }
}

This is one of our extenders:
public final class MyExtender implements MyDataType {
    public static MyTransport getInstance(MyTransport transport) {
        transport.instance = (MyDataType) new MyExtender( (String) transport.arguments[0] );

        return transport;
    }

    private MyExtender(String param) {
        ...
    }
}

In order to get an instance from MyExtender, you will need to parse through it's getInstance method. However, this method requires a MyTransport argument, which only the primary class can create. From the getInstance method, it will attach an instance of itself and then return the MyTransport object to the primary class. And by implementing MyDataType, you can use the same MyTransport class for any extender classes as they will all be able to be casted to the same data type.

That is all that there is to it. And like mentioned above, this can be used in any OOP language. In some however, you will need some manual checking of data types. PHP for an example does not really care about data types, so you will need to do a manual instanceOf check in the extender getInstance methods to make sure that the argument really is a MyTransport object. But that is not all that difficult to implement.

Saturday, July 13, 2013

Add missing Android Activity tools

One major issue with Android, is that Google have never implemented a proper way of detecting which Activity is currently in the foreground and which are behind. If you open multiple Activities in an application, and then flip the screen, all the callbacks (onCreate(), onResume() etc) will be invoked in all your Activities. The problem is that you might have some code in some of these Activities that you do not wish to have executed, unless the Activity holding that code, is currently placed in the foreground. Problem is that you can't check this state of an Activity. At least not in a proper way.

public Boolean isForeground() {
    ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
}

There is the possibility to use something like the above. There is just two issues regarding this. For one, google states that getSystemService(Context.ACTIVITY_SERVICE) is only intended for debugging and presenting task management user interfaces, and that it should never be used for core logic in an application. Second, you need to have android.permission.GET_TASKS added to the application in order to use this, which is not ideal for a simple task like this.

So what we can do instead, is extending the Activity class with a custom one which includes this missing feature and then extend our application Activities with our custom one instead.

public class ExtendedActivity extends Activity {
 
 private final static ArrayList mActivities = new ArrayList();
 
 private final static Object oLock = new Object();
 
 private Boolean mReCreate = false;
 
 @Override
 public void onSaveInstanceState(Bundle savedInstanceState) {
  savedInstanceState.putBoolean("mReCreate", true);

  super.onSaveInstanceState(savedInstanceState);
 }
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  
  if (savedInstanceState != null) {
   mReCreate = savedInstanceState.getBoolean("mReCreate");
  }
  
  synchronized (oLock) {
   mActivities.add( (mReCreate ? mActivities.size() : 0), this.getClass().getName());
  }
 }
 
 @Override
 protected void onDestroy() {
  super.onDestroy();
  
  synchronized (oLock) {
   mActivities.remove(this.getClass().getName());
  }
 }
 
 public final Boolean isForeground() {
  synchronized (oLock) {
   return mActivities.size() == 0 || mActivities.get(0).equals(this.getClass().getName());
  }
 }
}

What this does, it keep track of all active Activities and in which order they where opened. We only need to extend all of our Activities using this one, and then we can use isForeground() to check the state of an Activity Object.

public class MyActivity extends ExtendedActivity {

 @Override
 protected void onResume() {
  super.onResume();
  
  if ( isForeground() ) {
            // Do something
        }
 }
}

Sunday, June 30, 2013

Android Activity in Dialog Style

I was working on an Application where I had created a custom settings Activity (Not using the Android built-in settings tools), in order to adopt the same layout style as in the rest of the Application. It worked fine, and now I wanted to add some additional tablet styles as well. When using the Application on a tablet, I wanted a more dialog like view, something without a panel and did not take up the whole screen, but instead placed itself on top of the main activity. When searching the web for a solution to this, the only thing that I could find over and over again, was to add the Dialog Theme to the Activity via AndroidManifest.xml. I had two issues with this. For one, I did not want a Dialog like Activity for all devices, but only for tablets. And second, I have my own custom themes that I apply to all Activities. So I went another way which I was sure would work.

public class ActivityAppSettings extends Activity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  if (getApplication() != null && ((ApplicationBase) getApplication()).mTheme > 0) {
   setTheme( ((ApplicationBase) getApplication()).mTheme );
  }
  
  super.onCreate(savedInstanceState);
  
  if (getResources().getString(R.string.config_screen_type).equals("xlarge")) {
   requestWindowFeature(Window.FEATURE_NO_TITLE);
  
   Rect display = new Rect();
   getWindow().getDecorView().getWindowVisibleDisplayFrame(display);
   getWindow().setBackgroundDrawable(new ColorDrawable(0));

   getWindow().setLayout(
     (int) ((display.width() > display.height() ? display.height() : display.width()) * 0.7), 
     (int) (display.height() * 0.7)
   );
  }
  
  setContentView(R.layout.activity_app_settings);
 }
}

Sure enough it worked, but with one little issue. The space around the Activity was not transparent. It seamed that you could not change the window background from within the Activity. The panel however was removed, the size was set at 70% of the screen size and my custom theme had been applied to the content within, but with a black background surrounding it all.

I needed another work-around. I went to AndroidManifest.xml and applied Androids's Translucent theme to the Activity.

<activity android:theme="@android:style/Theme.Translucent"

The Activity theme would still be replaced by my Custom theme from within the Activity, but since you cannot change the window background from within there, the transparency would still stick. And then on Phones, you just apply a background to the main View, which you then configure as match_parent for both height and width, which will overlay the transparent window background, making it seam like a regular full-screen Activity.