Android – Audio Capture

Android – Audio Capture ”; Previous Next Android has a built in microphone through which you can capture audio and store it , or play it in your phone. There are many ways to do that but the most common way is through MediaRecorder class. Android provides MediaRecorder class to record audio or video. In order to use MediaRecorder class ,you will first create an instance of MediaRecorder class. Its syntax is given below. MediaRecorder myAudioRecorder = new MediaRecorder(); Now you will set the source , output and encoding format and output file. Their syntax is given below. myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB); myAudioRecorder.setOutputFile(outputFile); After specifying the audio source and format and its output file, we can then call the two basic methods prepare and start to start recording the audio. myAudioRecorder.prepare(); myAudioRecorder.start(); Apart from these methods , there are other methods listed in the MediaRecorder class that allows you more control over audio and video recording. Sr.No Method & description 1 setAudioSource() This method specifies the source of audio to be recorded 2 setVideoSource() This method specifies the source of video to be recorded 3 setOutputFormat() This method specifies the audio format in which audio to be stored 4 setAudioEncoder() This method specifies the audio encoder to be used 5 setOutputFile() This method configures the path to the file into which the recorded audio is to be stored 6 stop() This method stops the recording process. 7 release() This method should be called when the recorder instance is needed. Example This example provides demonstration of MediaRecorder class to capture audio and then MediaPlayer class to play that recorded audio. To experiment with this example , you need to run this on an actual device. Steps Description 1 You will use Android studio IDE to create an Android application and name it as AudioCapture under a package com.example.sairamkrishna.myapplication. 2 Modify src/MainActivity.java file to add AudioCapture code 3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required. 4 Modify AndroidManifest.xml to add necessary permissions. 5 Run the application and choose a running android device and install the application on it and verify the results. Here is the content of src/MainActivity.java package com.example.sairamkrishna.myapplication; import android.media.MediaPlayer; import android.media.MediaRecorder; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; import java.io.IOException; import java.util.Random; import static android.Manifest.permission.RECORD_AUDIO; import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; import android.support.v4.app.ActivityCompat; import android.content.pm.PackageManager; import android.support.v4.content.ContextCompat; public class MainActivity extends AppCompatActivity { Button buttonStart, buttonStop, buttonPlayLastRecordAudio, buttonStopPlayingRecording ; String AudioSavePathInDevice = null; MediaRecorder mediaRecorder ; Random random ; String RandomAudioFileName = “ABCDEFGHIJKLMNOP”; public static final int RequestPermissionCode = 1; MediaPlayer mediaPlayer ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); buttonStart = (Button) findViewById(R.id.button); buttonStop = (Button) findViewById(R.id.button2); buttonPlayLastRecordAudio = (Button) findViewById(R.id.button3); buttonStopPlayingRecording = (Button)findViewById(R.id.button4); buttonStop.setEnabled(false); buttonPlayLastRecordAudio.setEnabled(false); buttonStopPlayingRecording.setEnabled(false); random = new Random(); buttonStart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(checkPermission()) { AudioSavePathInDevice = Environment.getExternalStorageDirectory().getAbsolutePath() + “/” + CreateRandomAudioFileName(5) + “AudioRecording.3gp”; MediaRecorderReady(); try { mediaRecorder.prepare(); mediaRecorder.start(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } buttonStart.setEnabled(false); buttonStop.setEnabled(true); Toast.makeText(MainActivity.this, “Recording started”, Toast.LENGTH_LONG).show(); } else { requestPermission(); } } }); buttonStop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mediaRecorder.stop(); buttonStop.setEnabled(false); buttonPlayLastRecordAudio.setEnabled(true); buttonStart.setEnabled(true); buttonStopPlayingRecording.setEnabled(false); Toast.makeText(MainActivity.this, “Recording Completed”, Toast.LENGTH_LONG).show(); } }); buttonPlayLastRecordAudio.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) throws IllegalArgumentException, SecurityException, IllegalStateException { buttonStop.setEnabled(false); buttonStart.setEnabled(false); buttonStopPlayingRecording.setEnabled(true); mediaPlayer = new MediaPlayer(); try { mediaPlayer.setDataSource(AudioSavePathInDevice); mediaPlayer.prepare(); } catch (IOException e) { e.printStackTrace(); } mediaPlayer.start(); Toast.makeText(MainActivity.this, “Recording Playing”, Toast.LENGTH_LONG).show(); } }); buttonStopPlayingRecording.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { buttonStop.setEnabled(false); buttonStart.setEnabled(true); buttonStopPlayingRecording.setEnabled(false); buttonPlayLastRecordAudio.setEnabled(true); if(mediaPlayer != null){ mediaPlayer.stop(); mediaPlayer.release(); MediaRecorderReady(); } } }); } public void MediaRecorderReady(){ mediaRecorder=new MediaRecorder(); mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB); mediaRecorder.setOutputFile(AudioSavePathInDevice); } public String CreateRandomAudioFileName(int string){ StringBuilder stringBuilder = new StringBuilder( string ); int i = 0 ; while(i < string ) { stringBuilder.append(RandomAudioFileName. charAt(random.nextInt(RandomAudioFileName.length()))); i++ ; } return stringBuilder.toString(); } private void requestPermission() { ActivityCompat.requestPermissions(MainActivity.this, new String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO}, RequestPermissionCode); } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case RequestPermissionCode: if (grantResults.length> 0) { boolean StoragePermission = grantResults[0] == PackageManager.PERMISSION_GRANTED; boolean RecordPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED; if (StoragePermission && RecordPermission) { Toast.makeText(MainActivity.this, “Permission Granted”, Toast.LENGTH_LONG).show(); } else { Toast.makeText(MainActivity.this,”Permission Denied”,Toast.LENGTH_LONG).show(); } } break; } } public boolean checkPermission() { int result = ContextCompat.checkSelfPermission(getApplicationContext(), WRITE_EXTERNAL_STORAGE); int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), RECORD_AUDIO); return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED; } } Here is the content of activity_main.xml In the below code abc indicates the logo of tutorialspoint <?xml version=”1.0″ encoding=”utf-8″?> <RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android” xmlns:tools=”http://schemas.android.com/tools” android:layout_width=”match_parent” android:layout_height=”match_parent” android:paddingBottom=”@dimen/activity_vertical_margin” android:paddingLeft=”@dimen/activity_horizontal_margin” android:paddingRight=”@dimen/activity_horizontal_margin” android:paddingTop=”@dimen/activity_vertical_margin”> <ImageView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/imageView” android:layout_alignParentTop=”true” android:layout_centerHorizontal=”true” android:src=”@drawable/abc”/> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Record” android:id=”@+id/button” android:layout_below=”@+id/imageView” android:layout_alignParentLeft=”true” android:layout_marginTop=”37dp” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”STOP” android:id=”@+id/button2″ android:layout_alignTop=”@+id/button” android:layout_centerHorizontal=”true” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Play” android:id=”@+id/button3″ android:layout_alignTop=”@+id/button2″ android:layout_alignParentRight=”true” android:layout_alignParentEnd=”true” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”STOP PLAYING RECORDING ” android:id=”@+id/button4″ android:layout_below=”@+id/button2″ android:layout_centerHorizontal=”true” android:layout_marginTop=”10dp” /> </RelativeLayout> Here is the content of Strings.xml <resources> <string name=”app_name”>My Application</string> </resources> Here is the content of AndroidManifest.xml <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.example.sairamkrishna.myapplication” > <uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE”/> <uses-permission android:name=”android.permission.RECORD_AUDIO” /> <uses-permission android:name=”android.permission.STORAGE” /> <application android:allowBackup=”true” android:icon=”@drawable/ic_launcher” android:label=”@string/app_name” android:theme=”@style/AppTheme” > <activity android:name=”com.example.sairamkrishna.myapplication.MainActivity” android:label=”@string/app_name” > <intent-filter> <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> </application> </manifest> Let”s try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project”s activity files and click Run icon from the toolbar. Before starting your application, Android studio will display following images. Now by default you will see stop and play button disable. Just press the Record button and your application will start recording the audio. It will display the following screen. Now just press stop button and it will save the recorded audio to external sd card. When you click on stop button , the following screen would appear. Now just press the play button and and recorded audio will just start playing on the device. The following message appears when you click on play button. Print Page

