How to open link in Android Browser?
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://stacktips.com")); startActivity(browserIntent);
How to pass data to an IntentService?
You can pass data as bundle to IntentService before you start.
Intent intent = new Intent(Intent.ACTION_SYNC, null, this, DownloadService.class); /* Send optional extras to Download IntentService */ intent.putExtra("url", url); intent.putExtra("receiver", mReceiver); intent.putExtra("requestId", 101); startService(intent);
How to define a service in Android manifest file?
All the services used in the app need to be registered in application Manifest. Services are declared as shown below
<!--Service declared in manifest --> <service android:name=".HelloService" android:exported="false"/>
What are the different clock types supported for AlarmService?
Android supports two clock types for alarm service. Once is elapsed real time and other is real time clock (RTC). Elapsed real time uses the time since the device last booted. Real-time clock (RTC) uses UTC time for alarm service clock. RTC is most commonly used for setting alarm service in android.
What is the difference between bound and unbounded service in Android?
- Bound Service - Service which call indefinitely in between activity. An Android component may bind itself to a Service using bindservice (). A bound service would run as long as the other application components are bound to it. As soon as they unbind, the service destroys itself.
- Unbound Service - Service which call at the life span of calling activity. In this case, an application component starts the service, and it would continue to run in the background, even if the original component that initiated it is destroyed. For instance, when started, a service would continue to play music in the background indefinitely.
Explain service lifecycle methods in Android?
A service can be run by the system, If someone calls Context.startService() or bindService() method.
- onStartCommand() - This method is called when the service be started by calling startService(). Once this method executes, the service is started and can run in the background indefinitely. If you implement this, it is your responsibility to stop the service when its work is done, by calling stopSelf() or stopService(). If you are defining your service as, bounded service then you don?t need to implement this method.
- onBind() - You need to override this method, only if you are defining your service as bounded service. This method is called, when another component wants to bind with the service by calling bindService(). In your implementation of this method, you must provide an interface that clients use to communicate with the service, by returning an IBinder. You must always implement this method, but if you don?t want to allow binding, then you should return null.
- onCreate()- This method is called while the service is first created. Here all the service initialization is done. This method is never called again.
- onDestroy() - The system calls this method when the service is no longer used and is being destroyed. This method is used to, clean up any resources such as threads, registered listeners, receivers, etc. This is the last call the service receives.
What is the purposes of Service in Android?
Android Service is used to perform long-running jobs off the UI thread. Typical long-running tasks can be periodic downloading of data from the internet, saving multiple records into the database, performing file I/O, fetching your phone contacts list, etc. For such long-running tasks, Service is used to avoid UI lags and makes the user experience better.
How to Pass data between Activities in Android?
We an pass values between the activities, by using Bundles. Use below code to send data from ActivityA
String name="Javatechig"; String url="http://stacktips.com" Intent intent=new Intent(ActivityA.this, ActivityB.class); intent.putExtra("name", name); intent.putExtra("url", url); startActivity(intent);Now, you can retrieve the data in ActivityB using below code
Bundle bundle = new Bundle(); bundle = getIntent().getExtras(); String name = bundle.getString("name"); String url = bundle.getString("url");
How to display Android Toast?
Toast is a notification message that pop up, display a certain amount of time, and automatically fades in and out, most people just use it for debugging purpose. Below is the code snippets to create a Toast message
//display in short period of time Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_SHORT).show(); //display in long period of time Toast.makeText(getApplicationContext(), "msg msg", Toast.LENGTH_LONG).show();Android custom toast example
How to Display HTML in Android TextView?
In android there is a lovely class android.text.HTML
that processes HTML strings into displayable styled text. Currently android doesn't support all HTML tags.
Html.formHtml()
method takes an Html.TagHandler
and an Html.ImageGetter
as arguments as well as the text to parse. We can parse null as for the Html.TagHandler but you?d need to implement your own Html.ImageGetter as there isn?t a default implementation. The Html.ImageGetter needs to run synchronously and if you?re downloading images from the web you?ll probably want to do that asynchronously. But in my example I am using the images from resources to make my ImageGetter implementation simpler.
String htmlText = "<html><body>....</body></html>"; TextView htmlTextView = (TextView)findViewById(R.id.html_text); htmlTextView.setText(Html.fromHtml(htmlText, new ImageGetter(), null));
What is use of serialVersionUID?
During object serialization, the default Java serialization mechanism writes the metadata about the object, which includes the class name, field names, types, and superclass. This class definition is stored as a part of the serialized object. This stored metadata enables the deserialization process to reconstitute the objects and map the stream data into the class attributes with the appropriate type every time an object is serialized the java serialization mechanism automatically computes a hash value.
ObjectStreamClass’s computeSerialVersionUID() method passes the class name, sorted member names, modifiers, and interfaces to the secure hash algorithm (SHA), which returns a hash value. The serialVersionUID is also called suid.
So when the serialized object is retrieved, the JVM first evaluates the suid of the serialized class and compares the suid value with the one of the objects. If the suid values match then the object is said to be compatible with the class and hence it is de-serialized. If not InvalidClassException exception is thrown.
Changes to a serializable class can be compatible or incompatible.
How to integrating sharing in Android?
Android API made sharing feature handy. You don't need to integrate the third party applications SDK's like Facebook, twitter. Just a step to use share intent and it makes your application ready to share data to your social networks.
Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send."); sendIntent.setType("text/plain"); startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
How to send Email in Android?
Android Intent is the handy way to send Email using your app.
String to = toEmail.getText().toString(); String subject = emailSubject.getText().toString(); String message = emailBody.getText().toString(); Intent email = new Intent(Intent.ACTION_SEND); email.putExtra(Intent.EXTRA_EMAIL, new String[] { to }); email.putExtra(Intent.EXTRA_SUBJECT, subject); email.putExtra(Intent.EXTRA_TEXT, message); // need this to prompts email client only email.setType("message/rfc822"); startActivity(Intent.createChooser(email, "Choose an Email client"));
How to Make a call in Android?
Intent callIntent = new Intent(Intent.ACTION_CALL); callIntent.setData(Uri.parse("tel:03777788")); startActivity(callIntent);
How to send SMS in Android?
You may send SMS either using SmsManager or by invoking the Built-in SMS application
Sending SMS using SmsManager APISmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage("", null, "< message body>", null, null);SmsManager require, SMS_SEND permission in your android mainfeast. Sending SMS by invoking Built-in SMS application
Intent sendIntent = new Intent(Intent.ACTION_VIEW); sendIntent.putExtra("sms_body", ?"); sendIntent.setType("vnd.android-dir/mms-sms"); startActivity(sendIntent);
What are the different data storage options available in Android?
Android offers several different options for data persistence.
- Shared Preferences - Used to store private primitive data in key-value pairs. This sometimes gets limited as it offers only key value pairs. You cannot save your own java types.
- Internal Storage - Used to store private data on the device memory
- External Storage - Used to store public data on the shared external storage
- SQLite Databases - Used to store structured data in a private database. You can define many number of tables and can store data like other RDBMS.
Define different kind of context in android
Context defines the current state of application or object. Context provides access to things such as creating new activity instance, access databases, start a service, etc. You can get the context by invoking getApplicationContext()
, getContext()
, getBaseContext()
or this
when in the activity class.
//Creating ui instance ImageButton button = new ImageButton(getContext()); //creating adapter ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), ...); //querying content provider getApplicationContext().getContentResolver().query(uri, ...); //start activity. Here this means activity context Intent intent = new Intent(this, SecondActivity.class);
What is the use of WebView in android?
A WebView is an android UI component that displays webpages. It can either display a remote webpage or can also load static HTML data. This encompasses the functionality of a browser that can be integrated to application. WebView uses the WebKit rendering engine to display web pages and includes methods to navigate forward and backward through a history, zoom in and out, etc.
How to share text using android share Intent?
Share intent is an easy and convenient way of sharing content of your application with other apps.
Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send."); sendIntent.setType("text/plain"); startActivity(sendIntent);
What is the difference between a regular .png and a nine-patch image?
The nine patch images are extension with .9.png
. Nine-patch image allows resizing that can be used as background or other image size requirements for the target device. The Nine-patch refers to the way you can resize the image: 4 corners that are unscaled, 4 edges that are scaled in 1 axis, and the middle one that can be scaled into both axes.