Monday, November 5, 2012

Android - GCM Sample

Hello


Following is a code sample for using GCM.
Client is android application.
Server is based on ASP.Net.

The sample is very naive and hard code is used:

  • The android app is invoked ,  GCMRegister performs registration if needed and regId is saved and used on the server as  strDeviceRegistrationId 
  • The ASP.Net is invoked, it use strDeviceRegistrationId  and GoogleApiKey , to send a message to this particular device
  • The android device "catch" this message via GCMBaseIntentService.onMessage


Client registration

GCMRegister

Important methods :
  • register
  • unregister
  • getRegistrationId

This code register for GCM and the device registration ID is retrived - regId

 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        try {
   GCMRegistrar.checkDevice(this);
   GCMRegistrar.checkManifest(this);
   final String regId = GCMRegistrar.getRegistrationId(this);
   if (regId.equals("")) {
     GCMRegistrar.register(this, Constants.SENDER_ID);
   } else {
     Log.v("TAG", "Already registered");
   }
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
        
    }     



GCMBaseIntentService

Important methods :

  • onError
  • onMessage
  • onRegistered
  • onUnregistered

Most important method is onMessage. the message is read via  intent.getStringExtra("message");

public class GCMIntentService extends GCMBaseIntentService{

 @Override
 protected void onError(Context arg0, String arg1) {
  
   //Called on registration or unregistration error.
  Log.v("TAG", "GCMIntentService onError");
 }

 @Override
 protected void onMessage(Context arg0, Intent intent) {
  // TODO Auto-generated method stub
  
  // ---   Called when a cloud message has been received.
  
  // --- handle here the push notification e.g. Toast Notification
  Log.v("TAG", "GCMIntentService onMessage");
  String message = intent.getStringExtra("message");
 }

 @Override
 protected void onRegistered(Context arg0, String arg1) {
  // TODO Auto-generated method stub
  
  // --- Called after a device has been registered. 
  
  Log.v("TAG", "GCMIntentService Registered");
 }

 @Override
 protected void onUnregistered(Context arg0, String arg1) {
  // TODO Auto-generated method stub
  
    // Called after a device has been unregistered.
  Log.v("TAG", "GCMIntentService UnRegistered");
 }

}



ASP.Net Server

The server uses :




PushNotification.cs
public class AndroidGCMPushNotification
{
    
    public string SendNotification(string deviceId, string message)
    {
        var value = message;
        WebRequest tRequest;
        tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
        tRequest.Method = "post";

        // --- text
        tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
        string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message="
            + value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + deviceId + "";

        

        tRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleApiKey));
        
        Console.WriteLine(postData);
        Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        tRequest.ContentLength = byteArray.Length;

        Stream dataStream = tRequest.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.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();
        return sResponseFromServer;
    }

    

    public string GoogleApiKey
    {
        get { return m_strGoogleAppID; }
        set { m_strGoogleAppID = value; }
    }
   

    public string SenderId
    {
        get { return m_strSenderId; }
        set { m_strSenderId = value; }
    }


    string m_strSenderId;
    string m_strGoogleAppID;
}



first.aspx
<%@ Page Language="C#" %>






Sources :


Nathan

Android - Video\Audio Sample

Hello


Following is very simple sample for playing Audio and Video using external urls

Sample code - MediaPlayerTry.zip


Basic API is the class MediaPlayer

Audio Sample
  String url = "http://vprbbc.streamguys.net/vprbbc24.mp3";
 
  mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
  try {
  mediaPlayer.setDataSource(url);
  mediaPlayer.prepare();
  mediaPlayer.start();
 } catch (IllegalArgumentException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 } catch (SecurityException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 } catch (IllegalStateException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }


remarks :

  • patient is needed for prepare
  • mediaPlayer is a member type MediaPlayer
  • the player is stopped via stop()


Video Sample

Requires VideoView
String SrcPath = "rtsp://v5.cache1.c.youtube.com/CjYLENy73wIaLQnhycnrJQ8qmRMYESARFEIJbXYtZ29vZ2xlSARSBXdhdGNoYPj_hYjnq6uUTQw=/0/0/0/video.3gp";
VideoView myVideoView = (VideoView)findViewById(R.id.myvideoview);
myVideoView.setVideoURI(Uri.parse(SrcPath));
myVideoView.setMediaController(new MediaController(this));
myVideoView.requestFocus();
myVideoView.start();

It is possible to stop the video via the VideoView widget


http://developer.android.com/guide/topics/media/mediaplayer.html

Supported Media Formats

Nathan