How do you rate this blog

Thursday, August 16, 2012

Bluetooth - Scan for devices


In this post I have created a simple application which searches for and displays a list of all the devices which have their Bluetooth turned on.
                The logic for the following is –
1)      Create a Bluetooth adapter.
2)      Create a Listview to store all the devices which have been discovered.
3)      See if the device has Bluetooth capability and turn it on if it is not enabled.
4)      Search for devices and get the names

Now lets start creating this simple application, this application requires access to the Bluetooth in the device so provide access to Bluetooth in the manifest file as shown below.

Then create the layout as shown below





The code for the same is as shown below 



Then implement the logic as described earlier,
1)      Declaring the bluetooth adapter
BluetoothAdapter BA = BluetoothAdapter.getDefaultAdapter();

2)      Creating the listview which stores all the device names in an array adapter
BTadapter=new ArrayAdapter <String>(BluetoothDemoActivity.this,android.R.layout.simple_list_item_1);

3)      Then we need to check if the device has bluetooth capability, if the device has bluetooth check if it is enabled and if it is not request the user to turn on the Bluetooth as shown in the code below

private void findBluetoothState() {
                               
                                if(BA==null){
                                                BTState.setText("Bluetooth service not available in the device");
                                }
                                else{
                                                if(BA.isEnabled()){
                                                                if(BA.isDiscovering()){
                                                                                BTState.setText("Finding Devices");
                                                                }
                                                                else{
                                                                                BTState.setText("Bluetooth is Enabled");
                                                                                BTState.setEnabled(true);
                                                                }
                                                }
                                                else{
                                                                BTState.setText("Bluetooth is not enabled");
                                                                Intent startBT=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                                                                startActivityForResult(startBT,REQUEST_ENABLE_BLUETOOTH);
                                                }
                                }
                               
                }

4)      Next search for devices and get the devices which have their bluetooth turned on.
                private final BroadcastReceiver BR=new BroadcastReceiver(){
                                @Override
                                public void onReceive(Context context, Intent intent) {
                                                String act=intent.getAction();
                                                if(BluetoothDevice.ACTION_FOUND.equals(act)){
                                                                BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                                                                BTadapter.add(device.getName()+" - "+device.getAddress());
                                                                BTadapter.notifyDataSetChanged();
                                                }
                                }
                };
The code will look as shown in the image below – 



When you start the app and it finds that the Bluetooth is not enabled then you will get a screen shot as shown below.



Once you provide permission for it to turn on the Bluetooth and click on scan for devices then you will get the list of devices along with the MAC address as shown in the image below.



Tuesday, August 7, 2012

To get Latitude and Longitude of Current Location


This post explains how to get the current location using GPS. In this post the app will display your current latitude and longitude if it can access the network.

The logic for this is -
1)      Provide the app access to GPS in the device.
2)      Get location manager, which enables the device to get periodic location updates of the device.
3)      Then select the best provider based on the criteria.
4)      Then obtain the latitude and longitude if there is a provider.

Based on the logic mentioned above lets code the application –

1)      In the android manifest file provide access to the GPS using code as shown in the snapshot given below.

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

The code will look as shown below in the snapshot



2)      Get the location manager – 

LocationManager LC=(LocationManager) getSystemService(Context.LOCATION_SERVICE);

The above code creates a location manager to get the location updates.

3)      Select the best provider based on the criteria –
Criteria criteria=new Criteria();
provider=LC.getBestProvider(criteria, false);
        Location loc=LC.getLastKnownLocation(provider);
4)      Obtain the latitude and longitude –

@Override
        public void onLocationChanged(Location location) {
                        intlat=(int) (location.getLatitude());
                        intlon=(int) (location.getLongitude());
                        latitudeval.setText(String.valueOf(lat));
                        longitudeval.setText(String.valueOf(lon));
        }

The code will look as shown below.



Create an APK file out of it and install on your mobile and run the application. The output will be as shown in the snapshot shown below.


Thursday, May 24, 2012

Simple SMS - Receive Feature


    In the previous post I had told about the method to send sms, in this post I will tell about how to receive SMS and how to test out the application.