Android – UI Design

Android – UI Design ”; Previous Next In this chapter we will look at the different UI components of android screen. This chapter also covers the tips to make a better UI design and also explains how to design a UI. UI screen components A typical user interface of an android application consists of action bar and the application content area. Main Action Bar View Control Content Area Split Action Bar These components have also been shown in the image below − Understanding Screen Components The basic unit of android application is the activity. A UI is defined in an xml file. During compilation, each element in the XML is compiled into equivalent Android GUI class with attributes represented by methods. View and ViewGroups An activity is consist of views. A view is just a widget that appears on the screen. It could be button e.t.c. One or more views can be grouped together into one GroupView. Example of ViewGroup includes layouts. Types of layout There are many types of layout. Some of which are listed below − Linear Layout Absolute Layout Table Layout Frame Layout Relative Layout Linear Layout Linear layout is further divided into horizontal and vertical layout. It means it can arrange views in a single column or in a single row. Here is the code of linear layout(vertical) that includes a text view. <?xml version=”1.0” encoding=”utf-8”?> <LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android” android:layout_width=”fill_parent” android:layout_height=”fill_parent” android:orientation=”vertical” > <TextView android:layout_width=”fill_parent” android:layout_height=”wrap_content” android:text=”@string/hello” /> </LinearLayout> AbsoluteLayout The AbsoluteLayout enables you to specify the exact location of its children. It can be declared like this. <AbsoluteLayout android:layout_width=”fill_parent” android:layout_height=”fill_parent” xmlns:android=”http://schemas.android.com/apk/res/android” > <Button android:layout_width=”188dp” android:layout_height=”wrap_content” android:text=”Button” android:layout_x=”126px” android:layout_y=”361px” /> </AbsoluteLayout> TableLayout The TableLayout groups views into rows and columns. It can be declared like this. <TableLayout xmlns:android=”http://schemas.android.com/apk/res/android” android:layout_height=”fill_parent” android:layout_width=”fill_parent” > <TableRow> <TextView android:text=”User Name:” android:width =”120dp” /> <EditText android:id=”@+id/txtUserName” android:width=”200dp” /> </TableRow> </TableLayout> RelativeLayout The RelativeLayout enables you to specify how child views are positioned relative to each other.It can be declared like this. <RelativeLayout android:id=”@+id/RLayout” android:layout_width=”fill_parent” android:layout_height=”fill_parent” xmlns:android=”http://schemas.android.com/apk/res/android” > </RelativeLayout> FrameLayout The FrameLayout is a placeholder on screen that you can use to display a single view. It can be declared like this. <?xml version=”1.0” encoding=”utf-8”?> <FrameLayout android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:layout_alignLeft=”@+id/lblComments” android:layout_below=”@+id/lblComments” android:layout_centerHorizontal=”true” > <ImageView android:src = “@drawable/droid” android:layout_width=”wrap_content” android:layout_height=”wrap_content” /> </FrameLayout> Apart form these attributes, there are other attributes that are common in all views and ViewGroups. They are listed below − Sr.No View & description 1 layout_width Specifies the width of the View or ViewGroup 2 layout_height Specifies the height of the View or ViewGroup 3 layout_marginTop Specifies extra space on the top side of the View or ViewGroup 4 layout_marginBottom Specifies extra space on the bottom side of the View or ViewGroup 5 layout_marginLeft Specifies extra space on the left side of the View or ViewGroup 6 layout_marginRight Specifies extra space on the right side of the View or ViewGroup 7 layout_gravity Specifies how child Views are positioned 8 layout_weight Specifies how much of the extra space in the layout should be allocated to the View Units of Measurement When you are specifying the size of an element on an Android UI, you should remember the following units of measurement. Sr.No Unit & description 1 dp Density-independent pixel. 1 dp is equivalent to one pixel on a 160 dpi screen. 2 sp Scale-independent pixel. This is similar to dp and is recommended for specifying font sizes 3 pt Point. A point is defined to be 1/72 of an inch, based on the physical screen size. 4 px Pixel. Corresponds to actual pixels on the screen Screen Densities Sr.No Density & DPI 1 Low density (ldpi) 120 dpi 2 Medium density (mdpi) 160 dpi 3 High density (hdpi) 240 dpi 4 Extra High density (xhdpi) 320 dpi Optimizing layouts Here are some of the guidelines for creating efficient layouts. Avoid unnecessary nesting Avoid using too many Views Avoid deep nesting Print Page Previous Next Advertisements ”;

Android – Progress Circle

