List of all Iphone and Blackberry Development codes in a one click Iphone,objective C,xcode,blackberry Development,iOS Development

Thursday, July 26, 2012

Gauge Field in Blackberry(Like download status bar)

The following code will display a Download status Bar like Gauge field in Blackberry.




GaugeField gField;
 gField = new CustomGaugeField();
add(gField);
startProgressTimer();

private void startProgressTimer() {
       ttask = new TimerTask() {
            public void run() {
                Field f;
                for (int i = 0; i < getFieldCount(); i++) {
                    f = getField(i);
                    if (f instanceof CustomGaugeField) {
                        final CustomGaugeField gField = (CustomGaugeField) f;
                        final int increment = (i + 1) * 2;
                     
                        UiApplication.getUiApplication().invokeLater(
                            new Runnable() {
                                public void run() {
                                     
                                    if(gField.getValue()>=100)
                                    {
                                    ttask.cancel();
                                    //Implement your action here
                                    }
                                    else{
                                    gField.setValue((gField.getValue() + increment) % 101);
                                    }
                                   
                                }
                            }
                        );
                    }
                       
                }

            }
        };

        Timer ttimer = new Timer();
        ttimer.schedule(ttask, 1000, 300);
    }

//custom Gauge Field Class

import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.component.GaugeField;

class CustomGaugeField extends GaugeField {
    // Default constructor, need improvement
    public CustomGaugeField() {
        super("", 0, 100, 0, GaugeField.PERCENT);
    }

    // Colors
    private static final int BG_COLOR = 0xd6d7d6;
    private static final int BAR_COLOR = 0x63cb52;
    private static final int FONT_COLOR = 0x5a55c6;

    protected void paint(Graphics graphics) {
        int xProgress = (int) ((getWidth() / 100.0) * getValue());
        int xProgressInv = getWidth() - xProgress;

        // draw background
        graphics.setBackgroundColor(BG_COLOR);
        graphics.clear();

        // draw progress bar
        graphics.setColor(BAR_COLOR);
      
        graphics.fillRect(0, 0, xProgress, getHeight());//left to right
        //graphics.fillRect(xProgressInv, 0, xProgress, getHeight());//right to left

        // draw progress indicator text
        String text = getValue() + "%";
        Font font = graphics.getFont();
        int xText = (getWidth() - font.getAdvance(text)) / 2;
        int yText = (getHeight() - font.getHeight()) / 2;
        graphics.setColor(FONT_COLOR);
        graphics.drawText(text, xText, yText);
    }
   
    protected void layout(int width, int height) {
        super.layout(width, height);
        setExtent (width, 15);
        }
}


        

Tuesday, July 24, 2012

Push Notification in Blackberry

The BlackBerry Push Service is an essential component of the real-time, always-on experience of BlackBerry smartphones. It offers an efficient and reliable way of sending information to your users. It also lets your application process information in the background and notify users when their attention is required.

Refer this - developer.blackberry.com
First register for push Credentials.  (See the above link).
Use Alternate Entry Point Application. The Background app will listen for the push notifications. The UI Application is used to register the device for getting the push notification. You need to activate the BIS(Blackberry Internet Service) on your device.

Client app will be given upon requests (rincethomas33@gmail.com)

Client side code -

// Main Class-
class App extends UiApplication {
 private static App theApp;
  public App() {
       pushScreen(new register());    
    }

  public static void main(String[] args) {
          if (args.length > 0 && args[0].equals("push_msg") ){
             theApp = new App();
             theApp.enterEventDispatcher();   
       
            }
        else {      
            BackgroundApplication backApp=new BackgroundApplication();
            backApp.setupBackgroundApplication();
            backApp.enterEventDispatcher();
          
       }       
    }  
}

