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)));
What are the key differences between a service and IntentService in Android?
Service | IntentService |
---|---|
Service can be used in tasks with no UI, but shouldn't be too long. If you need to perform long tasks, you must create a new thread with in Service | IntentService can be used in long running tasks usually with no communication to Main Thread. If communication is required, can use Main Thread handler or broadcast intents. |
Service can be started using startService() method | IntentService can be started using startService() method and it triggers onHandleIntent() method. |
Service can be triggered from any thread | IntentService must be triggered from Main Thread |
Service runs in background but it runs on the Main Thread of the application. | IntentService runs on a separate worker thread |
The Service may block the Main Thread of the application. | The IntentService cannot run tasks in parallel. Hence all the consecutive intents will go into the message queue for the worker thread and will execute sequentially. |
You must call stopSelf() or stopService() to stop a service once your its job is done. | IntentService stops itself when it finishes its job so you never have to call stopSelf() |
What is an alarm service and explain the purpose with real-world example.
Alarm service is used to run tasks periodically at given interval. You can design application like alrm, birthday reminder, or AlarmManager can be used to initiate long running operations such as syncing data from server once a day. Once an Alarm Started, this will execute until it is stopped explicitly or until device reboots.
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));
How to open link in Android Browser?
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://stacktips.com")); startActivity(browserIntent);
When does onResume() method called?
The onResume() method is an activity lifecycle method. This is called when the activity come to foreground. You can override this method in your activity to execute code when activity is started, restarted or comes to foreground.
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.