Samsung Mobile SDK Tutorial 2

Samsung Mobile SDK TutorialWelcome to part 2 of my Samsung Mobile SDK Tutorial! In this part I will completely finish explaining every line of code for our app.

We’ll cover how to handle all the potential problems SsdkUnsupportedException can catch and we’ll handle each one. We’ll create custom alert dialogs. We’ll send the user to the app store to download an update and so much more. Most everything in this tutorial applies to any app you can make while also teaching about the Samsung Mobile SDK.

If you like videos like this, it helps to tell Google+ with a click here

Don’t forget to check out the Samsung Smart App Challenge and if it is still November 2013, don’t forget to sign up to win a Samsung Galaxy Note 3, or Samsung Galaxy Gear Smart Watch on my site.

Code From the Video

package com.samsung.android.sdk.pen.pg.example1_1;

import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.view.Display;
import android.widget.RelativeLayout;
import android.widget.Toast;

// Used to make sure the device supports the Samsung Mobile SDK
import com.samsung.android.sdk.SsdkUnsupportedException;

// Initializes and verifies that the S Pen is available
import com.samsung.android.sdk.pen.Spen;

// Allows you to manage SPD (S Pen Data Files)
// Loads and saves SPD files
// Adds and removes PageDocs from NoteDocs and attaches external files
import com.samsung.android.sdk.pen.document.SpenNoteDoc;

// Contains all the data and objects in a page
// Adds, deletes, retrieves and changes layers, objects and general
// settings for the page document.
import com.samsung.android.sdk.pen.document.SpenPageDoc;

// Allows for editing of the drawing surface with both a finger or the SPen
import com.samsung.android.sdk.pen.engine.SpenSurfaceView;
import com.samsung.spensdk3.example.R;

public class PenSample1_1_HelloPen extends Activity {

	// A Context provides access to application resources
	// Launch activities, receiving Intents, managing sound,
	// Bluetooth management, modifying the clipboard,
	// requests downloads, interacting with input methods,
	// retrieve LayoutInflator, file creation, and retrieving a 
	// NfcManager, MsdManager for network service 
	// discovery, SearchManager, SensorManager, 
	// StorageManager, TelephonyManager, TextServicesManager,
	// UsbManager, Vibrator, WifiP2pManager (peer to peerWiFi),
	// WifiManager and WindowManager
    private Context mContext;
    