//Register Class-
public class register extends MainScreen{
    public register(){
    final ButtonField btn=new ButtonField("Register");
        add(btn);
     FieldChangeListener listener=new FieldChangeListener() {
                   public void fieldChanged(Field field, int context) {
                      
                       if(field==btn){
                          
                         registerBpas();
                          
                       }
                  
                   }};
        btn.setChangeListener(listener);
       
    }
}


public static void registerBpas() {

    new Thread() {
        public void run() {
            try {
                final String registerUrl = formRegisterRequest(BPAS_URL, APP_ID, null) + ";deviceside=false;ConnectionType=mds-public";
                System.out.println("\n\n\n msg registerBPAS URL is:  "+ registerUrl);
                HttpConnection httpConnection = (HttpConnection) Connector.open(registerUrl);
                InputStream is = httpConnection.openInputStream();
                String response = new String(IOUtilities.streamToBytes(is));
                System.out.println("\n\n\n\n\n\n msg RESPOSE CODE :    " + response);
                httpConnection.close();
                String nextUrl = formRegisterRequest(BPAS_URL, APP_ID, response) + ";deviceside=false;ConnectionType=mds-public";
                System.out.println("\n\n\n\n\n\n msg nextUrl :    " + nextUrl);
                HttpConnection nextHttpConnection = (HttpConnection) Connector.open(nextUrl);
                InputStream nextInputStream = nextHttpConnection.openInputStream();
                response = new String(IOUtilities.streamToBytes(nextInputStream));
                System.out.println("\n\n\n\n\n\n msg RESPOSE CODE 1:    " + response);
                nextHttpConnection.close();
                if (REGISTER_SUCCESSFUL.equals(response) || USER_ALREADY_SUBSCRIBED.equals(response)) {
                    Dialog.alert("msg Registered successfully for BIS push");
                   
                   
                    System.out.println("msg Registered successfully for BIS push");
                } else {
                    Dialog.alert("msg BPAS rejected registration");
                    System.out.println("msg BPAS rejected registration");
                }
            } catch (final IOException e) {
                Dialog.alert("msg IOException on register() " + e + " " + e.getMessage());
                System.out.println("msg IOException on register() " + e + " " + e.getMessage());
            }
        }
    }.start();
}

private static String formRegisterRequest(String bpasUrl, String appId, String token) {
    StringBuffer sb = new StringBuffer(bpasUrl);
    sb.append("/mss/PD_subReg?");
    sb.append("serviceid=").append(appId);
    sb.append("&osversion=").append(DeviceInfo.getSoftwareVersion());
    sb.append("&model=").append(DeviceInfo.getDeviceName());
    if (token != null && token.length() > 0) {
        sb.append("&").append(token);
    }
    return sb.toString();
}
}

public static void close(Connection conn, InputStream is, OutputStream os) {
    if (os != null) {
        try {
            os.close();
        } catch (IOException e) {
        }
    }
    if (is != null) {
        try {
            is.close();
        } catch (IOException e) {
        }
    }
    if (conn != null) {
        try {
            conn.close();
        } catch (IOException e) {
        }
    }
}

//Background listener class

class BackgroundApplication extends Application {  
   
    public BackgroundApplication() {
        // TODO Auto-generated constructor stub
    }
    public void setupBackgroundApplication(){
       
        MessageReadingThread messageReadingThread = new MessageReadingThread();
        messageReadingThread.start();
       
    }  
   
    private static class MessageReadingThread extends Thread { private boolean running;
        private ServerSocketConnection socket;
        private HttpServerConnection conn;
        private InputStream inputStream;
        private PushInputStream pushInputStream;

        public MessageReadingThread() {
            this.running = true;
        }