We will use the same application which we used for sending SMS, here we will add one more class called Rec which will extend BroadcastReceiver have code to receive application.  Once you do this you need to implement onRecieve method as shown below and write an intent filter which will allow it to receive SMS.
/*to obtain the message*/        
public void onReceive(Context C, Intent I) {
                               
                                Bundle B=I.getExtras();
                                SmsMessage[] msgs=null;
                                String sms_str="";
/* Receive SMS and display*/                                   
                                if(B !=null){
                Object[] pdus=(Object[]) B.get("pdus");
                msgs=new SmsMessage[pdus.length];
                for(int i=0;i<msgs.length;i++){
/*To convert the sms which is in PDU format*/
                msgs[i]=SmsMessage.createFromPdu((byte[])pdus[i]);
/*To display the number from which the message was sent*/
                sms_str+="Recieved SMS From : "+msgs[i].getOriginatingAddress() +" : ";
                sms_str+=msgs[i].getMessageBody().toString()+"\n";
                                                }
                Toast.makeText(C, sms_str, Toast.LENGTH_LONG).show();
                                }
The code for receive class will look like in the snapshot given below.



Now we need to modify the manifest.xml file to include the following

<receiver android:name=".Rec">
     <intent-filter>
           <action android:name="android.provider.Telephony.SMS_RECEIVED" />
     </intent-filter>
</receiver>

Which will display the message in the application and will display it as a Toast.
Also include the below code so that the application has the access to receive sms.
<uses-permission android:name="android.permission.RECEIVE_SMS">
    </uses-permission>
So the manifest file will look like in the image given below.



Once these are done the application is ready to receive the SMS. So now the question is how to test it. Inorder to do test if the application receives the the eclipse has a DDMS perspective which allows you to send voice or sms to the emulator. To access DDMS you can refer to the following link DDMS Link. Now type in the emulator number in this case it is 5554 and send as SMS as shown in the snapshot below. 



Once you click on Send button in DDMS you can see that the SMS is received in the application as shown in the snapshot shown below.


Saturday, May 5, 2012

Simple SMS - Send feature


SMS is the most used and one of the most popular features in the mobile phone. In this post I have explained a simple custom sms app which uses the API’s provided by android.

                In this app I will create a text box which will take only numbers and one more text box where in you can type in your message. Once these are done the user can click on the send button which will send the sms to the phone number mentioned.
So lets get started with the creation of the application-
Step 1 – Modification of AndroidManifest.xml file
                Since this application sends SMS we need to provide the application rights to access the SMS service in the mobile device. So we need to add the code below in the “androidmanifest.xml” file
<uses-permission android:name="android.permission.SEND_SMS">    </uses-permission>
The manifest file would like in the snapshot shown below.



Step 2 – Layout Creation
                The layout for this is kept very simple wherein we have one editable text box for phone number and other for message. The layout will be as shown in the snapshot given below.



Step 3 – Code to send SMS
                Open the java file in src folder, as you can see you already have basic code already setup for you. So we need to just implement the send sms functionality in this. Declare the buttons and editable text boxes and bind them to the respective controls in the UI as shown in the code below –
    Button send;
    EditText ph_num;
    EditText message;

/*bind the variables to the controls used in the UI*/
        send=(Button) findViewById(R.id.button1);
        ph_num=(EditText) findViewById(R.id.editText1);
        message=(EditText) findViewById(R.id.editText2);
       
Then implement the send SMS functionality when you click the Send SMS button, the code for which is given below.

send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/*to convert the phone number and the message to string format*/
                String phone_num=ph_num.getText().toString();
                String sms=message.getText().toString();
/*we will go to send sms functionality only if there is message and phone number*/
                if(phone_num.length()>0 && sms.length() > 0)
                                send_sms(phone_num,sms);
                else
Toast.makeText(getBaseContext(), "Please enter both phone number and message", Toast.LENGTH_LONG).show();
                                                }
                                });

Now we will code the Send SMS functionality –
Inorder to send SMS android provides SmsManager, but this object cant be instantiated directly hence we need to make use of Pending Intent. A Pending Intent is a token that is provided to a foreign application which gives it right to use the applications permission to execute a predefined code in the application. This is done as per the code shown below
public void send_sms(String phone, String msg){
PendingIntent SMS_Sent=PendingIntent.getActivity(this, 0, new Intent(this,AndroidSMSActivity.class), 0);
                 SmsManager sms=SmsManager.getDefault();
                 sms.sendTextMessage(phone, null, msg, SMS_Sent, null);
                Toast.makeText(this, "SMS Sent", Toast.LENGTH_LONG).show();
    }
At the end we add a Toast to notify the user that the SMS has been sent. The code will be as shown below in the snapshot.


Now run the application through the emulator, although it doesnt send sms to any mobile device and the result will be as shown in the snapshot below. 



I will explain how to test out the application using 2 emulators in the post where I will explain how to receive SMS. Hope this was useful to you.

Sunday, January 22, 2012

ViewFlipper


             A ViewFlipper is used to animate the movement between 2 or more different views. This is generally used to improve the visual and make the app appear smooth.

So in this post I have created a small and simple app using the ViewFlipper control. The flow of the app is given below –
1) The first screen will have a text indicating the screen on which the user is present and it will have a button through which the user can go to the second screen.
2) When the user clicks on the button in screen 1 the first screen will move to right and the second screen will move in from left.
3) The second screen will be similar to the first screen but the button will redirect the user to the first screen.
If you haven’t got the flow, go to the bottom of the post where I have included the snapshot of the output.

Now lets get on with the coding part. Create a new project, once you have created a new project you need to create a new folder in res (resource) call it anim (you can name the folder anything you like. Here I have named it as anim). In this folder create new xml files which will define the animation of the screen. Create 2 new xml called transition_in_left and transition_out_left.

Ok here I will deviate from the topic a bit, since we need to understand what animation is all about.  As you know animation is making simple transformation or loading of different images to make an object livelier. In android there are 2 kinds of animation \
1) Property Animation – Creates animation by modifying the property of the image.
2) View Animation – Creates animation by showing sequence of image in sequence.
In this post I am using View animation, which in turn has 2 types
1) Tween Animation – Animation by performing series of transformation on an image.
2) Frame Animation – Animation by showing sequence of images in a particular order.