Android – Progress Circle ”; Previous Next The easiest way to make a progress circle is using through a class called ProgressDialog. The loading bar can also be made through that class. The only logical difference between bar and circle is , that the former is used when you know the total time for waiting for a particular task whereas the later is used when you don”t know the waiting time. In order to this , you need to instantiate an object of this class. Its syntax is. ProgressDialog progress = new ProgressDialog(this); Now you can set some properties of this dialog. Such as, its style,its text e.t.c progress.setMessage(“Downloading Music 🙂 “); progress.setProgressStyle(ProgressDialog.STYLE_SPINNER); progress.setIndeterminate(true); Apart from these methods, there are other methods that are provided by the ProgressDialog class. Sr.No Classes & Description 1 getMax() This methods returns the maximum value of the progress 2 incrementProgressBy(int diff) This method increment the progress bar by the difference of value passed as a parameter 3 setIndeterminate(boolean indeterminate) This method set the progress indicator as determinate or indeterminate 4 setMax(int max) This method set the maximum value of the progress dialog 5 setProgress(int value) This method is used to update the progress dialog with some specific value 6 show(Context context, CharSequence title, CharSequence message) This is a static method, used to display progress dialog Example This example demonstrates the spinning use of the progress dialog. It display a spinning progress dialog on pressing the button. To experiment with this example, you need to run this on an actual device on after developing the application according to the steps below. Steps Description 1 You will use Android Studio to create an Android application under a package com.example.sairamkrishna.myapplication. 2 Modify src/MainActivity.java file to add progress code to display the spinning progress dialog. 3 Modify res/layout/activity_main.xml file to add respective XML code. 4 Run the application and choose a running android device and install the application on it and verify the results. Following is the content of the modified main activity file src/MainActivity.java. package com.example.sairamkrishna.myapplication; import android.app.ProgressDialog; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.Button; public class MainActivity extends Activity { Button b1; private ProgressDialog progressBar; private int progressBarStatus = 0; private Handler progressBarbHandler = new Handler(); private long fileSize = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1=(Button)findViewById(R.id.button); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { progressBar = new ProgressDialog(v.getContext()); progressBar.setCancelable(true); progressBar.setMessage(“File downloading …”); progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER); progressBar.setProgress(0); progressBar.setMax(100); progressBar.show(); progressBarStatus = 0; fileSize = 0; new Thread(new Runnable() { public void run() { while (progressBarStatus < 100) { progressBarStatus = downloadFile(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } progressBarbHandler.post(new Runnable() { public void run() { progressBar.setProgress(progressBarStatus); } }); } if (progressBarStatus >= 100) { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } progressBar.dismiss(); } } }).start(); } }); } public int downloadFile() { while (fileSize <= 1000000) { fileSize++; if (fileSize == 100000) { return 10; }else if (fileSize == 200000) { return 20; }else if (fileSize == 300000) { return 30; }else if (fileSize == 400000) { return 40; }else if (fileSize == 500000) { return 50; }else if (fileSize == 700000) { return 70; }else if (fileSize == 800000) { return 80; } } return 100; } } Modify the content of res/layout/activity_main.xml to the following In the following code abc indicates the logo of tutorialspoint.com <?xml version=”1.0″ encoding=”utf-8″?> <RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android” xmlns:tools=”http://schemas.android.com/tools” android:layout_width=”match_parent” android:layout_height=”match_parent” android:paddingLeft=”@dimen/activity_horizontal_margin” android:paddingRight=”@dimen/activity_horizontal_margin” android:paddingTop=”@dimen/activity_vertical_margin” android:paddingBottom=”@dimen/activity_vertical_margin” tools:context=”.MainActivity”> <TextView android:text=”Music Palyer” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/textview” android:textSize=”35dp” android:layout_alignParentTop=”true” android:layout_centerHorizontal=”true” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Tutorials point” android:id=”@+id/textView” android:layout_below=”@+id/textview” android:layout_centerHorizontal=”true” android:textColor=”#ff7aff24″ android:textSize=”35dp” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”download” android:id=”@+id/button” android:layout_alignParentBottom=”true” android:layout_centerHorizontal=”true” android:layout_marginBottom=”112dp” /> <ImageView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/imageView” android:src=”@drawable/abc” android:layout_below=”@+id/textView” android:layout_centerHorizontal=”true” /> </RelativeLayout> Modify the res/values/string.xml to the following <resources> <string name=”app_name”>My Application</string> </resources> This is the default AndroidManifest.xml <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.example.sairamkrishna.myapplication” > <application android:allowBackup=”true” android:icon=”@drawable/ic_launcher” android:label=”@string/app_name” android:theme=”@style/AppTheme” > <activity android:name=”com.example.sairamkrishna.myapplication.MainActivity” android:label=”@string/app_name” > <intent-filter> <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> </application> </manifest> Let”s try to run your application. To run the app from android studio, open one of your project”s activity files and click Run icon from the toolbar. Before starting your application, Android studio will display following window to select an option where you want to run your Android application. Just press the button to start the Progress Dialog. After pressing , following screen would appear. Print Page Previous Next Advertisements ”;

Android – TextureView

