Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

Monday, February 10, 2014

Broadcast Receiver in Android with sample demo on SMS_RECEIVED

Broadcast receiver is one of the important component of Android. It's event based which receives event and based on that event it performed.So we also called it receiver.
So for all registered receivers for particular event will be notified by Android when that event happens.
For-example applications can register for the ACTION_BATTERY_LOW system event which is fired when battery getting low.
So now I am creating a sample Project in which I am registering for the event "Telephony.SMS_RECEIVED" on my mobile so when any SMS will come it will show you toast message on your mobile.Just follow the steps to implement this demo project.

Step-1:Create ActivityBroadcastIncomingSMS.java

package com.oxyandroid;

import android.os.Bundle;
import android.app.Activity;


public class BroadcastIncomingSMS extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}

}

Step-2:create main.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"
     >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="OxyAndroid : You will get SMS toast here" />


</RelativeLayout>


Step-3: Create ReceiverForSMS.java class which extends BroadcastReceiver

package com.oxyandroid;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

public class ReceiverForSMS extends BroadcastReceiver {

// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();

public void onReceive(Context context, Intent intent) {

// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();

try {

if (bundle != null) {

/*Note-

A PDU is a "protocol discription unit", which is the industry format for an SMS message. because SMSMessage reads/writes them you shouldn't need to disect them. A large message might be broken into many, which is why it is an array of objects.Apart from this we declare Intent-Filter in android-manifest file from there we r getting object of that intent.
*/

final Object[] pdusObj = (Object[]) bundle.get("pdus");

for (int i = 0; i < pdusObj.length; i++) {

SmsMessage sms = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String senderPhoneNo = sms.getDisplayOriginatingAddress();

       String Mymsg = sms.getDisplayMessageBody();

       Log.i("SmsReceiver", "senderPhoneNo: "+ senderPhoneNo + "; Message: " + Mymsg);     
      
Toast.makeText(context, "senderPhoneNo: "+ senderPhoneNo + ", Message: " + Mymsg, Toast.LENGTH_LONG).show();

} 
              } 

} catch (Exception e) {
e.printStackTrace();

}
}

}


Step-4:create AndroidManifest.xml 

We have to create receiver in side this xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.oxyandroid"
    android:versionCode="1"
    android:versionName="1.0" >
       <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="17" />
    
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>
    <uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.oxyandroid.BroadcastIncomingSMS">
            
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <receiver android:name="com.oxyandroid.ReceiverForSMS">   
            <intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
 
        </receiver>
        
    </application>
   


</manifest>

Thursday, December 26, 2013

Android Seek Bar

XML File

<SeekBar
                        android:id="@+id/sbfactor"
                        android:layout_width="85dp"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="0dp"
                        android:max="5"
                        android:progressDrawable="@drawable/bar"

                        android:thumb="@drawable/button_slider" />

Java Code

SeekBar sbTestFactor= (SeekBar) findViewById(R.id.sbfactor);

sbTestFactor.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
int progress = 0;

public void onProgressChanged(SeekBar seekBar, int progresValue,
boolean fromUser) {
progress = progresValue;
}

public void onStartTrackingTouch(SeekBar seekBar) {
}

public void onStopTrackingTouch(SeekBar seekBar) {

rate1 = progress;

LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) findViewById(R.id.toast_layout));
TextView tv = ((TextView) layout.findViewById(R.id.toast_text_1));
tv.setTypeface(type_regular);
tv.setText("Your Rating Is " + progress);
Toast toast1 = new Toast(getBaseContext());
toast1.setDuration(Toast.LENGTH_SHORT);
toast1.setGravity(Gravity.TOP | Gravity.CENTER, 0, 400);
toast1.setView(layout);
toast1.show();

try {
                                       //set result on textview
tvTestFactor.setText("" + rate1 + "/5");
} catch (Exception e) {
e.printStackTrace();
}

}
});

Android SQLite - Access data from local database where sqlite database kept inside assets folder

