Android – Widgets ”; Previous Next A widget is a small gadget or control of your android application placed on the home screen. Widgets can be very handy as they allow you to put your favourite applications on your home screen in order to quickly access them. You have probably seen some common widgets, such as music widget, weather widget, clock widget e.t.c Widgets could be of many types such as information widgets, collection widgets, control widgets and hybrid widgets. Android provides us a complete framework to develop our own widgets. Widget – XML file In order to create an application widget, first thing you need is AppWidgetProviderInfo object, which you will define in a separate widget XML file. In order to do that, right click on your project and create a new folder called xml. Now right click on the newly created folder and create a new XML file. The resource type of the XML file should be set to AppWidgetProvider. In the xml file, define some properties which are as follows − <appwidget-provider xmlns:android=”http://schemas.android.com/apk/res/android” android:minWidth=”146dp” android:updatePeriodMillis=”0″ android:minHeight=”146dp” android:initialLayout=”@layout/activity_main”> </appwidget-provider> Widget – Layout file Now you have to define the layout of your widget in your default XML file. You can drag components to generate auto xml. Widget – Java file After defining layout, now create a new JAVA file or use existing one, and extend it with AppWidgetProvider class and override its update method as follows. In the update method, you have to define the object of two classes which are PendingIntent and RemoteViews. Its syntax is − PendingIntent pending = PendingIntent.getActivity(context, 0, intent, 0); RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.activity_main); In the end you have to call an update method updateAppWidget() of the AppWidgetManager class. Its syntax is − appWidgetManager.updateAppWidget(currentWidgetId,views); A part from the updateAppWidget method, there are other methods defined in this class to manipulate widgets. They are as follows − Sr.No Method & Description 1 onDeleted(Context context, int[] appWidgetIds) This is called when an instance of AppWidgetProvider is deleted. 2 onDisabled(Context context) This is called when the last instance of AppWidgetProvider is deleted 3 onEnabled(Context context) This is called when an instance of AppWidgetProvider is created. 4 onReceive(Context context, Intent intent) It is used to dispatch calls to the various methods of the class Widget – Manifest file You also have to declare the AppWidgetProvider class in your manifest file as follows: <receiver android:name=”ExampleAppWidgetProvider” > <intent-filter> <action android:name=”android.appwidget.action.APPWIDGET_UPDATE” /> </intent-filter> <meta-data android:name=”android.appwidget.provider” android:resource=”@xml/example_appwidget_info” /> </receiver> Example Here is an example demonstrating the use of application Widget. It creates a basic widget applications that will open this current website in the browser. To experiment with this example, you need to run this on an actual device on which internet is running. 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 widget code. 3 Modify the res/layout/activity_main to add respective XML components 4 Create a new folder and xml file under res/xml/mywidget.xml to add respective XML components 5 Modify the AndroidManifest.xml to add the necessary permissions 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 MainActivity.java. package com.example.sairamkrishna.myapplication; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.widget.RemoteViews; import android.widget.Toast; public class MainActivity extends AppWidgetProvider{ public void onUpdate(Context context, AppWidgetManager appWidgetManager,int[] appWidgetIds) { for(int i=0; i<appWidgetIds.length; i++){ int currentWidgetId = appWidgetIds[i]; String url = “https://www.tutorialspoint.com”; Intent intent = new Intent(Intent.ACTION_VIEW); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setData(Uri.parse(url)); PendingIntent pending = PendingIntent.getActivity(context, 0,intent, 0); RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.activity_main); views.setOnClickPendingIntent(R.id.button, pending); appWidgetManager.updateAppWidget(currentWidgetId,views); Toast.makeText(context, “widget added”, 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” android:transitionGroup=”true”> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Tutorials point” android:id=”@+id/textView” android:layout_centerHorizontal=”true” android:textColor=”#ff3412ff” android:textSize=”35dp” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Widget” android:id=”@+id/button” android:layout_centerHorizontal=”true” android:layout_marginTop=”61dp” android:layout_below=”@+id/textView” /> </RelativeLayout> Following is the content of the res/xml/mywidget.xml. <?xml version=”1.0″ encoding=”utf-8″?> <appwidget-provider xmlns:android=”http://schemas.android.com/apk/res/android” android:minWidth=”146dp” android:updatePeriodMillis=”0″ android:minHeight=”146dp” android:initialLayout=”@layout/activity_main”> </appwidget-provider> 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=”@mipmap/ic_launcher” android:label=”@string/app_name” android:theme=”@style/AppTheme” > <receiver android:name=”.MainActivity”> <intent-filter> <action android:name=”android.appwidget.action.APPWIDGET_UPDATE”></action> </intent-filter> <meta-data android:name=”android.appwidget.provider” android:resource=”@xml/mywidget”></meta-data> </receiver> </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 tool bar. 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 − Go to your widget section and add your created widget to the desktop or home screen. It would look something like this − Now just tap on the widget button that appears, to launch the browser. But before that please make sure that you are connected to the internet. After pressing the button , the following screen would appear − Note. By just changing the url in the java file, your widget will open your desired website in the browser. Print Page Previous Next Advertisements ”;
Category: Android
Android – Text to Speech
Android – Text To Speech ”; Previous Next Android allows you convert your text into voice. Not only you can convert it but it also allows you to speak text in variety of different languages. Android provides TextToSpeech class for this purpose. In order to use this class, you need to instantiate an object of this class and also specify the initListener. Its syntax is given below − private EditText write; ttobj=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { } }); In this listener, you have to specify the properties for TextToSpeech object , such as its language ,pitch e.t.c. Language can be set by calling setLanguage() method. Its syntax is given below − ttobj.setLanguage(Locale.UK); The method setLanguage takes an Locale object as parameter. The list of some of the locales available are given below − Sr.No Locale 1 US 2 CANADA_FRENCH 3 GERMANY 4 ITALY 5 JAPAN 6 CHINA Once you have set the language, you can call speak method of the class to speak the text. Its syntax is given below − ttobj.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); Apart from the speak method, there are some other methods available in the TextToSpeech class. They are listed below − Sr.No Method & description 1 addSpeech(String text, String filename) This method adds a mapping between a string of text and a sound file. 2 getLanguage() This method returns a Locale instance describing the language. 3 isSpeaking() This method checks whether the TextToSpeech engine is busy speaking. 4 setPitch(float pitch) This method sets the speech pitch for the TextToSpeech engine. 5 setSpeechRate(float speechRate) This method sets the speech rate. 6 shutdown() This method releases the resources used by the TextToSpeech engine. 7 stop() This method stop the speak. Example The below example demonstrates the use of TextToSpeech class. It crates a basic application that allows you to set write text and speak it. To experiment with this example , you need to run this on an actual device. 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 TextToSpeech code. 3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required. 4 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.app.Activity; import android.os.Bundle; import android.speech.tts.TextToSpeech; import android.view.View; import android.widget.Button; import android.widget.EditText; import java.util.Locale; import android.widget.Toast; public class MainActivity extends Activity { TextToSpeech t1; EditText ed1; Button b1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ed1=(EditText)findViewById(R.id.editText); b1=(Button)findViewById(R.id.button); t1=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { if(status != TextToSpeech.ERROR) { t1.setLanguage(Locale.UK); } } }); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String toSpeak = ed1.getText().toString(); Toast.makeText(getApplicationContext(), toSpeak,Toast.LENGTH_SHORT).show(); t1.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); } }); } public void onPause(){ if(t1 !=null){ t1.stop(); t1.shutdown(); } super.onPause(); } } Here is the content of activity_main.xml In the following code abcindicates 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” android:transitionGroup=”true”> <TextView android:text=”Text to Speech” 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” android:theme=”@style/Base.TextAppearance.AppCompat” /> <EditText android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/editText” android:layout_below=”@+id/imageView” android:layout_marginTop=”46dp” android:hint=”Enter Text” android:layout_alignParentRight=”true” android:layout_alignParentEnd=”true” android:layout_alignParentLeft=”true” android:layout_alignParentStart=”true” android:textColor=”#ff7aff10″ android:textColorHint=”#ffff23d1″ /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Text to Speech” android:id=”@+id/button” android:layout_below=”@+id/editText” android:layout_centerHorizontal=”true” android:layout_marginTop=”46dp” /> </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” > <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 following screen. Now just type some text in the field and click on the text to speech button below. A notification would appear and text will be spoken. It is shown in the image below − Now type something else and repeat the step again with different locale. You will again hear sound. This is shown below − Print Page Previous Next Advertisements ”;
Android – RSS Reader
Android – RSS Reader ”; Previous Next RSS stands for Really Simple Syndication. RSS is an easy way to share your website updates and content with your users so that users might not have to visit your site daily for any kind of updates. RSS Example RSS is a document that is created by the website with .xml extension. You can easily parse this document and show it to the user in your application. An RSS document looks like this. <rss version=”2.0″> <channel> <title>Sample RSS</title> <link>http://www.google.com</link> <description>World”s best search engine</description> </channel> </rss> RSS Elements An RSS document such as above has the following elements. Sr.No Component & description 1 channel This element is used to describe the RSS feed 2 title Defines the title of the channel 3 link Defines the hyper link to the channel 4 description Describes the channel Parsing RSS Parsing an RSS document is more like parsing XML. So now lets see how to parse an XML document. For this, 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 white space characters. Example Here is an example demonstrating the use of XMLPullParser class. It creates a basic Parsing application that allows you to parse an RSS document present here at /android/sampleXML.xml and then show the result. 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 java file under src/HandleXML.java to fetch and parse XML data. 5 Create a new java file under src/second.java to display result of 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 src/MainActivity.java. package com.example.sairamkrishna.myapplication; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity { EditText title,link,description; Button b1,b2; private String finalUrl=”https://www.tutorialspoint.com/android/sampleXML.xml”; private HandleXML obj; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); title = (EditText) findViewById(R.id.editText); link = (EditText) findViewById(R.id.editText2); description = (EditText) findViewById(R.id.editText3); b1=(Button)findViewById(R.id.button); b2=(Button)findViewById(R.id.button2); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { obj = new HandleXML(finalUrl); obj.fetchXML(); while(obj.parsingComplete); title.setText(obj.getTitle()); link.setText(obj.getLink()); description.setText(obj.getDescription()); } }); b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent in=new Intent(MainActivity.this,second.class); startActivity(in); } }); } } Following is the content of the java file src/HandleXML.java. package com.example.rssreader; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; import android.util.Log; public class HandleXML { private String title = “title”; private String link = “link”; private String description = “description”; private String urlString = null; private XmlPullParserFactory xmlFactoryObject; public volatile boolean parsingComplete = true; public HandleXML(String url){ this.urlString = url; } public String getTitle(){ return title; } public String getLink(){ return link; } public String getDescription(){ return description; } public void parseXMLAndStoreIt(XmlPullParser myParser) { int event; String text=null; try { event = myParser.getEventType(); while (event != XmlPullParser.END_DOCUMENT) { String name=myParser.getName(); switch (event){ case XmlPullParser.START_TAG: break; case XmlPullParser.TEXT: text = myParser.getText(); break; case XmlPullParser.END_TAG: if(name.equals(“title”)){ title = text; } else if(name.equals(“link”)){ link = text; } else if(name.equals(“description”)){ description = text; } else{ } break; } event = myParser.next(); } parsingComplete = false; } catch (Exception e) { e.printStackTrace(); } } public void fetchXML(){ Thread thread = new Thread(new Runnable(){ @Override public void run() { try { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod(“GET”); conn.setDoInput(true); // Starts the query conn.connect(); InputStream stream = conn.getInputStream(); xmlFactoryObject = XmlPullParserFactory.newInstance(); XmlPullParser myparser = xmlFactoryObject.newPullParser(); myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); myparser.setInput(stream, null); parseXMLAndStoreIt(myparser); stream.close(); } catch (Exception e) { } } }); thread.start(); } } Create a file and named as second.java
Android – Bluetooth
Android – Bluetooth ”; Previous Next Among many ways, Bluetooth is a way to send or receive data between two different devices. Android platform includes support for the Bluetooth framework that allows a device to wirelessly exchange data with other Bluetooth devices. Android provides Bluetooth API to perform these different operations. Scan for other Bluetooth devices Get a list of paired devices Connect to other devices through service discovery Android provides BluetoothAdapter class to communicate with Bluetooth. Create an object of this calling by calling the static method getDefaultAdapter(). Its syntax is given below. private BluetoothAdapter BA; BA = BluetoothAdapter.getDefaultAdapter(); In order to enable the Bluetooth of your device, call the intent with the following Bluetooth constant ACTION_REQUEST_ENABLE. Its syntax is. Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(turnOn, 0); Apart from this constant, there are other constants provided the API , that supports different tasks. They are listed below. Sr.No Constant & description 1 ACTION_REQUEST_DISCOVERABLE This constant is used for turn on discovering of bluetooth 2 ACTION_STATE_CHANGED This constant will notify that Bluetooth state has been changed 3 ACTION_FOUND This constant is used for receiving information about each device that is discovered Once you enable the Bluetooth , you can get a list of paired devices by calling getBondedDevices() method. It returns a set of bluetooth devices. Its syntax is. private Set<BluetoothDevice>pairedDevices; pairedDevices = BA.getBondedDevices(); Apart form the parried Devices , there are other methods in the API that gives more control over Blueetooth. They are listed below. Sr.No Method & description 1 enable() This method enables the adapter if not enabled 2 isEnabled() This method returns true if adapter is enabled 3 disable() This method disables the adapter 4 getName() This method returns the name of the Bluetooth adapter 5 setName(String name) This method changes the Bluetooth name 6 getState() This method returns the current state of the Bluetooth Adapter. 7 startDiscovery() This method starts the discovery process of the Bluetooth for 120 seconds. Example This example provides demonstration of BluetoothAdapter class to manipulate Bluetooth and show list of paired devices by the Bluetooth. To experiment with this example , you need to run this on an actual device. Steps Description 1 You will use Android studio to create an Android application a package com.example.sairamkrishna.myapplication. 2 Modify src/MainActivity.java file to add the 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.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.Set; public class MainActivity extends Activity { Button b1,b2,b3,b4; private BluetoothAdapter BA; private Set<BluetoothDevice>pairedDevices; ListView lv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1 = (Button) findViewById(R.id.button); b2=(Button)findViewById(R.id.button2); b3=(Button)findViewById(R.id.button3); b4=(Button)findViewById(R.id.button4); BA = BluetoothAdapter.getDefaultAdapter(); lv = (ListView)findViewById(R.id.listView); } public void on(View v){ if (!BA.isEnabled()) { Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(turnOn, 0); Toast.makeText(getApplicationContext(), “Turned on”,Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), “Already on”, Toast.LENGTH_LONG).show(); } } public void off(View v){ BA.disable(); Toast.makeText(getApplicationContext(), “Turned off” ,Toast.LENGTH_LONG).show(); } public void visible(View v){ Intent getVisible = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); startActivityForResult(getVisible, 0); } public void list(View v){ pairedDevices = BA.getBondedDevices(); ArrayList list = new ArrayList(); for(BluetoothDevice bt : pairedDevices) list.add(bt.getName()); Toast.makeText(getApplicationContext(), “Showing Paired Devices”,Toast.LENGTH_SHORT).show(); final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list); lv.setAdapter(adapter); } } Here is the content of activity_main.xml Here abc indicates about 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: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” android:transitionGroup=”true”> <TextView android:text=”Bluetooth 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” android:theme=”@style/Base.TextAppearance.AppCompat” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Turn On” android:id=”@+id/button” android:layout_below=”@+id/imageView” android:layout_toStartOf=”@+id/imageView” android:layout_toLeftOf=”@+id/imageView” android:clickable=”true” android:onClick=”on” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Get visible” android:onClick=”visible” android:id=”@+id/button2″ android:layout_alignBottom=”@+id/button” android:layout_centerHorizontal=”true” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”List devices” android:onClick=”list” android:id=”@+id/button3″ android:layout_below=”@+id/imageView” android:layout_toRightOf=”@+id/imageView” android:layout_toEndOf=”@+id/imageView” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”turn off” android:onClick=”off” android:id=”@+id/button4″ android:layout_below=”@+id/button” android:layout_alignParentLeft=”true” android:layout_alignParentStart=”true” /> <ListView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/listView” android:layout_alignParentBottom=”true” android:layout_alignLeft=”@+id/button” android:layout_alignStart=”@+id/button” android:layout_below=”@+id/textView2″ /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Paired devices:” android:id=”@+id/textView2″ android:textColor=”#ff34ff06″ android:textSize=”25dp” android:layout_below=”@+id/button4″ android:layout_alignLeft=”@+id/listView” android:layout_alignStart=”@+id/listView” /> </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.BLUETOOTH”/> <uses-permission android:name=”android.permission.BLUETOOTH_ADMIN”/> <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 tool bar.If your Bluetooth will not be turned on then, it will ask your permission to enable the Bluetooth. Now just select the Get Visible button to turn on your visibility. The following screen would appear asking your permission to turn on discovery for 120 seconds. Now just select the List Devices option. It will list down the paired devices in the list view. In my case , I have only one paired device. It is shown below. Now just select the Turn off button to switch off the Bluetooth. Following message would appear when you switch off the bluetooth indicating the successful switching off of Bluetooth. Print Page Previous Next Advertisements ”;
Android – Camera
Android – Camera ”; Previous Next These are the following two ways, in which you can use camera in your application Using existing android camera application in our application Directly using Camera API provided by android in our application Using existing android camera application in our application You will use MediaStore.ACTION_IMAGE_CAPTURE to launch an existing camera application installed on your phone. Its syntax is given below Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); Apart from the above, there are other available Intents provided by MediaStore. They are listed as follows Sr.No Intent type and description 1 ACTION_IMAGE_CAPTURE_SECURE It returns the image captured from the camera , when the device is secured 2 ACTION_VIDEO_CAPTURE It calls the existing video application in android to capture video 3 EXTRA_SCREEN_ORIENTATION It is used to set the orientation of the screen to vertical or landscape 4 EXTRA_FULL_SCREEN It is used to control the user interface of the ViewImage 5 INTENT_ACTION_VIDEO_CAMERA This intent is used to launch the camera in the video mode 6 EXTRA_SIZE_LIMIT It is used to specify the size limit of video or image capture size Now you will use the function startActivityForResult() to launch this activity and wait for its result. Its syntax is given below startActivityForResult(intent,0) This method has been defined in the activity class. We are calling it from main activity. There are methods defined in the activity class that does the same job , but used when you are not calling from the activity but from somewhere else. They are listed below Sr.No Activity function description 1 startActivityForResult(Intent intent, int requestCode, Bundle options) It starts an activity , but can take extra bundle of options with it 2 startActivityFromChild(Activity child, Intent intent, int requestCode) It launch the activity when your activity is child of any other activity 3 startActivityFromChild(Activity child, Intent intent, int requestCode, Bundle options) It work same as above , but it can take extra values in the shape of bundle with it 4 startActivityFromFragment(Fragment fragment, Intent intent, int requestCode) It launches activity from the fragment you are currently inside 5 startActivityFromFragment(Fragment fragment, Intent intent, int requestCode, Bundle options) It not only launches the activity from the fragment , but can take extra values with it No matter which function you used to launch the activity , they all return the result. The result can be obtained by overriding the function onActivityResult. Example Here is an example that shows how to launch the existing camera application to capture an image and display the result in the form of bitmap. To experiment with this example , you need to run this on an actual device on which camera is supported. Steps Description 1 You will use Android studio IDE to create an Android application and name it as Camera under a com.example.sairamkrishna.myapplication. 2 Modify src/MainActivity.java file to add intent code to launch the Camera. 3 Modify layout XML file res/layout/activity_main.xml 4 Add the Camera permission and 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.Manifest; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; public class MainActivity extends AppCompatActivity { public static final int MY_PERMISSIONS_REQUEST_CAMERA = 100; public static final String ALLOW_KEY = “ALLOWED”; public static final String CAMERA_PREF = “camera_pref”; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { if (getFromPref(this, ALLOW_KEY)) { showSettingsAlert(); } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { // Should we show an explanation? if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) { showAlert(); } else { // No explanation needed, we can request the permission. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMERA); } } } else { openCamera(); } } public static void saveToPreferences(Context context, String key, Boolean allowed) { SharedPreferences myPrefs = context.getSharedPreferences(CAMERA_PREF, Context.MODE_PRIVATE); SharedPreferences.Editor prefsEditor = myPrefs.edit(); prefsEditor.putBoolean(key, allowed); prefsEditor.commit(); } public static Boolean getFromPref(Context context, String key) { SharedPreferences myPrefs = context.getSharedPreferences(CAMERA_PREF, Context.MODE_PRIVATE); return (myPrefs.getBoolean(key, false)); } private void showAlert() { AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create(); alertDialog.setTitle(“Alert”); alertDialog.setMessage(“App needs to access the Camera.”); alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, “DONT ALLOW”, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); finish(); } }); alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, “ALLOW”, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMERA); } }); alertDialog.show(); } private void showSettingsAlert() { AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create(); alertDialog.setTitle(“Alert”); alertDialog.setMessage(“App needs to access the Camera.”); alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, “DONT ALLOW”, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); //finish(); } }); alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, “SETTINGS”, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); startInstalledAppDetailsActivity(MainActivity.this); } }); alertDialog.show(); } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_REQUEST_CAMERA: { for (int i = 0, len = permissions.length; i < len; i++) { String permission = permissions[i]; if (grantResults[i] == PackageManager.PERMISSION_DENIED) { boolean showRationale = ActivityCompat.shouldShowRequestPermissionRationale( this, permission); if (showRationale) { showAlert(); } else if (!showRationale) { // user denied flagging NEVER ASK AGAIN // you can either enable some fall back, // disable features of your app // or open another dialog explaining // again the permission and directing to // the app setting saveToPreferences(MainActivity.this, ALLOW_KEY, true); } } } } // other ”case” lines to check for other // permissions this app might request } } @Override protected void onResume() { super.onResume(); } public static void startInstalledAppDetailsActivity(final Activity context) { if (context == null) { return; } final Intent i = new Intent(); i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); i.addCategory(Intent.CATEGORY_DEFAULT); i.setData(Uri.parse(“package:” + context.getPackageName())); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); context.startActivity(i); } private void openCamera() { Intent intent = new Intent(“android.media.action.IMAGE_CAPTURE”); startActivity(intent); } } Following will be the content of res/layout/activity_main.xml file− <?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”> </RelativeLayout> Following will be the content of res/values/strings.xml to define one new constants <resources> <string name=”app_name”>My Application</string> </resources> Following is the default content of AndroidManifest.xml − <?xml version=”1.0″ encoding=”utf-8″?> <manifest
Android – Gestures
Android – Gestures ”; Previous Next Android provides special types of touch screen events such as pinch , double tap, scrolls , long presses and flinch. These are all known as gestures. Android provides GestureDetector class to receive motion events and tell us that these events correspond to gestures or not. To use it , you need to create an object of GestureDetector and then extend another class with GestureDetector.SimpleOnGestureListener to act as a listener and override some methods. Its syntax is given below − GestureDetector myG; myG = new GestureDetector(this,new Gesture()); class Gesture extends GestureDetector.SimpleOnGestureListener{ public boolean onSingleTapUp(MotionEvent ev) { } public void onLongPress(MotionEvent ev) { } public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { } public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { } } Handling Pinch Gesture Android provides ScaleGestureDetector class to handle gestures like pinch e.t.c. In order to use it, you need to instantiate an object of this class. Its syntax is as follow − ScaleGestureDetector SGD; SGD = new ScaleGestureDetector(this,new ScaleListener()); The first parameter is the context and the second parameter is the event listener. We have to define the event listener and override a function OnTouchEvent to make it working. Its syntax is given below − public boolean onTouchEvent(MotionEvent ev) { SGD.onTouchEvent(ev); return true; } private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener { @Override public boolean onScale(ScaleGestureDetector detector) { float scale = detector.getScaleFactor(); return true; } } Apart from the pinch gestures , there are other methods available that notify more about touch events. They are listed below − Sr.No Method & description 1 getEventTime() This method get the event time of the current event being processed.. 2 getFocusX() This method get the X coordinate of the current gesture”s focal point. 3 getFocusY() This method get the Y coordinate of the current gesture”s focal point. 4 getTimeDelta() This method return the time difference in milliseconds between the previous accepted scaling event and the current scaling event. 5 isInProgress() This method returns true if a scale gesture is in progress.. 6 onTouchEvent(MotionEvent event) This method accepts MotionEvents and dispatches events when appropriate. Example Here is an example demonstrating the use of ScaleGestureDetector class. It creates a basic application that allows you to zoom in and out through pinch. To experiment with this example , you can run this on an actual device or in an emulator with touch screen enabled. 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 main activity file src/MainActivity.java. package com.example.sairamkrishna.myapplication; import android.app.Activity; import android.graphics.Matrix; import android.os.Bundle; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.widget.ImageView; public class MainActivity extends Activity { private ImageView iv; private Matrix matrix = new Matrix(); private float scale = 1f; private ScaleGestureDetector SGD; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); iv=(ImageView)findViewById(R.id.imageView); SGD = new ScaleGestureDetector(this,new ScaleListener()); } public boolean onTouchEvent(MotionEvent ev) { SGD.onTouchEvent(ev); return true; } private class ScaleListener extends ScaleGestureDetector. SimpleOnScaleGestureListener { @Override public boolean onScale(ScaleGestureDetector detector) { scale *= detector.getScaleFactor(); scale = Math.max(0.1f, Math.min(scale, 5.0f)); matrix.setScale(scale, scale); iv.setImageMatrix(matrix); return true; } } } Following is the modified content of the xml res/layout/activity_main.xml. Here abc indicates the logo of tutorialspoint <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=”Gestures 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:scaleType=”matrix” android:layout_below=”@+id/textView” android:layout_alignParentLeft=”true” android:layout_alignParentStart=”true” android:layout_alignParentBottom=”true” android:layout_alignParentRight=”true” android:layout_alignParentEnd=”true” /> </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.myapplicationMainActivity” 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.The sample output should be like this − Now just place two fingers over android screen , and separate them a part and you will see that the android image is zooming. It is shown in the image below − Now again place two fingers over android screen, and try to close them and you will see that the android image is now shrinking. It is shown in the image below − Print Page Previous Next Advertisements ”;
Android – Multitouch
Android – Multitouch ”; Previous Next Multi-touch gesture happens when more than one finger touches the screen at the same time. Android allows us to detect these gestures. Android system generates the following touch events whenever multiple fingers touches the screen at the same time. Sr.No Event & description 1 ACTION_DOWN For the first pointer that touches the screen. This starts the gesture. 2 ACTION_POINTER_DOWN For extra pointers that enter the screen beyond the first. 3 ACTION_MOVE A change has happened during a press gesture. 4 ACTION_POINTER_UP Sent when a non-primary pointer goes up. 5 ACTION_UP Sent when the last pointer leaves the screen. So in order to detect any of the above mention event , you need to override onTouchEvent() method and check these events manually. Its syntax is given below − public boolean onTouchEvent(MotionEvent ev){ final int actionPeformed = ev.getAction(); switch(actionPeformed){ case MotionEvent.ACTION_DOWN:{ break; } case MotionEvent.ACTION_MOVE:{ break; } return true; } } In these cases, you can perform any calculation you like. For example zooming , shrinking e.t.c. In order to get the co-ordinates of the X and Y axis, you can call getX() and getY() method. Its syntax is given below − final float x = ev.getX(); final float y = ev.getY(); Apart from these methods, there are other methods provided by this MotionEvent class for better dealing with multitouch. These methods are listed below − Sr.No Method & description 1 getAction() This method returns the kind of action being performed 2 getPressure() This method returns the current pressure of this event for the first index 3 getRawX() This method returns the original raw X coordinate of this event 4 getRawY() This method returns the original raw Y coordinate of this event 5 getSize() This method returns the size for the first pointer index 6 getSource() This method gets the source of the event 7 getXPrecision() This method return the precision of the X coordinates being reported 8 getYPrecision() This method return the precision of the Y coordinates being reported Example Here is an example demonstrating the use of Multitouch. It creates a basic Multitouch gesture application that allows you to view the co-ordinates when multitouch is performed. To experiment with this example , you need to run this on an actual device. 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 multitouch 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.app.Activity; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends Activity { float xAxis = 0f; float yAxis = 0f; float lastXAxis = 0f; float lastYAxis = 0f; EditText ed1, ed2, ed3, ed4; TextView tv1; @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); ed3 = (EditText) findViewById(R.id.editText3); ed4 = (EditText) findViewById(R.id.editText4); tv1=(TextView)findViewById(R.id.textView2); tv1.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { final int actionPeformed = event.getAction(); switch(actionPeformed){ case MotionEvent.ACTION_DOWN:{ final float x = event.getX(); final float y = event.getY(); lastXAxis = x; lastYAxis = y; ed1.setText(Float.toString(lastXAxis)); ed2.setText(Float.toString(lastYAxis)); break; } case MotionEvent.ACTION_MOVE:{ final float x = event.getX(); final float y = event.getY(); final float dx = x – lastXAxis; final float dy = y – lastYAxis; xAxis += dx; yAxis += dy; ed3.setText(Float.toString(xAxis)); ed4.setText(Float.toString(yAxis)); break; } } return true; } }); } } Following is the modified content of the xml res/layout/activity_main.xml. In the below code abcindicates 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” android:transitionGroup=”true”> <TextView android:text=”Multitouch 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” android:theme=”@style/Base.TextAppearance.AppCompat” /> <EditText android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/editText” android:layout_below=”@+id/imageView” android:layout_alignRight=”@+id/textview” android:layout_alignEnd=”@+id/textview” android:hint=”X-Axis” android:layout_alignLeft=”@+id/textview” android:layout_alignStart=”@+id/textview” android:textColorHint=”#ff69ff0e” /> <EditText android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/editText2″ android:layout_below=”@+id/editText” android:layout_alignLeft=”@+id/editText” android:layout_alignStart=”@+id/editText” android:textColorHint=”#ff21ff11″ android:hint=”Y-Axis” android:layout_alignRight=”@+id/editText” android:layout_alignEnd=”@+id/editText” /> <EditText android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/editText3″ android:layout_below=”@+id/editText2″ android:layout_alignLeft=”@+id/editText2″ android:layout_alignStart=”@+id/editText2″ android:hint=”Move X” android:textColorHint=”#ff33ff20″ android:layout_alignRight=”@+id/editText2″ android:layout_alignEnd=”@+id/editText2″ /> <EditText android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:id=”@+id/editText4″ android:layout_below=”@+id/editText3″ android:layout_alignLeft=”@+id/editText3″ android:layout_alignStart=”@+id/editText3″ android:textColorHint=”#ff31ff07″ android:hint=”Move Y” android:layout_alignRight=”@+id/editText3″ android:layout_alignEnd=”@+id/editText3″ /> <TextView android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Touch here” android:id=”@+id/textView2″ android:layout_alignParentBottom=”true” android:layout_alignLeft=”@+id/imageView” android:layout_alignStart=”@+id/imageView” android:focusable=”true” android:typeface=”sans” android:clickable=”true” android:textColor=”#ff5480ff” android:textSize=”35dp” /> </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=”@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 − By default you will see nothing in any field. Now just tap on the Touch here area and see some data in the fields. It is shown below − You will see that the data in the Move field is 0, because only a single touch gesture has been performed. Now tap on the screen and start dragging your finger. You will see the change in the data of the move field. It is shown below − Print Page Previous Next Advertisements ”;
Android – SDK Manager
Android – SDK Manager ”; Previous Next To download and install latest android APIs and development tools from the internet, android provide us with android SDK manager. Android SDK Manager separates the APIs, tools and different platforms into different packages which you can download. Android SDK manager comes with the Android SDK bundle. You can”t download it separately. You can download the android sdk from here. Running Android SDK Manager Once downloaded, you can launch Android SDK Manager in one of the following ways − Click tools->Android-> SDK Manager option in Eclipse. Double Click on the SDK Manager.exe file in the Android SDK folder. When it runs you will see the following screen − You can select which package you want to download by selecting the checkbox and then click Install to install those packages. By default SDK Manager keeps it up to date with latest APIs and other packages. Once you download the SDK, following packages are available but first three are necessary to run your SDK and others are recommended. Recommended Packages Sr.No Package & Description 1 SDK Tools This is necessary package to run your SDK. 2 SDK Platform-tools This package will be installed once when you first run the SDK manager. 3 SDK Platform At least one platform must be installed in your environment to run your application. 4 System Image It”s a good practice to download system images for all of the android versions so you can test your app on them with the Android Emulator. 5 SDK Samples This will give you some sample codes to learn about android. Enabling Proxy in Android SDK Manager When you run the Android SDK Manager, by default it will check from the Android Repository and Third Party Add-ons and display the available packages to you. If you want to use proxy, you can do it by clicking on the Tools–>Optionsin the menu. Once you click it, you will see the following screen − Just Enter the proxy and run your SDK Manager. Adding New Third Party Sites If you want to download some Third Party made Android add-ons, you can do it in the SDK manager by following steps − Click on the Tools option in the menu. Click on the Manage Add-On Sites option in the sub menu. Select the User Defined Sites tab. Click the New button. Following screen will be displayed − Just add the URL of Add-on.xml file and click Ok. Now you can download the Third Party Add-on in your development environment and use it. Print Page Previous Next Advertisements ”;
Android – Image Effects
Android – Image Effects ”; Previous Next Android allows you to manipulate images by adding different kinds of effects on the images. You can easily apply image processing techniques to add certain kinds of effects on images. The effects could be brightness,darkness, grayscale conversion e.t.c. Android provides Bitmap class to handle images. This can be found under android.graphics.bitmap. There are many ways through which you can instantiate bitmap. We are creating a bitmap of image from the imageView. private Bitmap bmp; private ImageView img; img = (ImageView)findViewById(R.id.imageView1); BitmapDrawable abmp = (BitmapDrawable)img.getDrawable(); Now we will create bitmap by calling getBitmap() function of BitmapDrawable class. Its syntax is given below − bmp = abmp.getBitmap(); An image is nothing but a two dimensional matrix. Same way you will handle a bitmap. An image consist of pixels. So you will get pixels from this bitmap and apply processing to it. Its syntax is as follows − for(int i=0; i<bmp.getWidth(); i++){ for(int j=0; j<bmp.getHeight(); j++){ int p = bmp.getPixel(i, j); } } The getWidth() and getHeight() functions returns the height and width of the matrix. The getPixel() method returns the pixel at the specified index. Once you got the pixel, you can easily manipulate it according to your needs. Apart from these methods, there are other methods that helps us manipulate images more better. Sr.No Method & description 1 copy(Bitmap.Config config, boolean isMutable) This method copy this bitmap”s pixels into the new bitmap 2 createBitmap(DisplayMetrics display, int width, int height, Bitmap.Config config) Returns a mutable bitmap with the specified width and height 3 createBitmap(int width, int height, Bitmap.Config config) Returns a mutable bitmap with the specified width and height 4 createBitmap(Bitmap src) Returns an immutable bitmap from the source bitmap 5 extractAlpha() Returns a new bitmap that captures the alpha values of the original 6 getConfig() This mehtod eturn that config, otherwise return null 7 getDensity() Returns the density for this bitmap 8 getRowBytes() Return the number of bytes between rows in the bitmap”s pixels 9 setPixel(int x, int y, int color) Write the specified Color into the bitmap (assuming it is mutable) at the x,y coordinate 10 setDensity(int density) This method specifies the density for this bitmap Example The below example demonstrates some of the image effects on the bitmap. It crates a basic application that allows you to convert the picture into grayscale and much more. To experiment with this example , you need to run this on an actual device. 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.graphics.Bitmap; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; public class MainActivity extends ActionBarActivity { Button b1, b2, b3; ImageView im; private Bitmap bmp; private Bitmap operation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1 = (Button) findViewById(R.id.button); b2 = (Button) findViewById(R.id.button2); b3 = (Button) findViewById(R.id.button3); im = (ImageView) findViewById(R.id.imageView); BitmapDrawable abmp = (BitmapDrawable) im.getDrawable(); bmp = abmp.getBitmap(); } public void gray(View view) { operation = Bitmap.createBitmap(bmp.getWidth(),bmp.getHeight(), bmp.getConfig()); double red = 0.33; double green = 0.59; double blue = 0.11; for (int i = 0; i < bmp.getWidth(); i++) { for (int j = 0; j < bmp.getHeight(); j++) { int p = bmp.getPixel(i, j); int r = Color.red(p); int g = Color.green(p); int b = Color.blue(p); r = (int) red * r; g = (int) green * g; b = (int) blue * b; operation.setPixel(i, j, Color.argb(Color.alpha(p), r, g, b)); } } im.setImageBitmap(operation); } public void bright(View view){ operation= Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(),bmp.getConfig()); for(int i=0; i<bmp.getWidth(); i++){ for(int j=0; j<bmp.getHeight(); j++){ int p = bmp.getPixel(i, j); int r = Color.red(p); int g = Color.green(p); int b = Color.blue(p); int alpha = Color.alpha(p); r = 100 + r; g = 100 + g; b = 100 + b; alpha = 100 + alpha; operation.setPixel(i, j, Color.argb(alpha, r, g, b)); } } im.setImageBitmap(operation); } public void dark(View view){ operation= Bitmap.createBitmap(bmp.getWidth(),bmp.getHeight(),bmp.getConfig()); for(int i=0; i<bmp.getWidth(); i++){ for(int j=0; j<bmp.getHeight(); j++){ int p = bmp.getPixel(i, j); int r = Color.red(p); int g = Color.green(p); int b = Color.blue(p); int alpha = Color.alpha(p); r = r – 50; g = g – 50; b = b – 50; alpha = alpha -50; operation.setPixel(i, j, Color.argb(Color.alpha(p), r, g, b)); } } im.setImageBitmap(operation); } public void gama(View view) { operation = Bitmap.createBitmap(bmp.getWidth(),bmp.getHeight(),bmp.getConfig()); for(int i=0; i<bmp.getWidth(); i++){ for(int j=0; j<bmp.getHeight(); j++){ int p = bmp.getPixel(i, j); int r = Color.red(p); int g = Color.green(p); int b = Color.blue(p); int alpha = Color.alpha(p); r = r + 150; g = 0; b = 0; alpha = 0; operation.setPixel(i, j, Color.argb(Color.alpha(p), r, g, b)); } } im.setImageBitmap(operation); } public void green(View view){ operation = Bitmap.createBitmap(bmp.getWidth(),bmp.getHeight(), bmp.getConfig()); for(int i=0; <bmp.getWidth(); i++){ for(int j=0; j<bmp.getHeight(); j++){ int p = bmp.getPixel(i, j); int r = Color.red(p); int g = Color.green(p); int b = Color.blue(p); int alpha = Color.alpha(p); r = 0; g = g+150; b = 0; alpha = 0; operation.setPixel(i, j, Color.argb(Color.alpha(p), r, g, b)); } } im.setImageBitmap(operation); } public void blue(View view){ operation = Bitmap.createBitmap(bmp.getWidth(),bmp.getHeight(), bmp.getConfig()); for(int i=0; i<bmp.getWidth(); i++){ for(int j=0; j<bmp.getHeight(); j++){ int p = bmp.getPixel(i, j); int r = Color.red(p); int g = Color.green(p); int b = Color.blue(p); int alpha = Color.alpha(p); r = 0; g = 0; b = b+150; alpha = 0; operation.setPixel(i, j, Color.argb(Color.alpha(p), r, g, b)); } } im.setImageBitmap(operation); } } Following is the modified content of the xml res/layout/activity_main.xml. Here abc indicates about 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: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=”Image Effects” /> <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=”Gray”
Android – Best Practices
Android – Best Practices ”; Previous Next There are some practices that you can follow while developing android application. These are suggested by the android itself and they keep on improving with respect to time. These best practices include interaction design features, performance, security and privacy, compatibility, testing, distributing and monetizing tips. They are narrowed down and are listed as below. Best Practices – User input Every text field is intended for a different job. For example, some text fields are for text and some are for numbers. If it is for numbers then it is better to display the numeric keypad when that textfield is focused. Its syntax is. <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=”User Name” android:layout_below=”@+id/imageView” android:layout_alignLeft=”@+id/imageView” android:layout_alignStart=”@+id/imageView” android:numeric=”integer” /> Other then that if your field is for password, then it must show a password hint, so that the user can easily remember the password. It can be achieved as. <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=”Pass Word” android:layout_below=”@+id/editText” android:layout_alignRight=”@+id/editText” android:layout_alignEnd=”@+id/editText” android:password=”true” /> Best Practices – Background jobs There are certain jobs in an application that are running in an application background. Their job might be to fetch some thing from the internet , playing music e.t.c. It is recommended that the long awaiting tasks should not be done in the UI thread and rather in the background by services or AsyncTask. AsyncTask Vs Services. Both are used for doing background tasks , but the service is not affected by most user interface life cycle events, so it continues to run in circumstances that would shut down an AsyncTask. Best Practices – Performance Your application performance should be up-to the mark. But it should perform differently not on the front end , but on the back end when it the device is connected to a power source or charging. Charging could be of from USB and from wire cable. When your device is charging itself , it is recommended to update your application settings if any, such as maximizing your refresh rate whenever the device is connected. It can be done as this. IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); Intent batteryStatus = context.registerReceiver(null, ifilter); // Are we charging / charged? Full or charging. int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1); // How are we charging? From AC or USB. int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1); Best Practices – Security and privacy It is very important that your application should be secure and not only the application , but the user data and the application data should also be secured. The security can be increased by the following factors. Use internal storage rather then external for storing applications files Use content providers wherever possible Use SSl when connecting to the web Use appropriate permissions for accessing different functionalities of device Example The below example demonstrates some of the best practices you should follow when developing android application. It crates a basic application that allows you to specify how to use text fields and how to increase performance by checking the charging status of the phone. 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 under a package com.example.sairamkrishna.myapplication. 2 Modify src/MainActivity.java file to add the code 3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required. 4 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.content.Intent; import android.content.IntentFilter; import android.os.BatteryManager; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; 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; @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); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); Intent batteryStatus = registerReceiver(null, ifilter); int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1); boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL; int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED,-1); boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB; boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC; if(usbCharge){ Toast.makeText(getApplicationContext(),”Mobile is charging on USB”, Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(),”Mobile is charging on AC”, Toast.LENGTH_LONG).show(); } } }); } @Override protected void onDestroy() { super.onDestroy(); } } 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:text=”Bluetooth 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=”User Name” android:layout_below=”@+id/imageView” android:layout_alignLeft=”@+id/imageView” android:layout_alignStart=”@+id/imageView” android:numeric=”integer” /> <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=”Pass Word” android:layout_below=”@+id/editText” android:layout_alignRight=”@+id/editText” android:layout_alignEnd=”@+id/editText” android:password=”true” /> <Button android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:text=”Check” android:id=”@+id/button” android:layout_below=”@+id/editText2″ android:layout_centerHorizontal=”true” /> </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” > <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 tool bar. Android Studio will display following Images. Above image shows an output of application Now just type on the username field and you will see the built in android suggestions from the dictionary will start coming up. This is shown Above. Now you will see the password field. It would disappear as soon as you start writing in the field. It is shown above. In the end , just connect your device to AC cable or USB cable and press on charging check button. In my case , i connect AC power,it shows the following message. Print Page Previous Next Advertisements ”;