All Things Techie With Huge, Unstructured, Intuitive Leaps
Showing posts with label source code. Show all posts
Showing posts with label source code. Show all posts

Android Source Code - Turn Off Media Player When You Click Back Button


Android persists activities even when you don't want them unless you explicitly kill them.  Sometimes the media player persists even if you kill the first activity of the app.  If you have an activity that kicks a media player, and you want to turn that media player off from other activities, including hitting the back button, you must do the following:

1) Make the media player into a static class.  The following code should do it:

package com.me.coderzen;

import android.content.Context;
import android.media.MediaPlayer;

public class StaticPlayer {
public static MediaPlayer player;
    public static void SoundPlayer(Context ctx,int raw_id){
            player = MediaPlayer.create(ctx, raw_id);
            player.setLooping(false); 
            player.setVolume(100, 100);
        }

}

On you media player activity you kick the player:

StaticPlayer.SoundPlayer(this, R.raw.sound_file);

Then to kill it from the back button, you override the back button function:

  @Override
   public boolean onKeyDown(int keyCode, KeyEvent event) {
       if (keyCode == KeyEvent.KEYCODE_BACK ) {
      if (StaticPlayer.player != null)
      StaticPlayer.player.stop();
           this.finish();
           
       }
       return super.onKeyDown(keyCode, event);
   }

I know that there is a newer, easier back button override, but this one works in my code.

And if you have a quit button in your menu, just put the stop in for the StaticPlayer before you call the this.finish().

Hope this helps someone.

Android - Programmatically Determine if Device is a Tablet




Here is some source code to determine if the Android device is a tablet or a phone:


public boolean isTablet() { 
    try { 
        // Compute screen size 
    Context context = (put the class name of your Activity here eg MyActivity).this;
        DisplayMetrics dm = context.getResources().getDisplayMetrics()
        float screenWidth  = dm.widthPixels / dm.xdpi
        float screenHeight = dm.heightPixels / dm.ydpi
        double size = Math.sqrt(Math.pow(screenWidth, 2) + 
                                Math.pow(screenHeight, 2)); 
        // Tablet devices have a screen size greater than 6 inches 
        return size >= 6; 
    } catch(Throwable t) { 
        Log.e("Failed to compute screen size", t.toString()); 
        return false; 
    } 
}





Killing Application With Escape Key in .NET C#


So, you are a C# weenie and you want to kill your Forms Application by hitting the escape key.  It's as easy as pie.

In the forms load method, put in the following two lines:

this.KeyPreview = true;
this.KeyDown += new KeyEventHandler(Form1_KeyDown);

Then create the KeyDown method:

private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
             if (e.KeyCode == Keys.Escape)
             {
                 Application.Exit();
             }
        } 

Hope this helps.

Giving a user an anonymous ID programatically

We have a web application written in Java whereby when the users sign in, we want them to be anonymous to each other.  So what we do, is give them a number.  I needed an algorithm to generate the number from their database user id, and I wanted the algorithm to vary such that it wasn't that easy to figure out.

So what I do, is on even days of the month, the user id is added to the day of the month, and on odd month days, I take the absolute value of the day of month - the user id.


//get day of month

int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
//cast it to a double so that I can get a modulus 2 which indicates whether it is even or odd
double amem = (double) dayOfMonth;
if ((amem % 2) == 0) {       // it's an even day with no remainder
dayOfMonth = dayOfMonth + userId;
} else {
//its an odd day
dayOfMonth = Math.abs(dayOfMonth - userId);
}


Hope this helps someone.

Fuzzy Logic, "Ish" values, Java

I previously wrote about an "ish" function ( which can be read HERE ) , that describes the need for a fuzzificator that identifies things from incomplete or incorrect knowledge. Humans are excellent at doing this in some sort of neural pattern recognition. In my "ish" function article, I made the case that it was needed to crack a code that the FBI was working on and asking for the public's help.

Little did I realize that I would need an "ish" function or a fuzzy value function shortly in my work. I am writing software that processes health surveys sent by smart phone to identify persons that need immediate care in a Third World country. The way this is done, is by sending people out using a survey tool that asks questions which identifies risk signs. There are many different types of surveys, and the only way to classify what comes in over GPRS or HTTP, is the XML document with the survey answers. I parse the document, and identify the type of survey by the number of answers.

However this method is not foolproof, because the tool lets the interviewer skip an answer. At this point, my survey classifier throws an exception because it cannot determine the type of survey. However each type of survey has a significant difference in the number of answers, so a fuzzificator would work well here. For example, one particular survey has 12 answers, the next has 25 and the next has 64, so making a fuzzy logic class to determine the type of survey is quite easy. I just give the exact answer a range, and if it falls into that range, then I know what type of survey it is.

Right now, my fuzzy value function works only on integers. It works on an actual difference or a percentage difference. The values are hard coded but the code could be modified to get the values from a config file or a database.

I see this function extended to strings, doubles, floats and indeed anything you want. In addition, once you have the fuzzificator, one can make the same thing for logic types, for example Boolean algebra. One could have a fuzzy AND gate where there are many inputs, and if one or two is out, a decision still could be made. And if one combines the decision making with Bayesian inference, or probabilities, then one has a truly useful tool for complex fuzzy logic.

Here is the prototype source code in Java:


package org.FuzzyLogic;



public class FuzzyValues {
static final int PLUS_MINUS_VALUE_INT = 1;
static final double PLUS_MINUS_VALUE_INT_PERCENT = 0.09;
static final int expectedInput = 12;

public static boolean fuzzyInt(int actualInput) {
boolean fuzzy = ((expectedInput-PLUS_MINUS_VALUE_INT) <= actualInput) && (actualInput <= (expectedInput+PLUS_MINUS_VALUE_INT ));
return fuzzy;
}



public static boolean intPercentMatch(int input) {
double minus_percent_value = expectedInput * (1 + PLUS_MINUS_VALUE_INT_PERCENT);
double plus_percent_value = expectedInput * (1 - PLUS_MINUS_VALUE_INT_PERCENT);
boolean fuzzy = (minus_percent_value <= input)&& (plus_percent_value >= input);
return fuzzy;
}




public static boolean isFuzzyIntValue(int input)
{
boolean success = fuzzyInt(input);
return success;
}
public static boolean isFuzzyIntPercent(int input)
{
boolean success = intPercentMatch(input);
return success;
}

}