Saturday 26 September 2015

Internet Connection Checking in Android

Activity_Main.XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text=" Internet Status" />
   
    <Button android:id="@+id/btn_check"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Check Internet Status"
        android:layout_centerInParent="true"/>

</RelativeLayout>


MainActivity.Java

package com.example.raji;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;



import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
   
    Boolean isInternetPresent = false;
     
    
    ConnectionDetector cd;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btnStatus = (Button) findViewById(R.id.btn_check);
        // creating connection detector class instance
        cd = new ConnectionDetector(this);
        
        btnStatus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 
              
                isInternetPresent = cd.isConnectingToInternet();
               
                if (isInternetPresent) {
                    
                    showAlertDialog(MainActivity.this, "Internet Connection",
                            "You have internet connection", true);
                } else {
                    
                    showAlertDialog(MainActivity.this, "No Internet Connection",
                            "You don't have internet connection.", false);
                }
            }
        });
    }

    @SuppressWarnings("deprecation")
public void showAlertDialog(Context context, String title, String message, Boolean status) {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();
        
        alertDialog.setTitle(title);
        
        alertDialog.setMessage(message);
         
        
        alertDialog.setIcon((status) ? R.drawable.ic_launcher : R.drawable.ic_launcher);
      
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        
        alertDialog.show();
    }
}

ConnectionDetector.Java

package com.example.raji;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context){
this._context = context;
}

public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
 if (connectivity != null) 
 {
 NetworkInfo[] info = connectivity.getAllNetworkInfo();
 if (info != null) 
 for (int i = 0; i < info.length; i++) 
 if (info[i].getState() == NetworkInfo.State.CONNECTED)
 {
 return true;
 }

 }
 return false;
}
}

AndroidManifestfile.XML

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.raji"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
    <!-- Internet Permissions -->
    <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/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>

Output




This Program developed by my Student Rajeswari.

Tuesday 15 September 2015

What is a Sticky Intent?

Sticky Intent is also a type of Intent which allows a communication between function and a service sendStickyBroadcast() performs a sendBroadcast(Inent) know as sticky,the Intent your are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter). In all other ways, this behaves the same as sendBroadcast(Intent).
One example of a sticky broadcast sent via the operating system isACTION_BATTARY_CHANGED.When you call registerReceiver() for that action — even with a null BroadcastReceiver — you get the Intent that was last Broadcast fot that action. Hence, you can use this to find the state of the battery without necessarily registering for all future state change in the battery.

Syntax
Intent intent = new Intent("some.custom.action");
intent.putExtra("some_boolean", true);
sendStickyBroadcast(intent);

Saturday 12 September 2015

Android or iOS - Which One Scores High On The Scale Of Security

Security is one of the major concerns of mobile app developers. Irrespective of whether you want to create a plain app or one that's loaded with complex functionality, being well aware about the major security breaches is something that will help you to the fullest.
With iOS and Android being considered as two of the brilliant mobile operating systems, there are chances to get confused about the one that can be utilized for developing 100% secure mobile applications. In this blog, I'll be discussing whether iOS or Android is better when it comes to creating apps that are fully secure and free from the attack of hackers and malware.

Android is more prone to attacks as compared to iOS
       Although it's not a straightforward task to compare the security of Google's Android and Apple's iOS, yet there are discussions which indicate that Android is better than iOS when it comes to building hacker-free mobile applications. If you've ever chosen iPhone app developers for hire, you'd be well familiar with the number of security measures that need to be followed for building fully-secure iOS apps. It is the open source nature of Android operating system that tends to attract hackers from different parts of the world. The free-to-download status of Android software package makes it convenient for the attackers to develop malicious programs that can run on the Android operating system. 
      Unlike the Apple Store, Google is doing a great job when it comes to preventing attacks by hackers. This is supported by the fact that Google quickly updates its Android core operating system as well as its Play Store for stopping any attacks  by spammers.



Regular software updates make room for a secure environment for casual app users
        There's no denying of the fact that multiple threats to a particular mobile operating system can be effectively eliminated if the consumers choose to upgrade their mobile device with the latest version of the respective operating system. For example, the inconsistency of Android smartphones opens doors for malware creators. Hence, it's crucial for the users to keep their device updated with the latest version of the operating system. Quite different from Google's Android, Apple's iOS doesn't have any such problem because each new release of the iOS reaches the consumers at a rapid pace. That means, the security scares associated with iOS don't actually tend to become a big news. 

Fake ID vulnerability by Bluebox- A brand new security flaw in Android
       The Fake ID vulnerability by Bluebox has actually hampered the security of Android operating system. This flaw allows the developers to build Android applications that appear to have come from a trusted app programmer. Since a majority of programs running on Android devices come with hard-coded access to the system, showcasing applications as coming from the same developer can pave the route for attackers who can then gain complete access to the Android device under focus. 

