Monday 23 November 2015

Android - Services

A service is a component that runs in the background to perform long-running operations without needing to interact with the user and it works even if application is destroyed. A service can essentially take two states −
A service has life cycle callback methods that you can implement to monitor changes in the service's state and you can perform work at the appropriate stage. The following diagram on the left shows the life cycle when the service is created with startService() and the diagram on the right shows the life cycle when the service is created with bindService(): (image courtesy : android.com )

To create an service, you create a Java class that extends the Service base class or one of its existing subclasses. The Servicebase class defines various callback methods and the most important are given below. You don't need to implement all the callbacks methods. However, it's important that you understand each one and implement those that ensure your app behaves the way users expect.
actvity_main.xml
-----------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
   
xmlns:android="http://schemas.android.com/apk/res/android"
   
xmlns:app="http://schemas.android.com/apk/res-auto"
   
xmlns:tools="http://schemas.android.com/tools"
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
app:layout_behavior="@string/appbar_scrolling_view_behavior"
   
tools:context="com.android.anil.services.MainActivity"
   
tools:showIn="@layout/activity_main"
   
android:orientation="vertical">
   
    <
Button
       
android:layout_width="fill_parent"
       
android:layout_height="wrap_content"
       
android:text="Start Service"
       
android:id="@+id/button"
       
android:layout_gravity="center_horizontal"
       
android:layout_marginTop="50dp" />

    <
Button
       
android:layout_width="fill_parent"
       
android:layout_height="wrap_content"
       
android:text="Stop Service"
       
android:id="@+id/button2"
       
android:layout_gravity="center_horizontal"
       
android:layout_marginTop="50dp" />
</
LinearLayout>

MainActvity.Java
----------------------
package com.android.anil.services;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    Button
startser,stopser;

   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.
toolbar);
        setSupportActionBar(toolbar);
       
startser=(Button)findViewById(R.id.button);
       
stopser=(Button)findViewById(R.id.button2);
       
startser.setOnClickListener(new View.OnClickListener() {
            
@Override
           
public void onClick(View v) {
                Intent intent=
new Intent(getApplicationContext(),MyServices.class);
                startService(intent);
            }
        });
       
stopser.setOnClickListener(new View.OnClickListener() {
           
@Override
           
public void onClick(View v) {
                Intent intent=
new Intent(getApplicationContext(),MyServices.class);
                stopService(intent);
            }
        });

    }
}

MyServices.Java
---------------------------
package com.android.anil.services;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;

/**
 * Created by Anil  on 11/23/15.
 */
public class MyServices extends Service {
   
@Nullable
    @Override
   
public IBinder onBind(Intent intent) {
       
return null;
    }

   
@Override
   
public void onCreate() {
        Toast.makeText(MyServices.
this, "Services is Created()", Toast.LENGTH_SHORT).show();
       
super.onCreate();
    }

   
@Override
   
public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(MyServices.
this, "Services is Running.........", Toast.LENGTH_SHORT).show();
       
return super.onStartCommand(intent, flags, startId);
    }

   
@Override
   
public void onDestroy() {
        Toast.makeText(MyServices.
this, "Services is Stopped", Toast.LENGTH_SHORT).show();
       
super.onDestroy();
    }
}
AndroidManifest.xml
------------------------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   
package="com.android.anil.services">

    <
application
       
android:allowBackup="true"
       
android:icon="@mipmap/ic_launcher"
       
android:label="@string/app_name"
       
android:supportsRtl="true"
       
android:theme="@style/AppTheme">
        <
activity
           
android:name=".MainActivity"
           
android:label="@string/app_name"
           
android:theme="@style/AppTheme.NoActionBar">
            <
intent-filter>
                <
action android:name="android.intent.action.MAIN" />

                <
category android:name="android.intent.category.LAUNCHER" />
            </
intent-filter>
        </
activity>
        <service android:name=".MyServices"></service>
    </
application>

</
manifest>


Output is:
---------------------------










Thursday 12 November 2015

Android External Storage

Every Android-compatible device supports a shared "external storage" that you can use to save files. This can be a removable storage media (such as an SD card) or an internal (non-removable) storage. Files saved to the external storage are world-readable and can be modified by the user when they enable USB mass storage to transfer files on a computer
actvity_main.xml
----------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
   
xmlns:android="http://schemas.android.com/apk/res/android"
   
xmlns:tools="http://schemas.android.com/tools"
   
xmlns:app="http://schemas.android.com/apk/res-auto"
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
app:layout_behavior="@string/appbar_scrolling_view_behavior"
   
tools:showIn="@layout/activity_main"
   
tools:context=".MainActivity"
   
android:orientation="vertical">

    <
EditText
        
android:layout_width="match_parent"
       
android:layout_height="wrap_content"
       
android:id="@+id/editText"
       
android:hint="enter file name" />

    <
EditText
       
android:layout_width="match_parent"
       
android:layout_height="wrap_content"
       
android:id="@+id/editText2"
       
android:layout_gravity="center_horizontal"
       
android:hint="enter text" />

    <
Button
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:text="Save"
       
android:id="@+id/button"
       
android:layout_gravity="center_horizontal" />

    <
Button
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:text="Show"
       
android:id="@+id/button2"
       
android:layout_gravity="center_horizontal" />
</
LinearLayout>


MainActvity.Java
-----------------------
package com.android.anil.externalstorage;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class MainActivity extends AppCompatActivity {
    Button
save,read;
    EditText
filename,textname;

   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.
toolbar);
        setSupportActionBar(toolbar);
       
save=(Button)findViewById(R.id.button);
       
read=(Button)findViewById(R.id.button2);
       
filename=(EditText)findViewById(R.id.editText);
       
textname=(EditText)findViewById(R.id.editText2);
       
save.setOnClickListener(new View.OnClickListener() {
           
@Override
           
public void onClick(View v) {
                String filename1=
filename.getText().toString();
                String data=
textname.getText().toString();

               
try {
                    File myFile =
new File("/sdcard/"+filename1);
                    myFile.createNewFile();
                    FileOutputStream fOut =
new

                           
FileOutputStream(myFile);
                    OutputStreamWriter myOutWriter =
new

                           
OutputStreamWriter(fOut);
                    myOutWriter.append(data);
                    myOutWriter.close();
                    fOut.close();
                    Toast.makeText(MainActivity.
this, filename1+"Saved", Toast.LENGTH_SHORT).show();



                }
catch (FileNotFoundException e) {e.printStackTrace();}
               
catch (IOException e) {e.printStackTrace();}


            }
        });
       
read.setOnClickListener(new View.OnClickListener() {
           
@Override
           
public void onClick(View v) {
                String s2=
filename.getText().toString();
                StringBuffer stringBuffer =
new StringBuffer();
                String aDataRow =
"";
                String aBuffer =
"";
               
try {
                    File myFile =
new File("/sdcard/"+s2);
                    FileInputStream fIn =
new FileInputStream(myFile);
                    BufferedReader myReader =
new BufferedReader(
                           
new InputStreamReader(fIn));

                   
while ((aDataRow = myReader.readLine()) != null) {
                        aBuffer += aDataRow +
"\n";
                    }
                    myReader.close();

                }
catch (IOException e) {
                    e.printStackTrace();
                }
                Toast.makeText(getApplicationContext

                        (),aBuffer,Toast.
LENGTH_LONG).show();

            }
        });
    }
}



Output:
-----------------------






Encryption Decryption Example Android Using AES Alogirthm

activity_main.xml ------------------------- <?xml version="1.0" encoding="utf-8"?> <LinearLayou...