views:

45

answers:

0

Hi Everyone: For example I saved time 6:00 and 6:05 then when i Started my service then First Message at 6:00 will sent and Second not . Here Timer class is not working properly I don't know why? Please help me.Manifest file is correct

Thanks in andvance Rintu kumar

here is my code package com.sms;

import java.util.Calendar; import java.util.Date; import java.util.Locale;

import org.apache.http.impl.cookie.DateUtils;

import android.R.string; import android.app.Activity; import android.app.DatePickerDialog; import android.app.Dialog; import android.app.PendingIntent; import android.app.PendingIntent.OnFinished; import android.app.TimePickerDialog;

import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.Bundle; import android.os.CountDownTimer; import android.provider.Contacts; import android.provider.Contacts.People; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.Phone;

import android.telephony.SmsManager; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.SimpleCursorAdapter; import android.widget.Spinner; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast;

public class sendtomany extends Activity implements OnClickListener, OnItemSelectedListener { /** Called when the activity is first created. */ EditText settimetomany, setdatetomany,selectno; Intent i; TextView timedisplay; String pername; TextView timetomany, datetomany; static final int DATE_DIALOG_ID = 0; static final int time_dialog_id=1; Spinner spintomany; SimpleCursorAdapter simplecursor; String messagebody; Button oksendtomany; String timehour; String timemin; long datediff;

int syear, smonth, sdays; int shour, smin, psec; int chour, cmin, csec; int cyear, cmonth,cdays; long gettime, getdate; String smstable; SQLiteDatabase db=null;

private PendingIntent sentPI; // MyCount counter;

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sendtomany);

    selectno=(EditText) findViewById(R.id.selectno);
    settimetomany=(EditText) findViewById(R.id.settimetomany);
    settimetomany.setOnClickListener(this);
    setdatetomany=(EditText) findViewById(R.id.setdatetomany);
    spintomany=(Spinner) findViewById(R.id.spintomany);
    setdatetomany.setOnClickListener(this);
    oksendtomany=(Button) findViewById(R.id.oksendtomany);
    oksendtomany.setOnClickListener(this);
    //timetomany=(TextView) findViewById(R.id.timetomany);
   // datetomany=(TextView) findViewById(R.id.datetomany);
    timedisplay=(TextView) findViewById(R.id.timedisplay);
    Bundle extras=getIntent().getExtras();
    if(extras!=null)
    {
     messagebody=extras.getString("mesbody");
    }

    Cursor cur = getContentResolver().query(
         People.CONTENT_URI, null, null, null, null);

      startManagingCursor(cur);

      String[] columns = new String[] { People.NAME ,People.NUMBER};

      int[] names = new int[] {android.R.id.text1};

    simplecursor=new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cur, columns,names);

  simplecursor.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    spintomany.setAdapter(simplecursor);
    spintomany.setOnItemSelectedListener(this);

    db=openOrCreateDatabase("sms.db",  SQLiteDatabase.CREATE_IF_NECESSARY, null);
     db.setVersion(1);
     db.setLocale(Locale.getDefault());
     db.setLockingEnabled(true);
   smstable="Create table IF NOT EXISTS smstable" +
     " ( settime  long," +
     "   message  Text," +
     "   phonenumber text)"; 

    db.execSQL(smstable);       

  // smsservice.setMainActivity(this); 




     }

public void onClick(View v) { // TODO Auto-generated method stub

switch(v.getId()) {

case R.id.setdatetomany: //i=new Intent(this , datepicker.class); //startActivity(i); showDialog(DATE_DIALOG_ID);

break;

case R.id.settimetomany:

showDialog(time_dialog_id); break;

case R.id.oksendtomany:

Calendar c = Calendar.getInstance(); cyear = c.get(Calendar.YEAR); cmonth = c.get(Calendar.MONTH); cmonth=cmonth+1; cdays = c.get(Calendar.DAY_OF_MONTH); chour=c.get(Calendar.HOUR_OF_DAY); cmin=c.get(Calendar.MINUTE); csec=c.get(Calendar.SECOND); int ssec=00;

datediff=(new Date(syear,smonth,sdays,shour,smin,ssec)).getTime();//-(new Date(cyear,cmonth,cdays,chour,cmin,csec)).getTime(); //timedisplay.setText(" " + datediff + " "); String phoneNo = selectno.getText().toString();

Toast.makeText(getBaseContext(), "total second" + datediff +" "+messagebody +" " +phoneNo, Toast.LENGTH_SHORT).show();

String sql="Insert into smstable values('" + datediff +"','" + messagebody+"','"+phoneNo + " ')"; db.execSQL(sql); db.close(); Toast.makeText(getBaseContext(), "data successfully added", Toast.LENGTH_SHORT).show();

//counter= new MyCount(datediff,1000); // counter.start(); //Log.d(getClass().getSimpleName(), "onClick: starting srvice"); Toast.makeText(getBaseContext(), "Service started", Toast.LENGTH_SHORT).show();

// Intent i=new Intent(); //i.putExtra(name, value);

startService(new Intent(this, smsservice.class)); // smsservice.setMainActivity(this);

//finish(); break;

} }