        public void run() {
           
             String url = "http://:" + Port;
             url += ";deviceside=false;ConnectionType=mds-public";
             if ((WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) && RadioInfo.areWAFsSupported(RadioInfo.WAF_WLAN)) {
                 url += ";interface=wifi";
                 }
           
            try {
                socket = (ServerSocketConnection) Connector.open( url );
            } catch( IOException ex ) {
                // can't open the port, probably taken by another application
                onListenError( ex );
            }

            while( running ) {
                try {
                    Object o = socket.acceptAndOpen();
                    conn = (HttpServerConnection) o;
                    inputStream = conn.openInputStream();
                    pushInputStream = new MDSPushInputStream( conn, inputStream );
                    PushMessageReader.process( pushInputStream, conn );
                } catch( Exception e ) {
                    if( running ) {
                      //  Logger.warn( "Failed to read push message, caused by " + e.getMessage() );
                        running = false;
                    }
                } finally {
                   // PushUtils.close( conn, pushInputStream, null );
                }
            }

          //  Logger.log( "Stopped listening for push messages" );
        }

        public void stopRunning() {
            running = false;
            //PushUtils.close( socket, null, null );
        }

        private void onListenError( final Exception ex ) {
           // Logger.warn( "Failed to open port, caused by " + ex );
          System.out.println(ex);
        }
    }
   
}
//push message reader class -

// HTTP header property that carries unique push message ID
    private static final String MESSAGE_ID_HEADER = "Push-Message-ID";
    // content type constant for text messages
    private static final String MESSAGE_TYPE_TEXT = "text";
    private static final int MESSAGE_ID_HISTORY_LENGTH = 10;
    private static String[] messageIdHistory = new String[MESSAGE_ID_HISTORY_LENGTH];
    private static byte historyIndex;

    private static byte[] buffer = new byte[15 * 1024];
public static void process(PushInputStream pis, Connection conn) {
        System.out.println("Reading incoming push message ...");

        try {

            HttpServerConnection httpConn;
            if (conn instanceof HttpServerConnection) {
                httpConn = (HttpServerConnection) conn;
            } else {
                throw new IllegalArgumentException("Can not process non-http pushes, expected HttpServerConnection but have "
                        + conn.getClass().getName());
            }

            String msgId = httpConn.getHeaderField(MESSAGE_ID_HEADER);
            String msgType = httpConn.getType();
            String encoding = httpConn.getEncoding();

            System.out.println("Message props: ID=" + msgId + ", Type=" + msgType + ", Encoding=" + encoding);

           
            boolean accept = true;
            if (!alreadyReceived(msgId)) {
                byte[] binaryData;

                if (msgId == null) {
                    msgId = String.valueOf(System.currentTimeMillis());
                }

                if (msgType == null) {
                    System.out.println("Message content type is NULL");
                    accept = false;
                } else if (msgType.indexOf(MESSAGE_TYPE_TEXT) >= 0) {
                    // a string
                    int size = pis.read(buffer);
                    binaryData = new byte[size];
                    System.arraycopy(buffer, 0, binaryData, 0, size);   
                   
                    PushMessage message = new PushMessage(msgId, System.currentTimeMillis(), binaryData, true, true );
                    String text = new String( message.getData(), "UTF-8" );
                     try{
                            final Dialog screen = new Dialog(Dialog.D_OK_CANCEL, " "+text,
                                    Dialog.OK,
                                    //mImageGreen.getBitmap(),
                                    null, Manager.VERTICAL_SCROLL);
                            final UiEngine ui = Ui.getUiEngine();
                            Application.getApplication().invokeAndWait(new Runnable() {
                                public void run() {
                                    NotificationsManager.triggerImmediateEvent(0x749cb23a76c66e2dL, 0, null, null);
                                    ui.pushGlobalScreen(screen, 0, UiEngine.GLOBAL_QUEUE);
                                   
                                }
                            });
                            screen.setDialogClosedListener(new MyDialogClosedListener());
                            }
                            catch (Exception e) {
                                // TODO: handle exception
                            }
                           
                   
                    // TODO report message
                }  else {
                    System.out.println("Unknown message type " + msgType);
                    accept = false;
                }
            } else {
                System.out.println("Received duplicate message with ID " + msgId);
            }
            pis.accept();
        } catch (Exception e) {
            System.out.println("Failed to process push message: " + e);
        }
    }