In this post I will be using Tween animation and will use the translate property of it, given below is a very brief description of the same.
It has 4 main elements,
1) alpha – provides fade in and fade out animations.
2) scale – provides the ability to increase or decrease the size.
3) translate – provides the ability to make horizontal or vertical movement.
4) rotate – provides the ability to rotate the image

So open the transition_in_left.xml file and use the code below. The below code will case the screen to move from left to right as you can see the fromdelta value changes from -100% to 0.
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
 android:interpolator="@android:anim/decelerate_interpolator">
<translate
 android:fromXDelta="-100%"
 android:toXDelta="0%"
 android:duration="500" />
</set>

Similarly create open another xml file transition_in_left.xml and add the property as shown below –
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
 android:interpolator="@android:anim/decelerate_interpolator">
<translate
 android:fromXDelta="0%"
 android:toXDelta="100%"
 android:duration="500" />
</set>

Now that we are done with the definition of the animator, lets define the main layout. Open main.xml layout in resà layout folder. Remove the existing text box and add a new textbox which will have a text called “View Flipper Demo”. Then add the fiew flipper such that it spans the entire length and width of the screen. Then add the LinearLayout which will have a text which indicates the screen which you are in and a button which will cause the second screen to appear with animation. Add one more LinearLayout and add the same contents as in screen 1.

With the UI and the animation done, we need to add action part. So go to the src folder and open the java file in it. As you can see the basic features are already present.
We need to bind the viewflipper, buttons , animations and assign action to the buttons. The code below does the same

The below code defines the ViewFlipper and buttons used.
        final ViewFlipper vf=(ViewFlipper) findViewById(R.id.viewFlipper1);
        Button firstScreenButton=(Button) findViewById(R.id.buttonfirstscreen);
        Button secondScreenButton=(Button) findViewById(R.id.buttonsecondscreen);
 
Then you need to define the animations. The below code does the same
        Animation inanimation=AnimationUtils.loadAnimation(this,R.anim.transition_in_left);
        Animation outanimation=AnimationUtils.loadAnimation(this, R.anim.transition_out_left);
 Now we need to assign the animation to in and out movements.
        vf.setInAnimation(inanimation);
        vf.setOutAnimation(outanimation);
  
Since we need the animations to appear when button is clicked we need to assign action to the onClickListener as shown below. In the below code we assign action to button in Screen1.
        firstScreenButton.setOnClickListener(new Button.OnClickListener(){

                   @Override
                   public void onClick(View arg0) {
                   vf.showNext();
                   }});
  
Similarly we need to assign action for the button in screen2.
        secondScreenButton.setOnClickListener(new Button.OnClickListener(){

                   @Override
                   public void onClick(View arg0) {
                   vf.showPrevious();
                   }});

The entire file will look in the snapshot shown below.



Now run the application in an emulator or a device. When the application runs the first screen that appears is given below. 



Click on the button and you can see the screen 1 appears to move out and screen 2 appears to move in from left replacing screen1 as shown below.



Now that you are in screen 2 it will be as shown in the snapshot shown below. Click on the button and it should take you back to the first Screen.


Wednesday, January 4, 2012

SeekBar

A seekbar is just like a progress bar with a dragger in it which the user can set. In this post I have just created a simple seekbar which shows the value in a text below and shows if the tracking is on if the touch is present over the tracker.
First create a new project. Then open file main.xml under resà layouts. Remove the default text there and add a text which will show if the tracking is on or not. Below that add the seekbar control. Below this add one more text which will show the value to which the slider has been dragged to. The layout will look as shown in the snapshot below.


Then we need to bind the functionality with the UI controls so open the java file under src à your package. You can see already there will be basic code is already there. The class will by default extend Activity you need to implement OnSeekBarChangeListener, once you do this you will need to override other functions onProgressChanged, onStartTrackingTouch, onStopTrackingTouch. Then declare the seekbar and the 2 text views which will show the tracking status and the value.
Then create a seekbar and create a listener for that as shown below-
sb=(SeekBar) findViewById(R.id.seekBar1);
sb.setOnSeekBarChangeListener(this);
Then you need to declare and bind the textboxes. Once this is done you need to add functionality when the seekbar position is changed, when the tracking has started, when the tracking has stopped as shown below.
@Override
public void onProgressChanged(SeekBar arg0, int progress, boolean TouchStart) {
                                sv.setText("Progress="+String.valueOf(progress));
}

@Override
public void onStartTrackingTouch(SeekBar arg0) {
                                title.setText("Tracking On");
}

@Override
public void onStopTrackingTouch(SeekBar arg0) {
                                title.setText("Tracking Off");
}
 Once this is done we are done and the file will look as in the snapshot given below.

Now run the project in your emulator or mobile. Drag the slider and the text above the seekbar should change to Tracking On and when u stop it should say Tracking off and the value in the textbox below the seekbar should show value at which the slider has been dragged to as show in the snapshot given below.