Android – TextureView ”; Previous Next If you want to display a live video stream or any content stream such as video or an OpenGL scene, you can use TextureView provided by android in order to do that. In order to use TextureView, all you need to do is get its SurfaceTexture.The SurfaceTexture can then be used to render content. In order to do this, you just need to do instantiate an object of this class and implement SurfaceTextureListener interface. Its syntax is given below − private TextureView myTexture; public class MainActivity extends Activity implements SurfaceTextureListener{ protected void onCreate(Bundle savedInstanceState) { myTexture = new TextureView(this); myTexture.setSurfaceTextureListener(this); setContentView(myTexture); } } After that, what you need to do is to override its methods. The methods are listed as follows − @Override public void onSurfaceTextureAvailable(SurfaceTexture arg0, int arg1, int arg2) { } @Override public boolean onSurfaceTextureDestroyed(SurfaceTexture arg0) { } @Override public void onSurfaceTextureSizeChanged(SurfaceTexture arg0, int arg1,int arg2) { } @Override public void onSurfaceTextureUpdated(SurfaceTexture arg0) { } Any view that is displayed in the texture view can be rotated and its alpha property can be adjusted by using setAlpha and setRotation methods. Its syntax is given below − myTexture.setAlpha(1.0f); myTexture.setRotation(90.0f); Apart from these methods, there are other methods available in TextureView class. They are listed below − Sr.No Method & description 1 getSurfaceTexture() This method returns the SurfaceTexture used by this view. 2 getBitmap(int width, int height) This method returns Returns a Bitmap representation of the content of the associated surface texture. 3 getTransform(Matrix transform) This method returns the transform associated with this texture view. 4 isOpaque() This method indicates whether this View is opaque. 5 lockCanvas() This method start editing the pixels in the surface 6 setOpaque(boolean opaque) This method indicates whether the content of this TextureView is opaque. 7 setTransform(Matrix transform) This method sets the transform to associate with this texture view. 8 unlockCanvasAndPost(Canvas canvas) This method finish editing pixels in the surface. Example The below example demonstrates the use of TextureView class. It crates a basic application that allows you to view camera inside a texture view and change its angle , orientation e.t.c. To experiment with this example , you need to run this on an actual device on which camera is present. Steps Description 1 You will use android studio IDE to create an Android application and name it as TextureView under a package com.example.textureview. 2 Modify src/MainActivity.java file to add Activity code. 3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required. 5 Run the application and choose a running android device and install the application on it and verify the results. Here is the content of src/com.example.textureview/MainActivity.java. package com.example.textureview; import java.io.IOException; import android.annotation.SuppressLint; import android.app.Activity; import android.graphics.SurfaceTexture; import android.hardware.Camera; import android.os.Bundle; import android.view.Gravity; import android.view.Menu; import android.view.TextureView; import android.view.TextureView.SurfaceTextureListener; import android.view.View; import android.widget.FrameLayout; public class MainActivity extends Activity implements SurfaceTextureListener { private TextureView myTexture; private Camera mCamera; @SuppressLint(“NewApi”) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myTexture = new TextureView(this); myTexture.setSurfaceTextureListener(this); setContentView(myTexture); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @SuppressLint(“NewApi”) @Override public void onSurfaceTextureAvailable(SurfaceTexture arg0, int arg1, int arg2) { mCamera = Camera.open(); Camera.Size previewSize = mCamera.getParameters().getPreviewSize(); myTexture.setLayoutParams(new FrameLayout.LayoutParams( previewSize.width, previewSize.height, Gravity.CENTER)); try { mCamera.setPreviewTexture(arg0); } catch (IOException t) { } mCamera.startPreview(); myTexture.setAlpha(1.0f); myTexture.setRotation(90.0f); } @Override public boolean onSurfaceTextureDestroyed(SurfaceTexture arg0) { mCamera.stopPreview(); mCamera.release(); return true; } @Override public void onSurfaceTextureSizeChanged(SurfaceTexture arg0, int arg1, int arg2) { // TODO Auto-generated method stub } @Override public void onSurfaceTextureUpdated(SurfaceTexture arg0) { // TODO Auto-generated method stub } } Here is the content of activity_main.xml <?xml version=”1.0″ encoding=”utf-8″?> <RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android” xmlns:tools=”http://schemas.android.com/tools” android:layout_width=”match_parent” android:layout_height=”match_parent” android:paddingBottom=”@dimen/activity_vertical_margin” android:paddingLeft=”@dimen/activity_horizontal_margin” android:paddingRight=”@dimen/activity_horizontal_margin” android:paddingTop=”@dimen/activity_vertical_margin” tools:context=”.MainActivity” > <TextureView android:id=”@+id/textureView1″ android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:layout_alignParentTop=”true” android:layout_centerHorizontal=”true” /> </RelativeLayout> Here is the default content of AndroidManifest.xml <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.example.textureview” > <uses-permission android:name=”android.permission.CAMERA”/> <application android:allowBackup=”true” android:icon=”@drawable/ic_launcher” android:label=”@string/app_name” android:theme=”@style/AppTheme” > <activity android:name=”com.example.textureview.MainActivity” android:label=”@string/app_name” > <intent-filter> <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> </application> </manifest> Let”s try to run your TextureView application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project”s activity files and click Run icon from the toolbar. Before starting your application, Android studio will display following window to select an option where you want to run your Android application. Select your mobile device as an option and then check your mobile device which will display following screen. This screen has alpha property set to 0.5 and rotation set to 45. This screen has alpha property set to 1.5 and rotation set to 45. This screen has alpha property set to 1.0 and rotation set to 90. Print Page Previous Next Advertisements ”;

Android – Twitter Integration

Android – Twitter Integration ”; Previous Next Android allows your application to connect to twitter and share data or any kind of updates on twitter. This chapter is about integrating twitter into your application. There are two ways through which you can integrate twitter and share something from your application. These ways are listed below − Twitter SDK (Twitter4J) Intent Share Integrating Twitter SDK This is the first way of connecting with Twitter. You have to register your application and then receive some Application Id, and then you have to download the twitter SDK and add it to your project. The steps are listed below − Registering your application Create a new twitter application at dev.twitter.com/apps/new and fill all the information. It is shown below − Now under settings tab, change the access to read,write and access messages and save the settings. It is shown below − If everything works fine, you will receive an consumer ID with the secret. Just copy the application id and save it somewhere. It is shown in the image below − Downloading SDK and integrating it Download twitter sdk here. Copy the twitter4J jar into your project libs folder. Posting tweets on twitter application Once everything is complete , you can run the twitter 4J samples which can be found here. In order to use twitter, you need to instantiate an object of twitter class.It can be done by calling the static method getsingleton(). Its syntax is given below. // The factory instance is re-usable and thread safe. Twitter twitter = TwitterFactory.getSingleton(); In order to update the status , you can call updateStatus() method. Its syntax is given below − Status status = twitter.updateStatus(latestStatus); System.out.println(“Successfully updated the status to [” + status.getText() + “].”); Intent share Intent share is used to share data between applications. In this strategy, we will not handle the SDK stuff, but let the twitter application handles it. We will simply call the twitter application and pass the data to share. This way, we can share something on twitter. Android provides intent library to share data between activities and applications. In order to use it as share intent, we have to specify the type of the share intent to ACTION_SEND. Its syntax is given below − Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); Next thing you need to is to define the type of data to pass, and then pass the data. Its syntax is given below − shareIntent.setType(“text/plain”); shareIntent.putExtra(Intent.EXTRA_TEXT, “Hello, from tutorialspoint”); startActivity(Intent.createChooser(shareIntent, “Share your thoughts”)); Apart from the these methods, there are other methods available that allows intent handling. They are listed below − Sr.No Method & description 1 addCategory(String category) This method add a new category to the intent. 2 createChooser(Intent target, CharSequence title) Convenience function for creating a ACTION_CHOOSER Intent 3 getAction() This method retrieve the general action to be performed, such as ACTION_VIEW 4 getCategories() This method return the set of all categories in the intent and the current scaling event 5 putExtra(String name, int value) This method add extended data to the intent. 6 toString() This method returns a string containing a concise, human-readable description of this object Example Here is an example demonstrating the use of IntentShare to share data on twitter. It creates a basic application that allows you to share some text on twitter. To experiment with this example , you can run this on an actual device or in an emulator. Steps Description 1 You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication. 2 Modify src/MainActivity.java file to add necessary code. 3 Modify the res/layout/activity_main to add respective XML components 4 Run the application and choose a running android device and install the application on it and verify the results Following is the content of the modified MainActivity.java. package com.example.sairamkrishna.myapplication; import android.content.Intent; import android.net.Uri; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import java.io.FileNotFoundException; import java.io.InputStream; public class MainActivity extends ActionBarActivity { private ImageView img; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); img=(ImageView)findViewById(R.id.imageView); Button b1=(Button)findViewById(R.id.button); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent sharingIntent = new Intent(Intent.ACTION_SEND); Uri screenshotUri = Uri.parse(“android.resource://comexample.sairamkrishna.myapplication/*”); try { InputStream stream = getContentResolver().openInputStream(screenshotUri); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } sharingIntent.setType(“image/jpeg”); sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri); startActivity(Intent.createChooser(sharingIntent, “Share image using”)); } }); } } Following is the modified content of the xml res/layout/activity_main.xml. <?xml version=”1.0″ encoding=”utf-8″?> <RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android” xmlns:tools=”http://schemas.android.com/tools” android:layout_width=”match_parent” android:layout_height=”match_parent” android:paddingLeft=”@dimen/activity_horizontal_margin” android:paddingRight=”@dimen/activity_horizontal_margin” android:paddingTop=”@dimen/activity_vertical_margin” android:paddingBottom=”@dimen/activity_vertical_margin” tools:context=”.MainActivity”> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/textView” android:layout_alignParentTop=”true” android:layout_centerHorizontal=”true” android:textSize=”30dp” android:text=”Twitter share ” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Tutorials Point” android:id=”@+id/textView2″ android:layout_below=”@+id/textView” android:layout_centerHorizontal=”true” android:textSize=”35dp” android:textColor=”#ff16ff01″ /> <ImageView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/imageView” android:layout_below=”@+id/textView2″ android:layout_centerHorizontal=”true” android:src=”@drawable/abc”/> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Share” android:id=”@+id/button” android:layout_marginTop=”61dp” android:layout_below=”@+id/imageView” android:layout_centerHorizontal=”true” /> </RelativeLayout> Following is the content of AndroidManifest.xml file. <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.example.sairamkrishna.myapplication” > <application android:allowBackup=”true” android:icon=”@mipmap/ic_launcher” android:label=”@string/app_name” android:theme=”@style/AppTheme” > <activity android:name=”.MainActivity” android:label=”@string/app_name” > <intent-filter> <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> </application> </manifest> Let”s try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project”s activity files and click Run icon from the toolbar. Before starting your application,Android studio will display following window to select an option where you want to run your Android application. Select your mobile device as an option and then check your mobile device which will display your default screen − Now just tap on the button and you will see a list of share providers. Now just select twitter from that list and then write any message. It is shown in the image below − Now just select the tweet button and then it would be post on your twitter page. It is shown below − Print Page Previous Next Advertisements ”;

Android – RenderScript

Android – RenderScript ”; Previous Next In this chapter, we will learn about Android RenderScript. Usually the apps on android are designed as to consume as minimum resources as possible. But some applications like some 3D games need high level processing on android. To provide these applications high performance android introduced the RenderScript. It is android based framework which is used for running applications that perform very highly computational tasks. The development on this framework is done in Native Development Kit(NDK) provided by android. RenderScript is extremely useful for applications which performs following types of actions − 3D Rendering Image Processing Computational Photography Computer Vision How RenderScript Works RenderScript framework is basically based on data parallel computation. It distributes your application workload on all the processors available on your device like multi-core CPUs or GPUs. This parallel distribution of workload frees the programmer from the tension of load balancing and work scheduling. You can write more detailed and complex algorithms for your app without the worry of computational power. How to Begin To use the RenderScript Framework you must have following two things − A RenderScript Kernel RenderScript APIs A RenderScript Kernel A kernel is a program which manages data processing instructions and manage workload on Central Processing Units.A kernel is a fundamental part of the operating system. Similarly to run the RenderScript framework we need a written script named as Kernel to manage all the data processing requests from our app and utilize more features of the android OS provided by the NDK and as mentioned earlier that the development of RenderScript is done in the Native Development Kit of Android. The Kernel Script is written in C-99 standard of C-language. This Standard was before the development of C++. A RenderScript kernel script file usually placed in .rs file. Each file is called as a script. A RenderScript Kernel script can contain following elements − Sr.No Elements & Description 1 A Language declaration It declares the version of RenderScript Kernel language used in this script. 2 A package declaration This declaration names the package name of the Java class which will be affected by this Kernel Code. 3 Invokable functions You can call these invokable functions from your JAVA code with arbitrary arguments. 4 Script Global Variables These are just like the variables defined in C and C++ programming language. You can access these variables from your JAVA code. Following is the Sample Code of a Kernel − uchar4 __convert__((kernel)) invert(uchar4 in, uint32_t x, uint32_t y) { uchar4 out = in; out.r = 255 – in.r; out.g = 255 – in.g; return out; } RenderScript APIs If you want to use RenderScript in your API, you can do it in following two ways − Sr.No APIs & Description 1 android.renderscript This API is available on devices running Android 3.0 and higher. 2 android.support.v8.renderscript This API is available on devices running Android 2.2 and higher. To android support library following tools are required − Latest Android SDK Tools version Latest Android SDK Build-tools version How to use RenderScript Support Library First Open the project.properties file in your project and add following lines in the file − renderscript.target=18 renderscript.support.mode=true sdk.buildtools=18.1.0 Now open your main class which use RenderScript and add an import for the Support Library classes as following − import android.support.v8.renderscript.*; Following are the purposes of above mentioned properties that we add in the project.properties file. Sr.No Project properties & Description 1 renderscript.target It specifies the byte code version to be generated. 2 renderscript.support.mode It specifies a compatible version for the generated byte code to fall back. 3 sdk.buildtools It Specifies the versions of Android SDK build tools to use. Now call your RenderScript Kernel functions and compute complex algorithms in your app. Print Page Previous Next Advertisements ”;

Android – XML Parsers

Android – XML Parser ”; Previous Next XML stands for Extensible Mark-up Language.XML is a very popular format and commonly used for sharing data on the internet. This chapter explains how to parse the XML file and extract necessary information from it. Android provides three types of XML parsers which are DOM,SAX and XMLPullParser. Among all of them android recommend XMLPullParser because it is efficient and easy to use. So we are going to use XMLPullParser for parsing XML. The first step is to identify the fields in the XML data in which you are interested in. For example. In the XML given below we interested in getting temperature only. <?xml version=”1.0″?> <current> <city id=”2643743″ name=”London”> <coord lon=”-0.12574″ lat=”51.50853″/> <country>GB</country> <sun rise=”2013-10-08T06:13:56″ set=”2013-10-08T17:21:45″/> </city> <temperature value=”289.54″ min=”289.15″ max=”290.15″ unit=”kelvin”/> <humidity value=”77″ unit=”%”/> <pressure value=”1025″ unit=”hPa”/> </current> XML – Elements An xml file consist of many components. Here is the table defining the components of an XML file and their description. Sr.No Component & description 1 Prolog An XML file starts with a prolog. The first line that contains the information about a file is prolog 2 Events An XML file has many events. Event could be like this. Document starts , Document ends, Tag start , Tag end and Text e.t.c 3 Text Apart from tags and events, and xml file also contains simple text. Such as GB is a text in the country tag. 4 Attributes Attributes are the additional properties of a tag such as value e.t.c XML – Parsing In the next step, we will create XMLPullParser object , but in order to create that we will first create XmlPullParserFactory object and then call its newPullParser() method to create XMLPullParser. Its syntax is given below − private XmlPullParserFactory xmlFactoryObject = XmlPullParserFactory.newInstance(); private XmlPullParser myparser = xmlFactoryObject.newPullParser(); The next step involves specifying the file for XmlPullParser that contains XML. It could be a file or could be a Stream. In our case it is a stream.Its syntax is given below − myparser.setInput(stream, null); The last step is to parse the XML. An XML file consist of events, Name, Text, AttributesValue e.t.c. So XMLPullParser has a separate function for parsing each of the component of XML file. Its syntax is given below − int event = myParser.getEventType(); while (event != XmlPullParser.END_DOCUMENT) { String name=myParser.getName(); switch (event){ case XmlPullParser.START_TAG: break; case XmlPullParser.END_TAG: if(name.equals(“temperature”)){ temperature = myParser.getAttributeValue(null,”value”); } break; } event = myParser.next(); } The method getEventType returns the type of event that happens. e.g: Document start , tag start e.t.c. The method getName returns the name of the tag and since we are only interested in temperature , so we just check in conditional statement that if we got a temperature tag , we call the method getAttributeValue to return us the value of temperature tag. Apart from the these methods, there are other methods provided by this class for better parsing XML files. These methods are listed below − Sr.No Method & description 1 getAttributeCount() This method just Returns the number of attributes of the current start tag 2 getAttributeName(int index) This method returns the name of the attribute specified by the index value 3 getColumnNumber() This method returns the Returns the current column number, starting from 0. 4 getDepth() This method returns Returns the current depth of the element. 5 getLineNumber() Returns the current line number, starting from 1. 6 getNamespace() This method returns the name space URI of the current element. 7 getPrefix() This method returns the prefix of the current element 8 getName() This method returns the name of the tag 9 getText() This method returns the text for that particular element 10 isWhitespace() This method checks whether the current TEXT event contains only whitespace characters. Example Here is an example demonstrating the use of XML DOM Parser. It creates a basic application that allows you to parse XML. To experiment with this example, you can run this on an actual device or in an emulator. Steps Description 1 You will use Android studio to create an Android application under a package com.example.sairamkrishna.myapplication. 2 Modify src/MainActivity.java file to add necessary code. 3 Modify the res/layout/activity_main to add respective XML components 4 Create a new XML file under Assets Folder/file.xml 5 Modify AndroidManifest.xml to add necessary internet permission 6 Run the application and choose a running android device and install the application on it and verify the results Following is the content of the modified main activity file MainActivity.java. package com.example.sairamkrishna.myapplication; import java.io.InputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends Activity { TextView tv1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv1=(TextView)findViewById(R.id.textView1); try { InputStream is = getAssets().open(“file.xml”); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(is); Element element=doc.getDocumentElement(); element.normalize(); NodeList nList = doc.getElementsByTagName(“employee”); for (int i=0; i<nList.getLength(); i++) { Node node = nList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element2 = (Element) node; tv1.setText(tv1.getText()+”nName : ” + getValue(“name”, element2)+”n”); tv1.setText(tv1.getText()+”Surname : ” + getValue(“surname”, element2)+”n”); tv1.setText(tv1.getText()+”———————–“); } } } catch (Exception e) {e.printStackTrace();} } private static String getValue(String tag, Element element) { NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes(); Node node = nodeList.item(0); return node.getNodeValue(); } } Following is the content of Assets/file.xml. <?xml version=”1.0″?> <records> <employee> <name>Sairamkrishna</name> <surname>Mammahe</surname> <salary>50000</salary> </employee> <employee> <name>Gopal </name> <surname>Varma</surname> <salary>60000</salary> </employee> <employee> <name>Raja</name> <surname>Hr</surname> <salary>70000</salary> </employee> </records> Following is the modified content of the xml res/layout/activity_main.xml. <?xml version=”1.0″ encoding=”utf-8″?> <RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android” xmlns:tools=”http://schemas.android.com/tools” android:layout_width=”match_parent” android:layout_height=”match_parent” android:paddingBottom=”@dimen/activity_vertical_margin” android:paddingLeft=”@dimen/activity_horizontal_margin” android:paddingRight=”@dimen/activity_horizontal_margin” android:paddingTop=”@dimen/activity_vertical_margin” tools:context=”.MainActivity”> <TextView android:id=”@+id/textView1″ android:layout_width=”wrap_content” android:layout_height=”wrap_content” /> </RelativeLayout> Following is the content of AndroidManifest.xml file. <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.example.sairamkrishna.myapplication” > <application android:allowBackup=”true” android:icon=”@mipmap/ic_launcher” android:label=”@string/app_name” android:theme=”@style/AppTheme” > <activity android:name=”.MainActivity” android:label=”@string/app_name” > <intent-filter> <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> </application> </manifest> Let”s try to run our application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project”s activity files and click Run icon from the