    private SpenNoteDoc mSpenNoteDoc;
    private SpenPageDoc mSpenPageDoc;
    private SpenSurfaceView mSpenSurfaceView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hello_pen);
        mContext = this;

        boolean isSpenFeatureEnabled = false;
        
        // Create an SPen object
        Spen spenPackage = new Spen();
        
        // Try to initialize the Spen and if it doesn't exist
        // trigger an exception that is handled below
        try {
            spenPackage.initialize(this);
            
            // Is the SPen available for use
            isSpenFeatureEnabled = spenPackage.isFeatureEnabled(Spen.DEVICE_PEN);
        } catch (SsdkUnsupportedException e) {
            if( processUnsupportedException(e) == true) {
                return;
            }
        } catch (Exception e1) {
        	
        	// A Toast is a little message that opens in a gray
        	// box in the bottom of the screen
        	// Pass it the Context, message and how long to display
        	// the message
            Toast.makeText(mContext, "Cannot initialize Spen.",
                Toast.LENGTH_SHORT).show();
            e1.printStackTrace();
            
            // Drop the Activity from memory
            finish();
        }

        // Initialize the RelativeLayout in activity_hello_pen.xml
        RelativeLayout spenViewLayout =
            (RelativeLayout) findViewById(R.id.spenViewLayout);
        
        // Create the drawing surface on the device
        mSpenSurfaceView = new SpenSurfaceView(mContext);
        
        // Check if the SPen surface was created and if not display Toast
        // error message
        if (mSpenSurfaceView == null) {
            Toast.makeText(mContext, "Cannot create new SpenView.",
                Toast.LENGTH_SHORT).show();
            finish();
        }
        
        // Insert the drawing surface into the relative layout
        spenViewLayout.addView(mSpenSurfaceView);

        // Display provides information on the display
        // Information about the size, density, orientation
        // refresh rate
        Display display = getWindowManager().getDefaultDisplay();
        
        // Holds 4 integer coordinates for a rectangle
        // bottom, left, right, top
        Rect rect = new Rect();
        
        // Get the size of the display as a Rect in pixels
        display.getRectSize(rect);
        

        try {
        	
        	// Create a SpenNoteDoc by passing the Context and the 
        	// width and height
            mSpenNoteDoc =
                new SpenNoteDoc(mContext, rect.width(), rect.height());
        } catch (IOException e) {
            Toast.makeText(mContext, "Cannot create new NoteDoc.",
                Toast.LENGTH_SHORT).show();
            e.printStackTrace();
            finish();
        } catch (Exception e) {
            e.printStackTrace();
            finish();
        }
        
        // Adds a page to the document
        mSpenPageDoc = mSpenNoteDoc.appendPage();
        
        // Changes the background color
        mSpenPageDoc.setBackgroundColor(0xFFD6E6F5);
        
        // Clear undo / redo history
        mSpenPageDoc.clearHistory();
        
        // Put the Spen document in the current view
        // and pass true to update the screen
        mSpenSurfaceView.setPageDoc(mSpenPageDoc, true);

        // Check if the Spen is available or not
        if(isSpenFeatureEnabled == false) {
        	
        	// Set the type of tool to recognize as the finger
        	// and for the finger to be able to draw on the screen
            mSpenSurfaceView.setToolTypeAction(SpenSurfaceView.TOOL_FINGER,
                SpenSurfaceView.ACTION_STROKE);
            Toast.makeText(mContext,
                "Device does not support Spen. \n You can draw stroke by finger",
                Toast.LENGTH_SHORT).show();
        }
    }

    // You get here if the device isn't a Samsung device, or
    // if the mobile SDK doesn't work with this device
    private boolean processUnsupportedException(SsdkUnsupportedException e) {
        
        e.printStackTrace();
        int errType = e.getType();
        
        // Is this a Samsung device?
        if (errType == SsdkUnsupportedException.VENDOR_NOT_SUPPORTED
                || errType == SsdkUnsupportedException.DEVICE_NOT_SUPPORTED) {
            Toast.makeText(mContext, "This device does not support Spen.",
                    Toast.LENGTH_SHORT).show();
            finish();
        }
        
        // Is the SDK library installed?
        else if (errType == SsdkUnsupportedException.LIBRARY_NOT_INSTALLED) {
            

            showAlertDialog( "You need to install additional Spen software"
                +" to use this application."
                + "You will be taken to the installation screen."
                + "Restart this application after the software has been installed."
                , true);
        } 
        
        // If the SDK library is installed, but it is out of date
        else if (errType
                == SsdkUnsupportedException.LIBRARY_UPDATE_IS_REQUIRED) {
            

            showAlertDialog( "You need to update your Spen software "
                + "to use this application."
                + " You will be taken to the installation screen."
                + " Restart this application after the software has been updated."
                , true);
        } 
        
        // It is recommended, but not required that the user updates
        // the SDK library
        else if (errType
                == SsdkUnsupportedException.LIBRARY_UPDATE_IS_RECOMMENDED) {
            

            showAlertDialog( "We recommend that you update your Spen software" 
                +" before using this application."
                + " You will be taken to the installation screen."
                + " Restart this application after the software has been updated."
                , false);
            return false;
        }
        return true;
    }

    private void showAlertDialog(String msg, final boolean closeActivity) {

    	// Create a dialog box
        AlertDialog.Builder dlg = new AlertDialog.Builder(mContext);
        
        // Set the icon to display in the title
        // Use ic_dialog_alert which is a default Android icon
        dlg.setIcon(getResources().getDrawable(
            android.R.drawable.ic_dialog_alert));
        
        // Change the title of the dialog
        dlg.setTitle("Upgrade Notification")
            .setMessage(msg) // Message to display in the dialog
            // Handle the event when the button is pressed
            .setPositiveButton(android.R.string.yes,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(
                        DialogInterface dialog, int which) {
                        
                    	// Create a Uniform Resource Identifier
                    	// to the missing software on Google Play
                        Uri uri = Uri.parse("market://details?id="
                                + Spen.SPEN_NATIVE_PACKAGE_NAME);
                        
                        // Create an Intent which is an operation
                        // you will perform
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        
                        // Set flags that define how the Intent is handled
                        // A new task is being started
                        // Close the current task / application before
                        // the new activity is started
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                            | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        
                        // Open Google Play and the Mobile SDK app
                        startActivity(intent);

                        // Close the dialog box
                        dialog.dismiss();
                        finish();
                    }
                })
                // If they hit the negative button
            .setNegativeButton(android.R.string.no,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(
                        DialogInterface dialog, int which) {
                        
                    	// Check the value of closeActivity 
                    	// that was sent to showAlertDialog
                    	if(closeActivity == true) {
                            

                            finish();
                        }
                    	
                    	// Close the dialog box
                        dialog.dismiss();
                    }
            })
            // If they hit the cancel button
            .setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    if(closeActivity == true) {
                        

                        finish();
                    }
                }
            })
            // Display the dialog box
            .show();
        dlg = null;
    }
    
    // The app is being shutdown and all resources will be lost
    @Override
    protected void onDestroy() {
        super.onDestroy();

        // Close the SpenSurfaceView
        if(mSpenSurfaceView != null) {
            mSpenSurfaceView.close();
            mSpenSurfaceView = null;
        }

        // Close the SpenNoteDoc
        if(mSpenNoteDoc != null) {
            try {
                mSpenNoteDoc.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            mSpenNoteDoc = null;
        }
    };
}

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/spenViewLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".PenSample1_1_HelloPen" >
</RelativeLayout>

Information on my Contest

The Requirements for Entering the Samsung Smart App Challenge can be found here : http://developer.samsung.com/ssac2013/note/main.do