Hardware integration matters a lot when it comes to security of Android mobile operating system
         Unlike the case of Apple's iOS, the security of Google's Android primarily depends on the type of hardware that it's running on. There are Android device manufacturers who're quite better in making sure that Android's built-in security features have been well incorporated into the device and are functioning properly. For example, the latest Samsung KNOX 2.0 platform offers a secure booting process which works well for ensuring that any unauthorized software is not being loaded while the smartphone is being switched on. 

Apple's tight control over app distribution keeps it free from malware
       As compared to Google's Android, Apple's iOS has a tight control over its app distribution process. This keeps the mobile operating system safe from the attack of hackers, malware and trojans. Google Play doesn't follow any stringent rule for the publishing of Android apps and with apps being fetched from the third-party app stores, the very popular Android application hub gets vulnerable to attacks by scammers and unauthorized users. 

Wrapping Up
        Despite the differences between iOS and Android in terms of app security, it is interesting to note that both the mobile operating systems can be easily protected from attackers by 
following a simple security measure. With phishing attacks being common to both these platform, it would be beneficial for developers to gain access to tools and techniques that can enable them in building apps that are safeguarded against minor and major security threats. 

Author Signature: 
Lucie Kruger is an application developer working with Mobiers Ltd, the leading mobile application development services provider. She provides concrete information on latest technologies like iOS, Android mobile apps development.

What makes Android special?


What makes android so special?
There are many modile operating systems available in the market including iOs, Windows Phone os, Java mobile version, Symbian, Balckberry OS,   and so on. Android is one of the mobile operating systems that combines component based architecture, open source, out-of-the-box built in services, effective automatic management of appliation lifecycle, good graphics support, wide range of hardware support. Thats why Android is so special among all available mobile platforms.
Lets see how android provides above features;

Effective automatic management of applcation lifecycle:
Android provides multiple layers of security which makes it easier to isolate one program from other. So the user need not worry about the application lifecycle. The user need not worry about which application to be closed for the effective running of other applcation. All these are handled by the operating system very well. This gives a stability to the operating system. This operating system is optimized for low memory, low power usage which makes it easier to run in wide range of devices. Nowadays other platforms like Windows Phone also comes with low power usage.

Open source:
Android is a truely open source platform so the developers get most freedom to develop, test their applications. Thats why this platform has large number applications and it is increasing continuesly.

Out-of-the-box built in services:
Android provides wide range of services which makes the application development very simple. For example the SQLite database gives storage capabilities to the application. Location based services makes the use of GPS,Network features. The application can be developed with mapping capabilities. Browsers can be directly integerated with the application. BroadcastReceiver, content privider and other features helps the developers to create stable, efficient applciations.

Component based architecture:
We can replace built in components with out own improved version easily. This creates a way for cretive ideas from the developers.

Graphics support:
2D vector graphics support, Smooth graphics, 3D animations, Flash support, OpenGL support are helping high quality gaming experience and ultra smooth application interfaces. Android platform provides wide range of codecs so that we can run almost any format of media files in the device. Android gives excellent multi touch facilities.

Hardware support:
All the programs are written in java language. Executed by android's Dalvik Virtual Machine. So the code is portable across ARM, X86 and other architecture based devices. Android also supports variety of input machanisms including keyboard, touchpad, trackball. User interface can be customized to any resolution easily. So android is used in devices with various screen size.

Apart from above features Android provides many other features to the users, developers, device manufacturers and everyone. So all these makes Android so special!!!

Android: Why, When and How to use AsyncTask with example

What is AsyncTask?
               AsyncTask is an abstract class provided by Android which helps us to use the UI thread properly. This class allows us to perform long/background operations and show its result on the UI thread without having to manipulate threads.
When to use AsyncTask?
            Android implements single thread model and whenever an android application is launched, a thread is created. Assuming we are doing network operation on a button click in our application. On button click a request would be made to the server and response will be awaited. Due to single thread model of android, till the time response is awaited our screen is non-responsive. So we should avoid performing long running operations on the UI thread. This includes file and network access.
            To overcome this we can create new thread and implement run method to perform this network call, so UI remains responsive.
            But since Android follows single thread model and Android UI toolkit is not thread safe, so if there is a need to make some change to the UI based on the result of the operation performed, then this approach may lead some issues.

So the Android framework has given a very good pattern which is enveloped into AsyncTask.

Note: AsyncTask should ideally be used for operations that take few seconds. Some tasks keep the thread running for long time so in that case it is recommended to use java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.