Publishing Android Application

Publishing Android Application ”; Previous Next Android application publishing is a process that makes your Android applications available to users. Infect, publishing is the last phase of the Android application development process. Android development life cycle Once you developed and fully tested your Android Application, you can start selling or distributing free using Google Play (A famous Android marketplace). You can also release your applications by sending them directly to users or by letting users download them from your own website. You can check a detailed publishing process at Android official website, but this tutorial will take you through simple steps to launch your application on Google Play. Here is a simplified check list which will help you in launching your Android application − Step Activity 1 Regression Testing Before you publish your application, you need to make sure that its meeting the basic quality expectations for all Android apps, on all of the devices that you are targeting. So perform all the required testing on different devices including phone and tablets. 2 Application Rating When you will publish your application at Google Play, you will have to specify a content rating for your app, which informs Google Play users of its maturity level. Currently available ratings are (a) Everyone (b) Low maturity (c) Medium maturity (d) High maturity. 3 Targeted Regions Google Play lets you control what countries and territories where your application will be sold. Accordingly you must take care of setting up time zone, localization or any other specific requirement as per the targeted region. 4 Application Size Currently, the maximum size for an APK published on Google Play is 50 MB. If your app exceeds that size, or if you want to offer a secondary download, you can use APK Expansion Files, which Google Play will host for free on its server infrastructure and automatically handle the download to devices. 5 SDK and Screen Compatibility It is important to make sure that your app is designed to run properly on the Android platform versions and device screen sizes that you want to target. 6 Application Pricing Deciding whether you app will be free or paid is important because, on Google Play, free app”s must remain free. If you want to sell your application then you will have to specify its price in different currencies. 7 Promotional Content It is a good marketing practice to supply a variety of high-quality graphic assets to showcase your app or brand. After you publish, these appear on your product details page, in store listings and search results, and elsewhere. 8 Build and Upload release-ready APK The release-ready APK is what you you will upload to the Developer Console and distribute to users. You can check complete detail on how to create a release-ready version of your app: Preparing for Release. 9 Finalize Application Detail Google Play gives you a variety of ways to promote your app and engage with users on your product details page, from colourful graphics, screen shots, and videos to localized descriptions, release details, and links to your other apps. So you can decorate your application page and provide as much as clear crisp detail you can provide. Export Android Application Process Apk development process Before exporting the apps, you must some of tools Dx tools(Dalvik executable tools ): It going to convert .class file to .dex file. it has useful for memory optimization and reduce the boot-up speed time AAPT(Android assistance packaging tool):it has useful to convert .Dex file to.Apk APK(Android packaging kit): The final stage of deployment process is called as .apk. You will need to export your application as an APK (Android Package) file before you upload it Google Play marketplace. To export an application, just open that application project in Android studio and select Build → Generate Signed APK from your Android studio and follow the simple steps to export your application − Next select, Generate Signed APK option as shown in the above screen shot and then click it so that you get following screen where you will choose Create new keystore to store your application. Enter your key store path,key store password,key alias and key password to protect your application and click on Next button once again. It will display following screen to let you create an application − Once you filled up all the information,like app destination,build type and flavours click finish button While creating an application it will show as below Finally, it will generate your Android Application as APK formate File which will be uploaded at Google Play marketplace. Google Play Registration The most important step is to register with Google Play using Google Play Marketplace. You can use your existing google ID if you have any otherwise you can create a new Google ID and then register with the marketplace. You will have following screen to accept terms and condition. You can use Continue to payment button to proceed to make a payment of $25 as a registration fee and finally to complete your account detail. Once you are a registered user at Google Play, you can upload release-ready APK for your application and finally you will complete application detail using application detail page as mentioned in step 9 of the above mentioned checklist. Signing Your App Manually You do not need Android Studio to sign your app. You can sign your app from the command line using standard tools from the Android SDK and the JDK. To sign an app in release mode from the command line − Generate a private key using keytool $ keytool -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000 Compile your app in release mode to obtain an unsigned APK Sign your app with your private key using jarsigner $ jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.keystore my_application.apk alias_name Verify that your APK is signed. For example − $ jarsigner -verify -verbose -certs my_application.apk Align the final APK package using zipalign. $