public class MyDataBaseHelper extends SQLiteOpenHelper {
private SQLiteDatabase myDataBase;
private final Context myContext;

private static String DB_DIR = "/data/data/com.test/";
private static String DB_NAME = "TestDB.sqlite";
private static String DB_PATH = DB_DIR + DB_NAME;
boolean dbfnd;
Cursor chk;
private String TAG = "Database Helper";

public WineDataHelperNew(Context context) {

super(context, MyDataBaseHelper.DB_NAME, null, 1);
this.myContext = context;
// DB_PATH=myContext.getDatabasePath(DB_NAME).getAbsolutePath();
System.out.println("My DataBase Path: " + DB_PATH);
try {
copyDataBase();
openDataBase();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public void createDataBase() throws IOException {

Log.e("createDataBase1", "+++++++++++++");
boolean dbExist = checkDataBase();

if (dbExist) {
Log.e("createDataBase2", "++++++ database already exist");
// do nothing - database already exist
} else {

// this.getReadableDatabase();

try {

copyDataBase();

} catch (IOException e) {

throw new Error("Error copying database");

}
}

}

private boolean checkDataBase() {

/*
* //SQLiteDatabase checkDB = null; String myPath = DB_PATH; File dbFile
* = new File(myPath); return dbFile.exists();
*/
SQLiteDatabase checkDB = null;

try {
String myPath = DB_PATH;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);

} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}

return checkDB != null ? true : false;

}

private void copyDataBase() throws IOException {

// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);

// Path to the just created empty db
String outFileName = DB_PATH;

// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);

// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();

}

public static void copyFile(InputStream fromFile, OutputStream toFile)
throws IOException {
// transfer bytes from the inputfile to the outputfile
System.out.println("In copying.....");
byte[] buffer = new byte[1024];
int length;

try {
while ((length = fromFile.read(buffer)) > 0) {
toFile.write(buffer, 0, length);
System.out.println("Reading & writing the file....");
}
} catch (Exception e) {
System.out.println("Error in copy1 file :" + e.toString());
}
// Close the streams
finally {
try {
if (toFile != null) {
try {
toFile.flush();
} finally {
toFile.close();
}
}
} catch (Exception e) {
System.out.println("Error in copy2 file :" + e.toString());
} finally {
if (fromFile != null) {
fromFile.close();
System.out.println("File copied successfully.....");
}
}
}
}

public static void copyFile(String fromFile, String toFile)
throws IOException {
copyFile(new FileInputStream(fromFile), new FileOutputStream(toFile));
}

// Open the database
public void openDataBase() {

String myPath = DB_PATH;
try {

myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
System.out.println(myDataBase.toString()
+ " Database found....................!!!!!!!");
dbfnd = true;
} catch (Exception e) {
System.out.println("Database not found....................!!!!!!!");
// TODO: handle exception
dbfnd = false;
}
}

public SQLiteDatabase getReadableDatabase() {
myDataBase = SQLiteDatabase.openDatabase(DB_PATH, null,

SQLiteDatabase.OPEN_READONLY);
return myDataBase;
}

public SQLiteDatabase getWritableDatabase() {
myDataBase = SQLiteDatabase.openDatabase(DB_PATH, null,

SQLiteDatabase.OPEN_READWRITE);

return myDataBase;
}

@Override
public synchronized void close() {

if (myDataBase != null)
myDataBase.close();
super.close();

}

@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

public Cursor get_Data() {
chk = null;

try {
System.out.println("select Distinct Bang from city");
chk = myDataBase.rawQuery(
"select Distinct Bangalore from city", null);

} catch (Exception e) {
Log.e(TAG, "Error in city_table");
e.printStackTrace();
return null;
}
return chk;

}

public Cursor get_Brand(String selBrand) {
// TODO Auto-generated method stub
chk = null;

try {
System.out
.println("select brand from city where Bangalore='"
+ selBrand + "'");
chk = myDataBase.rawQuery(
"select OvalBar from city where Bangalore='"
+ selBrand + "'", null);

} catch (Exception e) {
Log.e(TAG, "Error in brands_table");
e.printStackTrace();
return null;
}
return chk;
}

public Cursor get_Brand() {
chk = null;

try {
System.out.println("select Distinct brand_type from brand");
chk = myDataBase.rawQuery(
"select Distinct alcohol_type from brand", null);

} catch (Exception e) {
Log.e(TAG, "Error in brand");
e.printStackTrace();
return null;
}
return chk;

}

public Cursor get_SuperBrand(String selType) {
// TODO Auto-generated method stub
chk = null;

try {
System.out
.println("select brand_name from brand where type='"
+ selSuperType + "'");
chk = myDataBase.rawQuery(
"select brand_name from brand_alcohol where type='"
+ selType + "'", null);

} catch (Exception e) {
Log.e(TAG, "Error in brand");
e.printStackTrace();
return null;
}
return chk;
}

}