Monday, 14 May 2012

service


package com.BirthdayWisherFinal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;

import android.app.Activity;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.IBinder;
import android.telephony.SmsManager;
import android.util.Log;
import android.widget.Toast;

public class MessageService extends Service{
    DBBirthday db;
    DBMessage dbmsg;
    String curDate;
    String data;
    Vector<String> vectName;

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        //Log.v("Birthday Wisher", "Messaging service called");
    }
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub       
        return null;
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        Log.v("Birthday Wisher", "Messaging service called");
        getBirthdateData();

        String msgsend = getmessage();
       
        int totalElements = vectName.size();
        if (totalElements > 0) {
            for (int index = 0; index < totalElements; index++) {
                //Log.v("Birthday Wisher", vectName.get(index));
                data = vectName.get(index);
                String[] dataSplit = data.split(":");
                //Log.v("Birthday Wisher", dataSplit[1]+ " "+dataSplit[3] );

                if (dataSplit[3].equals("blank")) {
                    if(!(msgsend == null || msgsend.length() == 0)){
                        sendSMS(dataSplit[1], msgsend);
                    }
                } else {
                    sendSMS(dataSplit[1], dataSplit[3]);
                }
            }
        }
        return super.onStartCommand(intent, flags, startId);       
    }

/// to get message from template table
protected String getmessage() {
    String messagetemp=null;
    dbmsg = new DBMessage(getApplicationContext());
    dbmsg.open();
    Cursor cs = dbmsg.getMessage();
    if (!(cs.getCount() == 0)) {
        if (cs.moveToFirst()) {
            do {
                messagetemp = cs.getString(1);
                return messagetemp;
            } while (cs.moveToNext());
        }
    }
    cs.close();
    dbmsg.close();
    return messagetemp;
}
public void getBirthdateData() {

    // to get the current date
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM");

    String dt = sdf.format(new Date());
    Toast.makeText(getApplicationContext(), "Current date " + dt,
            Toast.LENGTH_LONG).show();

    // get value from database
    db = new DBBirthday(this);
    vectName = new Vector<String>();
    db.open();
    Cursor c = db.getBirthdayContacts();
    if (c.getCount() == 0) {
        Toast.makeText(getApplicationContext(),
                Integer.toString(c.getCount()) + " Records found",
                Toast.LENGTH_SHORT).show();
        return;
    } else {
        if (c.moveToFirst()) {
            do {
                /*
                 * vector will store data whose birth date will match
                 * current date in the format [
                 * name:contact:birthdate:message ]
                 */
                String birthDate = c.getString(3);
                Toast.makeText(getApplicationContext(),
                        "Birthdate " + " " + birthDate, Toast.LENGTH_SHORT)
                        .show();
                if (dt.equals(birthDate)) {
                   
                    if (c.getString(6).length() == 0) {
                        vectName.addElement(c.getString(1) + ":"
                                + c.getString(2) + ":" + c.getString(3)
                                + ":" + "blank");
                    } else {
                        vectName.addElement(c.getString(1) + ":"
                                + c.getString(2) + ":" + c.getString(3)
                                + ":" + c.getString(6));
                    }
                    Toast.makeText(getApplicationContext(),
                            "element added", Toast.LENGTH_SHORT).show();
                }
            } while (c.moveToNext());
        }
        c.close();
    }
    db.close();
}
private void sendSMS(String phoneNumber, String message)
{       
    String SENT = "SMS_SENT";
    String DELIVERED = "SMS_DELIVERED";

    PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
        new Intent(SENT), 0);

    PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
        new Intent(DELIVERED), 0);

    //registerReceiver(receiver, filter)
    //---when the SMS has been sent---
    registerReceiver(new BroadcastReceiver(){
        @Override
        public void onReceive(Context arg0, Intent arg1) {
            switch (getResultCode())
            {
                case Activity.RESULT_OK:
                    Toast.makeText(getBaseContext(), "SMS sent",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                    Toast.makeText(getBaseContext(), "Generic failure",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NO_SERVICE:
                    Toast.makeText(getBaseContext(), "No service",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_NULL_PDU:
                    Toast.makeText(getBaseContext(), "Null PDU",
                            Toast.LENGTH_SHORT).show();
                    break;
                case SmsManager.RESULT_ERROR_RADIO_OFF:
                    Toast.makeText(getBaseContext(), "Radio off",
                            Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }, new IntentFilter(SENT));

    //---when the SMS has been delivered---
    registerReceiver(new BroadcastReceiver(){
        @Override
        public void onReceive(Context arg0, Intent arg1) {
            switch (getResultCode())
            {
                case Activity.RESULT_OK:
                    Toast.makeText(getBaseContext(), "SMS delivered",
                            Toast.LENGTH_SHORT).show();
                    break;
                case Activity.RESULT_CANCELED:
                    Toast.makeText(getBaseContext(), "SMS not delivered",
                            Toast.LENGTH_SHORT).show();
                    break;                       
            }
        }
    }, new IntentFilter(DELIVERED));       
    SmsManager sms = SmsManager.getDefault();
    sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI); 
}

}

Receiver

package com.BirthdayWisherFinal;

import java.util.Calendar;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class AlarmSetupReceiver extends BroadcastReceiver{

    public static AlarmManager alarmManager;
    public static PendingIntent intentExecuted;
    public static Integer interval;
    public static Calendar now;
    public static  Intent i;
    public static boolean FoundAlarm;
   
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
           
       
        now = Calendar.getInstance();
        // here u can set the time when you want to send the message
        // for testing purpose i have set to 1:30 pm
        // for testing purpose set the hour,min respectively n msg will be send on dat time
        now.set(Calendar.HOUR_OF_DAY, 13);
        now.set(Calendar.MINUTE, 30);
        now.set(Calendar.SECOND, 0);
   
        alarmManager = (AlarmManager)(context.getSystemService(Context.ALARM_SERVICE));
        i = new Intent(context,EventReceiver.class);
           
        intentExecuted = PendingIntent.getBroadcast(context,1, i,
                PendingIntent.FLAG_CANCEL_CURRENT);
       
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,now.getTimeInMillis()
                , 24*60*60*1000,intentExecuted);
        Log.v("Birthday Wisher", "alarm setup done for birthday wisher");
    }
}

Helper

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBBirthday {

    public static final String KEY_ROWID = "_id";
    public static final String KEY_NAME = "name";
    public static final String KEY_NO = "number";
    public static final String KEY_BIRTHDATE = "birthdate";
    public static final String KEY_EMAIL = "email";
    public static final String KEY_FACEBOOK_ID = "facebook_id";
    public static final String KEY_Message = "message";
    private static final String TAG = "DBClient";
   
    private static final String DATABASE_NAME = "BirthdaySMSDB";
    private static final String DATABASE_TABLE_Birthday = "birthday";
    private static final int DATABASE_VERSION = 2;

    private static final String BIRTHDAY_CREATE =
        "create table birthday (_id integer primary key autoincrement, "
        + "name text not null, number text not null," +
          "birthdate text not null,email text,facebook_id text,message text);";
   
    private final Context context;
    private DatabaseHelper DBHelper;
    private SQLiteDatabase db;

    public DBBirthday(Context ctx)
    {
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
    }
       
    private static class DatabaseHelper extends SQLiteOpenHelper
    {
        DatabaseHelper(Context context)
        {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db)
        {
            try {
                db.execSQL(BIRTHDAY_CREATE);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
        {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_Birthday);
            onCreate(db);
        }
    }   

    //---opens the database---
    public DBBirthday open() throws SQLException
    {
        db = DBHelper.getWritableDatabase();
        return this;
    }

    //---closes the database---
    public void close()
    {
        DBHelper.close();
    }
   
    //---insert a contact into providers table in the database ---
    public long insertBirthday(String name, String number,String birthdate,String email,String facebook_id,String message)
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_NAME, name);
        initialValues.put(KEY_NO, number);
        initialValues.put(KEY_BIRTHDATE, birthdate);
        initialValues.put(KEY_EMAIL, email);
        initialValues.put(KEY_FACEBOOK_ID,facebook_id);
        initialValues.put(KEY_Message, message);
       
        return db.insert(DATABASE_TABLE_Birthday, null, initialValues);
    }

    //---deletes a particular contact in providers ---
    public boolean deleteBirthday(String delname)
    {
        boolean DEL_OK = false;
        Log.i("delrow",delname);               
        int delrow = db.delete(DATABASE_TABLE_Birthday, KEY_NAME + "=?",new String[]{delname.trim()});
        Log.i("delrow", String.valueOf(delrow));

        if (delrow == 1){
            DEL_OK = true;
        }
        return DEL_OK;      
    }

  //---updates a contact
    public boolean updateBrithday(String name,String number,String birthdate,String email,String facebook_id,String message)
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_NO, number);
        initialValues.put(KEY_BIRTHDATE, birthdate);
        initialValues.put(KEY_EMAIL, email);
        initialValues.put(KEY_FACEBOOK_ID,facebook_id);
        initialValues.put(KEY_Message, message);       
       
        return db.update(DATABASE_TABLE_Birthday, initialValues,
                KEY_NAME + " = '" + name.trim() + "'", null) > 0;
       
    }
    //---retrieves all providers contacts---
    public Cursor getBirthdayContacts()
    {
        return db.query(DATABASE_TABLE_Birthday, new String[] {KEY_ROWID, KEY_NAME,
                KEY_NO,KEY_BIRTHDATE,KEY_EMAIL,KEY_FACEBOOK_ID,KEY_Message}, null, null, null, null, null);
    }
   
  
    public Cursor getBirthday(String name)
    {
        return db.query(DATABASE_TABLE_Birthday,
                new String[] {KEY_ROWID, KEY_NAME,
                KEY_NO,KEY_BIRTHDATE,KEY_EMAIL,KEY_FACEBOOK_ID,KEY_Message},
                KEY_NAME + " = '" + name.trim() + "'",
                null, null, null, null,null);
       
    }
}

Thursday, 23 February 2012

har shaks kuch kehta hai

har shaks kuch kehta hai,
koi rulata hai, to koi hasata hai,
koi aayne dikhata hai, to koi zindagi k mayne sikhate hai,
koi zara se waqt mei zindagi bhar ki khushiya dikhata hai
to koi un khushiyo ko apne sang wapis le jata hai,
koi dhundli aur ujli tasveero mai bas jata hai,
to koi zanzeero ko jakde hue dil k kisi kone mei chup jata hai,
koi sehna sikhata hai,
to koi us dherya k dhage ko todh jata hai,
ye "koi" saala jo bhi hai, hota lajawab hai,
baithe baithe zindagi k haseen aur gamgeen lamho ka safar karwa jata hai