Android – Network Connection

Android – Network Connection ”; Previous Next Android lets your application connect to the internet or any other local network and allows you to perform network operations. A device can have various types of network connections. This chapter focuses on using either a Wi-Fi or a mobile network connection. Checking Network Connection Before you perform any network operations, you must first check that are you connected to that network or internet e.t.c. For this android provides ConnectivityManager class. You need to instantiate an object of this class by calling getSystemService() method. Its syntax is given below − ConnectivityManager check = (ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE); Once you instantiate the object of ConnectivityManager class, you can use getAllNetworkInfo method to get the information of all the networks. This method returns an array of NetworkInfo. So you have to receive it like this. NetworkInfo[] info = check.getAllNetworkInfo(); The last thing you need to do is to check Connected State of the network. Its syntax is given below − for (int i = 0; i<info.length; i++){ if (info[i].getState() == NetworkInfo.State.CONNECTED){ Toast.makeText(context, “Internet is connected Toast.LENGTH_SHORT).show(); } } Apart from this connected states, there are other states a network can achieve. They are listed below − Sr.No State 1 Connecting 2 Disconnected 3 Disconnecting 4 Suspended 5 Unknown Performing Network Operations After checking that you are connected to the internet, you can perform any network operation. Here we are fetching the html of a website from a url. Android provides HttpURLConnection and URL class to handle these operations. You need to instantiate an object of URL class by providing the link of website. Its syntax is as follows − String link = “http://www.google.com”; URL url = new URL(link); After that you need to call openConnection method of url class and receive it in a HttpURLConnection object. After that you need to call the connect method of HttpURLConnection class. HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); And the last thing you need to do is to fetch the HTML from the website. For this you will use InputStream and BufferedReader class. Its syntax is given below − InputStream is = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is, “UTF-8”)); String webPage = “”,data=””; while ((data = reader.readLine()) != null){ webPage += data + “n”; } Apart from this connect method, there are other methods available in HttpURLConnection class. They are listed below − Sr.No Method & description 1 disconnect() This method releases this connection so that its resources may be either reused or closed 2 getRequestMethod() This method returns the request method which will be used to make the request to the remote HTTP server 3 getResponseCode() This method returns response code returned by the remote HTTP server 4 setRequestMethod(String method) This method Sets the request command which will be sent to the remote HTTP server 5 usingProxy() This method returns whether this connection uses a proxy server or not Example The below example demonstrates the use of HttpURLConnection class. It creates a basic application that allows you to download HTML from a given web page. To experiment with this example, you need to run this on an actual device on which wifi internet is connected . Steps Description 1 You will use Android studio IDE to create an Android application under a package com.tutorialspoint.myapplication. 2 Modify src/MainActivity.java file to add Activity code. 4 Modify layout XML file res/layout/activity_main.xml add any GUI component if required. 6 Modify AndroidManifest.xml to add necessary permissions. 7 Run the application and choose a running android device and install the application on it and verify the results. Here is the content of src/MainActivity.java. package com.tutorialspoint.myapplication; import android.app.ProgressDialog; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.ConnectivityManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class MainActivity extends ActionBarActivity { private ProgressDialog progressDialog; private Bitmap bitmap = null; Button b1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1 = (Button) findViewById(R.id.button); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { checkInternetConenction(); downloadImage(“https://www.tutorialspoint.com/green/images/logo.png”); } }); } private void downloadImage(String urlStr) { progressDialog = ProgressDialog.show(this, “”, “Downloading Image from ” + urlStr); final String url = urlStr; new Thread() { public void run() { InputStream in = null; Message msg = Message.obtain(); msg.what = 1; try { in = openHttpConnection(url); bitmap = BitmapFactory.decodeStream(in); Bundle b = new Bundle(); b.putParcelable(“bitmap”, bitmap); msg.setData(b); in.close(); }catch (IOException e1) { e1.printStackTrace(); } messageHandler.sendMessage(msg); } }.start(); } private InputStream openHttpConnection(String urlStr) { InputStream in = null; int resCode = -1; try { URL url = new URL(urlStr); URLConnection urlConn = url.openConnection(); if (!(urlConn instanceof HttpURLConnection)) { throw new IOException(“URL is not an Http URL”); } HttpURLConnection httpConn = (HttpURLConnection) urlConn; httpConn.setAllowUserInteraction(false); httpConn.setInstanceFollowRedirects(true); httpConn.setRequestMethod(“GET”); httpConn.connect(); resCode = httpConn.getResponseCode(); if (resCode == HttpURLConnection.HTTP_OK) { in = httpConn.getInputStream(); } }catch (MalformedURLException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); } return in; } private Handler messageHandler = new Handler() { public void handleMessage(Message msg) { super.handleMessage(msg); ImageView img = (ImageView) findViewById(R.id.imageView); img.setImageBitmap((Bitmap) (msg.getData().getParcelable(“bitmap”))); progressDialog.dismiss(); } }; private boolean checkInternetConenction() { // get Connectivity Manager object to check connection ConnectivityManager connec =(ConnectivityManager)getSystemService(getBaseContext().CONNECTIVITY_SERVICE); // Check for network connections if ( connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED || connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING || connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING || connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED ) { Toast.makeText(this, ” Connected “, Toast.LENGTH_LONG).show(); return true; }else if ( connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED || connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED ) { Toast.makeText(this, ” Not Connected “, Toast.LENGTH_LONG).show(); return false; } return false; } } Here is the content of activity_main.xml. <?xml version=”1.0″ encoding=”utf-8″?> <RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android” xmlns:tools=”http://schemas.android.com/tools” android:layout_width=”match_parent” android:layout_height=”match_parent” android:paddingLeft=”@dimen/activity_horizontal_margin” android:paddingRight=”@dimen/activity_horizontal_margin” android:paddingTop=”@dimen/activity_vertical_margin” android:paddingBottom=”@dimen/activity_vertical_margin” tools:context=”.MainActivity”> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”UI Animator Viewer” android:id=”@+id/textView” android:textSize=”25sp” android:layout_centerHorizontal=”true” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Tutorials point” android:id=”@+id/textView2″ android:layout_below=”@+id/textView” android:layout_alignRight=”@+id/textView” android:layout_alignEnd=”@+id/textView” android:textColor=”#ff36ff15″ android:textIsSelectable=”false” android:textSize=”35dp” /> <ImageView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/imageView” android:layout_below=”@+id/textView2″ android:layout_centerHorizontal=”true” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Button” android:id=”@+id/button” android:layout_below=”@+id/imageView” android:layout_centerHorizontal=”true” android:layout_marginTop=”76dp” /> </RelativeLayout> Here is the content of Strings.xml. <resources> <string name=”app_name”>My Application</string> </resources> Here is the content of AndroidManifest.xml <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.tutorialspoint.myapplication” > <uses-permission android:name=”android.permission.INTERNET”></uses-permission> <uses-permission