private static boolean alreadyReceived(String id) {
        if (id == null) {
            return false;
        }

        if (Arrays.contains(messageIdHistory, id)) {
            return true;
        }

        // new ID, append to the history (oldest element will be eliminated)
        messageIdHistory[historyIndex++] = id;
        if (historyIndex >= MESSAGE_ID_HISTORY_LENGTH) {
            historyIndex = 0;
        }
        return false;
    }



public class PushMessage{

    private String id;
    private long timestamp;
    private byte[] data;
    private boolean textMesasge;
    private boolean unread;

    public PushMessage( String id, long timestamp, byte[] data, boolean textMesasge, boolean unread ) {
        super();
        this.id = id;
        this.timestamp = timestamp;
        this.data = data;
        this.textMesasge = textMesasge;
        this.unread = unread;
    }

    public String getId() {
        return id;
    }

    public long getTimestamp() {
        return timestamp;
    }

    public byte[] getData() {
        return data;
    }

    public boolean isTextMesasge() {
        return textMesasge;
    }

    public boolean isUnread() {
        return unread;
    }

    public void setUnread( boolean unread ) {
        this.unread = unread;
    }

}

public class MyDialogClosedListener implements DialogClosedListener
    {

    public void dialogClosed(Dialog dialog, int choice)
    {
        if(dialog.equals(dialog))
        {
           if(choice == -1)
            {
                //Your code for Press OK
            }
            if(choice == 1)
            {
                //Your code for Press Cancel
               
            }
                   }
   }
}

For setting alternate entry point - Refer below images -


Server sode PHP code is given Below -

//
ini_set('display_errors','1');
error_reporting(E_ALL);

    // APP ID provided by RIM
$appid = 'app id';
// Password provided by RIM
$password = 'password';
//Deliver before timestamp
$deliverbefore = gmdate('Y-m-d\TH:i:s\Z', strtotime('+time minutes'));

//An array of address must be in PIN format or "push_all"
$addresstosendto[] = 'your pin';

$addresses = '';
foreach ($addresstosendto as $value) {
$addresses .= '
';
}

// create a new cURL resource
$err = false;
$ch = curl_init();
$messageid = microtime(true);

$data = '--mPsbVQo0a68eIL3OAxnm'. "\r\n" .
'Content-Type: application/xml; charset=UTF-8' . "\r\n\r\n" .
'
'
. $addresses .
'
' . "\r\n" .
'--mPsbVQo0a68eIL3OAxnm' . "\r\n" .
'Content-Type: text/plain' . "\r\n" .
'Push-Message-ID: ' . $messageid . "\r\n\r\n" .
stripslashes('r') . "\r\n" .
'--mPsbVQo0a68eIL3OAxnm--' . "\n\r";

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "https://pushapi.eval.blackberry.com/mss/PD_pushRequest");//"https://cp2991.pushapi.eval.blackberry.com/mss/PD_pushRequest"
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_USERAGENT, "Hallgren Networks BB Push Server/1.0");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $appid . ':' . $password);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: multipart/related; boundary=mPsbVQo0a68eIL3OAxnm; type=application/xml", "Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2", "Connection: keep-alive"));

// grab URL and pass it to the browser
echo $xmldata = curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);

//Start parsing response into XML data that we can read and output
$p = xml_parser_create();
xml_parse_into_struct($p, $xmldata, $vals);
$errorcode = xml_get_error_code($p);
if ($errorcode > 0) {
echo xml_error_string($errorcode);
$err = true;
}
xml_parser_free($p);