I’m very excited to provide you with my Samsung Mobile SDK Tutorial! Over the next few videos I cover: the Samsung Mobile SDK.

Thanks to the nice people at Samsung and the Samsung Smart App Challenge, who are giving away $1.1 Million in prizes.

I’ll also be offering a give away. Between now and November the 30th, sign up for a free Samsung developer account at http://developer.samsung.com/signup and you will be eligible to win a Samsung GALAXY Note 3 device or one of three Samsung GALAXY Gear smart watches. I will choose a winner at random.

After you signup for the Samsung developer account, leave a comment on my website stating that you signed up. That is all!

23 Responses to “Samsung Mobile SDK Tutorial 2”

  1. Israel ClavΓ© says:

    Hey Derek! I signed up for the Samsung developer account. I will keep my fingers crossed. =)

  2. Preston Yuen says:

    Hi Derek,

    You have great tutorial videos! I don’t know why Microsoft or Apple hasn’t hired brilliant people like you yet πŸ˜›

    I don’t know if you remember me, but you’ve helped me out with recursion in Java, and I appreciate it. I know that you have done tutorials on the C language and is very similar to C++, but I was hoping that you would be able to create a few tutorials for it as well.

    I also know you’re a busy man with creating many other video tutorials for other topics, and I (and probably others) am not in a big rush for tutorials in C++. However, it’ll be nice to see how games are programed in C++ and would like to see how you would program some simple games. I’ve already equipped myself with many C++, game coding, game engine, and related books and am ready to work my way through them. It would be nice to see other creative work developed by brilliant people such as yourself.

    I hope this works out for you after you’ve completed your other recent helpful video tutorials such as this one!

    • Derek Banas says:

      Hi Preston,

      Yes I remember you. I plan to finish the C tutorial soon. I’ll then probably run a C++ tutorial at the same time I continue making Android tutorials. I’ll devote about 6 months to making Android tutorials. I see so many opportunities in Android app development so I’m dedicating a lot of time to teaching it. I may reboot the Android tutorial actually and teach in a new way because I’ve learned a lot about what people struggle with since I started this.

      I worked for Apple many many years ago, but I don’t work well in a corporate atmosphere. I’m much happier being a consultant. Thanks for stopping back πŸ™‚

  3. sagar says:

    i have singed up for samsung sdk derek….

  4. Maciej Szpakowski says:

    Hi, Derek I just signed up for the Samsung developer account. I love your tutorials !!! I realy would like to win this awesome smartphone.

  5. Mateusz says:

    Hi Derek! Thx for all the tutorials! All the Java stuff is just great… and I’m hopeing for a PHP extansion tutorial in C. Oh! I signed up Samsung Developer Account. Samsung SDK sounds like fun πŸ˜‰

  6. Nishant says:

    You are the Best Teacher ever πŸ˜€ .
    How to generate random Questions from database?
    (i am making a quiz site for my college)
    i have made interface using HTML and CSS
    please Help.
    Thanks in advance πŸ˜€

  7. Rex David says:

    Hello Again! Derek,

    As always awesome videos πŸ™‚ I’ve signed up for the Samsung dev account. I’m a big fan of Samsung note phones. My current phone is Note 2 (it’s rooted & its awesome) πŸ˜€

    I Would love to own a note 3, so please put me in the contest. In the words of J.Green -Don’t forget to be Awesome.. Take care

    -Rex David

  8. Rex David says:

    Hey Derek,

    Have a dumb question. This is from your android video 21. In the FragmentContactList.Java , you’ve used
    contactList = AllContacts.get(getActivity()).getContactList(), my question is why do we have to use ‘getActivity()’ in this statement?

  9. nishant says:

    How to generate random questions from database???
    pls help make a tutorial….
    Thanks πŸ™‚

  10. nishant says:

    yeahh got this.Can you please make a Tutorial on it.
    (there a sites such as QuizBuilder,moodle quiz they help us to make quiz.But suppose you make a Quiz on it how can you link it to your website… Moreover you built a quiz on it you have to make student to go on their website which is not what i want.If you have any other altenative pls suggest.)
    Thank You πŸ™‚

  11. Steve says:

    Hi Derek,
    Thanks for your great tutorials but do you have a tutorial where you make a menu for a game with settings credits etc.?

    Thanks

    • Derek Banas says:

      Hi Steve, I have 3 videos waiting to be approved by Samsung. They cover how to make a ListActivity and then call other classes from it. It is pretty much exactly what you asked for. It will be out in the next few days.

  12. Mathijs says:

    Hi derek,

    i just singed up for samsung sdk. love your vids πŸ˜‰

  13. Paul says:

    Hi, I signed up for a samsung developers acount. Do all your Samsung related Videos need a aproval of Samsung? and have they ever turned one of your videos down?

    -Paul

    • Derek Banas says:

      Hi Paul, Yes they are all approved by Samsung. No they have never turned down anything I sent to them. I was only supposed to do 4 videos originally, but I wanted to cover everything I found interesting in the Samsung Mobile SDK.

      Good luck in the contest πŸ™‚

Leave a Reply

Your email address will not be published.

Google+