@Override protected Dialog onCreateDialog(int id) { Calendar c = Calendar.getInstance(); cyear = c.get(Calendar.YEAR); cmonth = c.get(Calendar.MONTH); cdays = c.get(Calendar.DAY_OF_MONTH); switch (id) { case DATE_DIALOG_ID: return new DatePickerDialog(this, mDateSetListener, cyear, cmonth, cdays); case time_dialog_id: return new TimePickerDialog(this,mTimeSetListener, 0, 0, false); } return null; } private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { // TODO Auto-generated method stub String date_selected = String.valueOf(monthOfYear+1)+" /"+String.valueOf(dayOfMonth)+" /"+String.valueOf(year);

syear=year;

smonth=monthOfYear+1;
sdays=dayOfMonth;

setdatetomany.setText(date_selected +  " { " +  smonth +""+ sdays +""+ syear);

} };

private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {

public void onTimeSet(TimePicker view, int hourOfDay, int minute) { // TODO Auto-generated method stub

//Toast.makeText(sendtomany.this, "Time is="+hourOfDay+":"+minute, Toast.LENGTH_SHORT).show();

String time_selected=String.valueOf(hourOfDay+":"+minute); shour=hourOfDay; smin=minute;

settimetomany.setText(time_selected + " "+shour+" "+smin );

} };

public void onItemSelected(AdapterView<?> parent, View arg1, int arg2,
long arg3) {

// TODO Auto-generated method stub String number=null; Long get=parent.getSelectedItemId(); String s=""+ get; ContentResolver cr = getContentResolver(); Cursor cur = cr.query(People.CONTENT_URI,null, null, null, null); if (cur.getCount() > 0) { while (cur.moveToNext()) { String id = cur.getString(cur.getColumnIndex(People._ID)); //String name = cur.getString(cur.getColumnIndex(People.DISPLAY_NAME)); //String phn=cur.getString(cur.getColumnIndexOrThrow(Contacts.Phones.NUMBER)); Cursor pCur = cr.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", new String[]{id}, null); while (pCur.moveToNext()) { // Do something with phones if(id.endsWith(s)) { number = pCur.getString(pCur.getColumnIndex(Phone.NUMBER)); // selectno.setText(number); } } } }

  }

public void onNothingSelected(AdapterView arg0) { // TODO Auto-generated method stub

}

}

Service is smsservice.java

package com.sms;

import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.Timer; import java.util.TimerTask;

import android.app.Activity; import android.app.AlertDialog; 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.database.sqlite.SQLiteDatabase; import android.os.Binder; import android.os.CountDownTimer; import android.os.IBinder; import android.telephony.SmsManager; import android.util.Log; import android.widget.Toast;

public class smsservice extends Service{

SQLiteDatabase db=null; String smstable; long currentmillsec; Calendar c; String messagebody; long settime; String phonenumber; MyCount counter; long difftime; int year, month, days, hour, min, sec;

 sendtomany myclass;
   Timer timer=new Timer();   

long UPDATE_INTERVAL = 60*1000; //default

  long DELAY_INTERVAL = 0;  

@Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; }

@Override public void onCreate() {

Toast.makeText(getBaseContext(), "service: Oncreated ", Toast.LENGTH_SHORT).show();

c = Calendar.getInstance(); db=openOrCreateDatabase("sms.db", SQLiteDatabase.CREATE_IF_NECESSARY, null); db.setVersion(1); db.setLocale(Locale.getDefault()); db.setLockingEnabled(true); year=c.get(Calendar.YEAR); month=c.get(Calendar.MONTH); month=month+1; days=c.get(Calendar.DAY_OF_MONTH); hour=c.get(Calendar.HOUR_OF_DAY); min=c.get(Calendar.MINUTE); sec=c.get(Calendar.SECOND); currentmillsec=new Date(year,month,days,hour,min,sec).getTime();

     String sql="delete from smstable where settime < " + currentmillsec;
     db.execSQL(sql);
     Toast.makeText(this, "successfully deleted", Toast.LENGTH_LONG).show();

     startactivity();

}

