SMS Scheduler 在特定时间用于短信

发布于 2024-09-25 23:17:18 字数 17930 浏览 3 评论 0原文

例如,我节省了 6:00 和 6:05 的时间,然后当我开始服务时,将在 6:00 发送第一条消息,而不会发送第二条消息。这里 Timer 类无法正常工作我不知道为什么?请帮助我。清单文件是正确的

,这是我的代码

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,      Toas0t.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:

  <receiver  android:name=".SmsReceiver">
   <intent-filter>
   <action android:name="android.provider.Telephony.SMS_RECEIVED"/>

   </intent-filter>


   </receiver>

   <!-- <receiver android:name=".smsbrodcast">
   <intent-filter>
   <action android:name="android.intent.action.BOOT_COMPLETED"></action>

  </intent-filter>
  android:name=".smsservice"  android:enabled="true">

  </service>

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

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,      Toas0t.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:

  <receiver  android:name=".SmsReceiver">
   <intent-filter>
   <action android:name="android.provider.Telephony.SMS_RECEIVED"/>

   </intent-filter>


   </receiver>

   <!-- <receiver android:name=".smsbrodcast">
   <intent-filter>
   <action android:name="android.intent.action.BOOT_COMPLETED"></action>

  </intent-filter>
  android:name=".smsservice"  android:enabled="true">

  </service>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

坠似风落 2024-10-02 23:17:18

考虑使用 BuzzBox SDK 来安排您的短信。将您的 sendSms 代码放入任务中,并使用类似以下内容来安排任务:

SchedulerManager.getInstance()
    .saveTask(this, "0 6 * * 1,2,3,4,5,6,7|5 6 * * 1,2,3,4,5,6,7", SmsTask.class);

其中 cron 字符串表示将您的任务安排在每天的 6:00 和 6:05。
SDK 将处理剩下的事情。

更多信息http://hub.buzzbox.com/android-sdk/

Consider using the BuzzBox SDK for scheduling your SMS. Put your sendSms code in a Task and schedule the task using something like:

SchedulerManager.getInstance()
    .saveTask(this, "0 6 * * 1,2,3,4,5,6,7|5 6 * * 1,2,3,4,5,6,7", SmsTask.class);

where the cron string says to schedule your Task at 6:00 and at 6:05, every day.
The SDK will take care of the rest.

More info http://hub.buzzbox.com/android-sdk/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文