Android – Clipboard

Android – Clipboard ”; Previous Next Android provides the clipboard framework for copying and pasting different types of data. The data could be text, images, binary stream data or other complex data types. Android provides the library of ClipboardManager and ClipData and ClipData.item to use the copying and pasting framework.In order to use clipboard framework, you need to put data into clip object, and then put that object into system wide clipboard. In order to use clipboard , you need to instantiate an object of ClipboardManager by calling the getSystemService() method. Its syntax is given below − ClipboardManager myClipboard; myClipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE); Copying data The next thing you need to do is to instantiate the ClipData object by calling the respective type of data method of the ClipData class. In case of text data , the newPlainText method will be called. After that you have to set that data as the clip of the Clipboard Manager object.Its syntax is given below − ClipData myClip; String text = “hello world”; myClip = ClipData.newPlainText(“text”, text); myClipboard.setPrimaryClip(myClip); The ClipData object can take these three form and following functions are used to create those forms. Sr.No ClipData Form & Method 1 Text newPlainText(label, text) Returns a ClipData object whose single ClipData.Item object contains a text string. 2 URI newUri(resolver, label, URI) Returns a ClipData object whose single ClipData.Item object contains a URI. 3 Intent newIntent(label, intent) Returns a ClipData object whose single ClipData.Item object contains an Intent. Pasting data In order to paste the data, we will first get the clip by calling the getPrimaryClip() method. And from that click we will get the item in ClipData.Item object. And from the object we will get the data. Its syntax is given below − ClipData abc = myClipboard.getPrimaryClip(); ClipData.Item item = abc.getItemAt(0); String text = item.getText().toString(); Apart from the these methods , there are other methods provided by the ClipboardManager class for managing clipboard framework. These methods are listed below − Sr.No Method & description 1 getPrimaryClip() This method just returns the current primary clip on the clipboard 2 getPrimaryClipDescription() This method returns a description of the current primary clip on the clipboard but not a copy of its data. 3 hasPrimaryClip() This method returns true if there is currently a primary clip on the clipboard 4 setPrimaryClip(ClipData clip) This method sets the current primary clip on the clipboard 5 setText(CharSequence text) This method can be directly used to copy text into the clipboard 6 getText() This method can be directly used to get the copied text from the clipboard Example Here is an example demonstrating the use of ClipboardManager class. It creates a basic copy paste application that allows you to copy the text and then paste it via clipboard. To experiment with this example , you can run this on an actual device or in an emulator. Steps Description 1 You will use Android studio IDE to create an Android application and under a package com.example.sairamkrishna.myapplication. 2 Modify src/MainActivity.java file to add necessary code. 3 Modify the res/layout/activity_main to add respective XML components 4 Run the application and choose a running android device and install the application on it and verify the results Following is the content of the modified main activity file src/MainActivity.java. package com.example.sairamkrishna.myapplication; import android.content.ClipData; import android.content.ClipboardManager; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends ActionBarActivity { EditText ed1, ed2; Button b1, b2; private ClipboardManager myClipboard; private ClipData myClip; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ed1 = (EditText) findViewById(R.id.editText); ed2 = (EditText) findViewById(R.id.editText2); b1 = (Button) findViewById(R.id.button); b2 = (Button) findViewById(R.id.button2); myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String text; text = ed1.getText().toString(); myClip = ClipData.newPlainText(“text”, text); myClipboard.setPrimaryClip(myClip); Toast.makeText(getApplicationContext(), “Text Copied”, Toast.LENGTH_SHORT).show(); } }); b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ClipData abc = myClipboard.getPrimaryClip(); ClipData.Item item = abc.getItemAt(0); String text = item.getText().toString(); ed2.setText(text); Toast.makeText(getApplicationContext(), “Text Pasted”, Toast.LENGTH_SHORT).show(); } }); } } Following is the modified content of the xml res/layout/activity_main.xml. <?xml version=”1.0″ encoding=”utf-8″?> <RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android” xmlns:tools=”http://schemas.android.com/tools” android:layout_width=”match_parent” android:layout_height=”match_parent” android:paddingLeft=”@dimen/activity_horizontal_margin” android:paddingRight=”@dimen/activity_horizontal_margin” android:paddingTop=”@dimen/activity_vertical_margin” android:paddingBottom=”@dimen/activity_vertical_margin” tools:context=”.MainActivity”> <TextView android:text=”Example” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/textview” android:textSize=”35dp” android:layout_alignParentTop=”true” android:layout_centerHorizontal=”true” /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Tutorials point” android:id=”@+id/textView” android:layout_below=”@+id/textview” android:layout_centerHorizontal=”true” android:textColor=”#ff7aff24″ android:textSize=”35dp” /> <ImageView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/imageView” android:src=”@drawable/abc” android:layout_below=”@+id/textView” android:layout_centerHorizontal=”true” /> <EditText android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/editText” android:layout_alignParentRight=”true” android:layout_alignParentEnd=”true” android:hint=”Copy text” android:layout_below=”@+id/imageView” android:layout_alignLeft=”@+id/imageView” android:layout_alignStart=”@+id/imageView” /> <EditText android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/editText2″ android:layout_alignLeft=”@+id/editText” android:layout_alignStart=”@+id/editText” android:hint=”paste text” android:layout_below=”@+id/editText” android:layout_alignRight=”@+id/editText” android:layout_alignEnd=”@+id/editText” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Copy text” android:id=”@+id/button” android:layout_below=”@+id/editText2″ android:layout_alignLeft=”@+id/editText2″ android:layout_alignStart=”@+id/editText2″ /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Paste text” android:id=”@+id/button2″ android:layout_below=”@+id/editText2″ android:layout_alignRight=”@+id/editText2″ android:layout_alignEnd=”@+id/editText2″ /> </RelativeLayout> Following is the content of the res/values/string.xml. <resources> <string name=”app_name”>My Application</string> </resources> Following is the content of AndroidManifest.xml file. <?xml version=”1.0″ encoding=”utf-8″?> <manifest xmlns:android=”http://schemas.android.com/apk/res/android” package=”com.example.sairamkrishna.myapplication” > <application android:allowBackup=”true” android:icon=”@drawable/ic_launcher” android:label=”@string/app_name” android:theme=”@style/AppTheme” > <activity android:name=”com.example.sairamkrishna.myapplication.MainActivity” android:label=”@string/app_name” > <intent-filter> <action android:name=”android.intent.action.MAIN” /> <category android:name=”android.intent.category.LAUNCHER” /> </intent-filter> </activity> </application> </manifest> Let”s try to run our an application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project”s activity files and click Run icon from the tool bar. Android studio installer will display following images − Now just enter any text in the Text to copy field and then select the copy text button. The following notification will be displayed which is shown below − Now just press the paste button, and you will see the text which is copied is now pasted in the field of Copied Text. It is shown below − Print Page Previous Next Advertisements ”;