public void startactivity() { // TODO Auto-generated method stub Toast.makeText(this, "Activity started from startactivity", Toast.LENGTH_LONG).show();

refreshdata();

}

@Override public void onDestroy() { if(timer!=null) { timer.cancel(); Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show(); }

}

public class MyCount extends CountDownTimer { public MyCount(long millisInFuture, long countDownInterval) { super(millisInFuture, countDownInterval); }

  public void onFinish() {
   // timedisplay.setText("Done!");

    if (phonenumber.length()>0 && messagebody.length()>0)    
    {
    String del=",";
       String[] user=phonenumber.split(del);

       int index=user.length;

       for(int i=0;i<index;i++)
       {



              sendSMS(user[i], messagebody); 

       }

       }
          else
          {
              Toast.makeText(getBaseContext(), 
                  "Please enter both phone number and message.", 
                  Toast.LENGTH_SHORT).show() ;
  }

    Toast.makeText(getBaseContext(), " " + messagebody +" " +phonenumber, 
               Toast.LENGTH_SHORT).show();















    //restart your service

  //  Context context=null;
//  Intent i=new Intent();
//  i.setAction("com.sms.smsservice");
//  context.startActivity(i);   

  }

public void onTick(long millisUntilFinished) { }

  }



  private void sendSMS(String phoneNo, String message) {
// TODO Auto-generated method stub

 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);

       //---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));        

        //phonenumber=selectno.getText().toString();


       SmsManager sms = SmsManager.getDefault();
       sms.sendTextMessage(phoneNo, null, message, sentPI, deliveredPI);     

}

  public void refreshdata()
  {
   Toast.makeText(getBaseContext(), "service: Oncreated at referesh data function", 
              Toast.LENGTH_SHORT).show();
 //c = Calendar.getInstance();
 db=openOrCreateDatabase("sms.db",  SQLiteDatabase.CREATE_IF_NECESSARY, null);
      db.setVersion(1);
       db.setLocale(Locale.getDefault());
       db.setLockingEnabled(true);
   Date(year,month,days,hour,min,sec).getTime();  




     //  String sql="delete from smstable where settime < " + currentmillsec;
     //  db.execSQL(sql);
     //  Toast.makeText(this, "successfully deleted", Toast.LENGTH_LONG).show();


       Toast.makeText(getBaseContext(), "service started ", 
               Toast.LENGTH_SHORT).show();


 Cursor cur=db.rawQuery("Select * from smstable ORDER BY settime", null);

 int row=cur.getCount();

  cur.moveToFirst();
  int get=cur.getPosition();


int settimecount=cur.getColumnIndexOrThrow("settime");
int messagecount=cur.getColumnIndexOrThrow("message");
int phonenumbercount=cur.getColumnIndexOrThrow("phonenumber");

   settime=cur.getLong(settimecount);
   messagebody=cur.getString(messagecount);
   phonenumber=cur.getString(phonenumbercount);


   Toast.makeText(getBaseContext(), " " + currentmillsec + settime , 
              Toast.LENGTH_SHORT).show();

   Toast.makeText(getBaseContext(), " "  +messagebody+" " +phonenumber , 
              Toast.LENGTH_SHORT).show();

      difftime=settime-currentmillsec;

      Toast.makeText(getBaseContext(), " "+ difftime, 
              Toast.LENGTH_SHORT).show(); 


    counter= new MyCount(difftime,1000); 
  counter.start();



  }      



  public void checkmessage()
  {

     if (phonenumber.length()>0 && messagebody.length()>0)    
     {
     String del=",";
        String[] user=phonenumber.split(del);

        int index=user.length;

        for(int i=0;i<index;i++)
        {



               sendSMS(user[i], messagebody); 

        }

        }
           else
           {
               Toast.makeText(getBaseContext(), 
                   "Please enter both phone number and message.", 
                   Toast.LENGTH_SHORT).show() ;
   }

     Toast.makeText(getBaseContext(), " " + messagebody +" " +phonenumber, 
                Toast.LENGTH_SHORT).show();

}

}

    manifiest file:

   </intent-filter>


   </receiver>

android:name=".smsservice" android:enabled="true">

Thanks in advance Rintu kumar