AsyncTask has four steps:

  1. doInBackgroundCode performing long running operation goes in this method.  When onClick method is executed on click of button, it calls execute method which accepts parameters and automatically calls doInBackground method with the parameters passed.
  2. onPostExecuteThis method is called after doInBackground method completes processing. Result from doInBackground is passed to this method.
  3. onPreExecuteThis method is called before doInBackground method is called.
  4. onProgressUpdate: This method is invoked by calling publishProgress anytime from doInBackground call this method.
The task can be cancelled by invoking cancel(boolean) method. This will cause subsequent calls to isCancelled()to return true. After invoking this method, onCancelled(Object) method is called instead of onPostExecute() after doInBackground() returns. 

How to use AyncTask? Example application

         In this sample application I just made the process to sleep for some period of time instead of doing network operation.( Just to explain the concept of AsyncTask. This is not a realtime application).
In the UI thread user enters a value (time in milli seconds) which will be passed to AsyncTaskRunner.
AsyncTaskRunner is a private class which extends AsyncTask.

Steps to create the application:

1. Create new android application project in eclipse with default settings.
2. Create the layout for the application.
3. Create the MainActivity and AsyncTaskRunner at com.example.asynctaskdemo.MainActivity.java
4. Run the application as given in the below screenshots.

Activity_Asynctask.xml
   <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"
    tools:context=".MainActivity" >
 
     <TextView
        android:id="@+id/tv_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="10pt"
        android:textColor="#444444"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="9dip"
        android:layout_marginTop="20dip"
        android:layout_marginLeft="10dip"
        android:text="Sleep time in milliseconds:"/>
    <EditText
        android:id="@+id/et_time"
        android:layout_width="150dip"
        android:layout_height="wrap_content"
        android:background="@android:drawable/editbox_background"
        android:layout_toRightOf="@id/tv_time"
        android:layout_alignTop="@id/tv_time"
        android:inputType="text"
        />

    <Button
        android:id="@+id/btn_do_it"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/tv_time"
        android:layout_below="@id/et_time"
        android:layout_marginTop="15dip"
        android:text="Run Async task" />

     <TextView
         android:id="@+id/tv_result"
         android:layout_width="fill_parent"
         android:layout_height="100dip"
         android:layout_alignLeft="@+id/btn_do_it"
         android:layout_below="@id/btn_do_it"
         android:layout_marginRight="9dip"
         android:layout_marginTop="15dip"
         android:text=""
         android:textColor="#AA0000"
         android:textSize="7pt" />

</RelativeLayout>

AsyncTaskActivity.Java

package com.example.asynctask;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class AsyncTaskActivity extends Activity {
private Button button;
private EditText time;
private TextView finalResult;

@Override
protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_async_task);
 time = (EditText) findViewById(R.id.et_time);
 button = (Button) findViewById(R.id.btn_do_it);
 finalResult = (TextView) findViewById(R.id.tv_result);
 button.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
   AsyncTaskRunner runner = new AsyncTaskRunner();
   String sleepTime = time.getText().toString();
   runner.execute(sleepTime);
  }
 });
}

 
/**
 * @author Raj
 * Private class which runs the long operation. ( Sleeping for some time )
 */
private class AsyncTaskRunner extends AsyncTask<String, String, String> {

 private String resp;

 @Override
 protected String doInBackground(String... params) {
  publishProgress("Sleeping..."); // Calls onProgressUpdate()
  try {
   // Do your long operations here and return the result
   int time = Integer.parseInt(params[0]);    
   // Sleeping for given time period
   Thread.sleep(time);
   resp = "Slept for " + time + " milliseconds";
  } catch (InterruptedException e) {
   e.printStackTrace();
   resp = e.getMessage();
  } catch (Exception e) {
   e.printStackTrace();
   resp = e.getMessage();
  }
  return resp;
 }

 /*
  * (non-Javadoc)
  * 
  * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
  */
 @Override
 protected void onPostExecute(String result) {
  // execution of result of Long time consuming operation
  finalResult.setText(result);
 }

 /*
  * (non-Javadoc)
  * 
  * @see android.os.AsyncTask#onPreExecute()
  */
 @Override
 protected void onPreExecute() {
  // Things to be done before execution of long running operation. For
  // example showing ProgessDialog
 }

 /*
  * (non-Javadoc)
  * 
  * @see android.os.AsyncTask#onProgressUpdate(Progress[])
  */
 @Override
 protected void onProgressUpdate(String... text) {
  finalResult.setText(text[0]);
  // Things to be done while execution of long running operation is in
  // progress. For example updating ProgessDialog
 }
}
}

OutPut




Ads Inside Post