echo 'Our PUSH-ID: ' . $messageid . "
\n";
if (!$err && $vals[1]['tag'] == 'PUSH-RESPONSE') {
echo 'PUSH-ID: ' . $vals[1]['attributes']['PUSH-ID'] . "
\n";
echo 'REPLY-TIME: ' . $vals[1]['attributes']['REPLY-TIME'] . "
\n";
echo 'Response CODE: ' . $vals[2]['attributes']['CODE'] . "
\n";
echo 'Response DESC: ' . $vals[2]['attributes']['DESC'] . "
\n";
} else {
echo 'An error has occured
' . "\n";
echo 'Error CODE: ' . $vals[1]['attributes']['CODE'] . "
\n";
echo 'Error DESC: ' . $vals[1]['attributes']['DESC'] . "
\n";
}

?>



OR Server sode C# code is given Below -

private void pushMessageSample(string pushedMessage)
    {
        String appid="xxxx-xxxxxxxxxxxxxxxxxxxxxxxxxx";
        String password = "xxxxxx";
        String deliverbefore = DateTime.UtcNow.AddMinutes(5).ToString("s",System.Globalization.CultureInfo.InvariantCulture) + "Z";
        String pushPin = "xxxxxxxx";
        String Boundary = "mPsbVQo0a68eIL3OAxnm";

 StringBuilder dataToSend = new StringBuilder();

 dataToSend.AppendLine("--" + Boundary);
 dataToSend.AppendLine("Content-Type: application/xml; charset=UTF-8");

 dataToSend.AppendLine("");
 dataToSend.AppendLine("");
 dataToSend.AppendLine("");
 dataToSend.AppendLine("");
 string myPushId = DateTime.Now.ToFileTime().ToString();
 dataToSend.AppendLine("");
 //dataToSend.AppendLine("");
 dataToSend.AppendLine("

");
 dataToSend.AppendLine("");
 dataToSend.AppendLine("
");
 dataToSend.AppendLine("");
 dataToSend.AppendLine("--" + Boundary);

 dataToSend.AppendLine("Content-Type: text/plain");
 dataToSend.AppendLine("Push-Message-ID: " + myPushId);
 dataToSend.AppendLine("");

 dataToSend.AppendLine(pushedMessage);

 dataToSend.AppendLine("--" + Boundary + "--");
 dataToSend.AppendLine("");

 byte[] bytes = Encoding.ASCII.GetBytes(dataToSend.ToString());
        String httpURL = "https://cpxxxx.pushapi.eval.blackberry.com/mss/PD_pushRequest";

            WebRequest tRequest;
            tRequest = WebRequest.Create(httpURL);
            //SetProxy(tRequest);
            tRequest.Method = "POST";
            //tRequest.ContentType = "text/plain";

            //tRequest.ContentLength = bytes.Length;
            tRequest.Credentials = new NetworkCredential(appid, password);

            tRequest.PreAuthenticate = true;
            tRequest.ContentType = "multipart/related; boundary=" + Boundary + "; type=application/xml";
            tRequest.ContentLength = bytes.Length;
            string rawCredentials = string.Format("{0}:{1}", appid, password);
            tRequest.Headers.Add("Authorization",
                string.Format(
                    "Basic {0}",
                    Convert.ToBase64String(Encoding.UTF8.GetBytes(rawCredentials))));

            SetBasicAuthHeader(tRequest, appid, password);

            Stream dataStream = tRequest.GetRequestStream();
            dataStream.Write(bytes, 0, bytes.Length);
            dataStream.Close();

            WebResponse tResponse = tRequest.GetResponse();

            dataStream = tResponse.GetResponseStream();

            StreamReader tReader = new StreamReader(dataStream);

            String sResponseFromServer = tReader.ReadToEnd();

            tReader.Close();
            dataStream.Close();
            tResponse.Close();
    }

public static void SetBasicAuthHeader(WebRequest req, String appID, String userPassword)
    {
        string authInfo = appID + ":" + userPassword;
        authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
        req.Headers["Authorization"] = "Basic " + authInfo;
    }