短信调度不发送短信

时间:2013-07-21 13:53:46

标签: java android

我正在尝试在我的应用中的预定时间发送消息

这是我的活动

public class Lenditem extends Activity {
Context mContext;
private int mHour;
private int mMin;

private int mYear;
private int mMonth;
private int mDay;



Button b1, b2, b3;
EditText et1, et2,et3;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    //Full screen code
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

    setContentView(R.layout.lenditem);



    b1 = (Button)findViewById(R.id.bselectcontactlenditem);

    b3 = (Button)findViewById(R.id.bcancellenditem);
    et1 = (EditText)findViewById(R.id.etdesclenditem);
    et2 = (EditText)findViewById(R.id.etamountlenditem);
    et3 = (EditText)findViewById(R.id.lietentercontact);
     Button dateSet=(Button) findViewById(R.id.limyDatePickerButton);
        Button timeSet=(Button) findViewById(R.id.limyTimePickerButton);



     b3.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View arg0) {
                boolean diditWork = true;
                try {
                    String Desc1 = et1.getText().toString();
                    String Amt1 = et2.getText().toString();

                    Databaselentitem entry = new Databaselentitem(Lenditem.this);
                    entry.open();
                    entry.createEntry1(Desc1, Amt1);
                    entry.close();

                } catch (Exception e) {
                    diditWork = false;
                    Toast.makeText(getApplicationContext(), "Something's Wrong.!!", Toast.LENGTH_LONG).show();

                } finally {
                    if (diditWork) {
                        Toast.makeText(getApplicationContext(), "Reminder saved successfully.!!", Toast.LENGTH_LONG).show();
                    }
                }
            }
     });

     b1.setOnClickListener(new OnClickListener() {

         @Override
         public void onClick(View arg0) {
            // user BoD suggests using Intent.ACTION_PICK instead of
                        // .ACTION_GET_CONTENT to avoid the chooser
                        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                        // BoD con't: CONTENT_TYPE instead of CONTENT_ITEM_TYPE
                        intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);

                        startActivityForResult(intent, 1);
         }
        });

     dateSet.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                Intent localIntent1 = new Intent();
                localIntent1.setClass(Lenditem.this.mContext, TimePickerActivity.class);
                Lenditem.this.startActivityForResult(localIntent1, 0);
                return;

             /*   DatePickerDialog.OnDateSetListener d=new DatePickerDialog.OnDateSetListener() {


                    @Override
                    public void onDateSet(DatePicker view, int year, int monthofyear, int dayofmonth) {
                        // TODO Auto-generated method stub
                        // Use the current date as the default date in the picker
                        final Calendar c = Calendar.getInstance();
                        int mYear = c.get(Calendar.YEAR);
                        int mMonth = c.get(Calendar.MONTH);
                        int mDay = c.get(Calendar.DAY_OF_MONTH);
                        mMonth=monthofyear;
                        mYear=year;
                        mDay=dayofmonth;
                        Toast.makeText(getBaseContext(), "Date Set is :"+mDay+"/"+(mMonth+1)+"/"+mYear, Toast.LENGTH_SHORT).show();
                    }
                };
                // TODO Auto-generated method stub
                new DatePickerDialog(Lenditem.this,d,Calendar.YEAR,Calendar.MONTH,Calendar.DAY_OF_MONTH).show();
          */  }

        });
    timeSet.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            TimePickerDialog.OnTimeSetListener t = new TimePickerDialog.OnTimeSetListener() {

                @Override
                public void onTimeSet(TimePicker view2, int hour, int min) {
                    // TODO Auto-generated method stub
                    mHour = hour;
                    mMin = min;

                    if (mHour >= 12)
                        mHour = mHour - 12;

                    Log.d("MYAPP", "hh:" + mHour + "\nmm:" + mMin);
                    Toast.makeText(getBaseContext(),
                            "Time Set is:" + mHour + ":" + mMin + ":00",
                            Toast.LENGTH_SHORT).show();
                }
            };
            Calendar cal = Calendar.getInstance();
            new TimePickerDialog(Lenditem.this, t, cal
                    .get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE),
                    true).show();

        }
    });
    Button saveAndClearBtn = (Button) findViewById(R.id.bSubmitlenditem);
    saveAndClearBtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {


            // TODO Auto-generated method stub
            Calendar myCal = Calendar.getInstance();
            long timeToTrigger;

            myCal.set(Calendar.YEAR, mYear);
            myCal.set(Calendar.MONTH, mMonth);
            myCal.set(Calendar.DAY_OF_MONTH, mDay);
            myCal.set(Calendar.HOUR, mHour);
            myCal.set(Calendar.MINUTE, mMin);
            myCal.set(Calendar.SECOND, 0);

            long setTime = myCal.getTimeInMillis();

            if (setTime > System.currentTimeMillis()) {

                timeToTrigger = setTime - System.currentTimeMillis();
                EditText edt1 = (EditText) findViewById(R.id.bselectcontactlenditem);
                EditText edt2 = (EditText) findViewById(R.id.litxtMessage);
                String msg = edt2.getText().toString();
                String telno = edt1.getText().toString();
                int count = 0;

                SQLiteDatabase db = openOrCreateDatabase("MYDBli",
                        MODE_PRIVATE, null);
                db.execSQL("CREATE TABLE IF NOT EXISTS mySmsSchedulerli(SlNo VARCHAR,Number VARCHAR,Msg VARCHAR);");

                String s = "INSERT INTO mySmsSchedulerli VALUES ('" + count
                        + "','" + telno + "','" + msg + "');";
                db.execSQL(s);
                Log.d("MYREC", "Insertion of data successfull");
                db.close();

                edt1.setText("");
                edt2.setText("");

                Intent intent = new Intent();
                intent.setClass(Lenditem.this, MyBroadcastRecieverli.class);
                Bundle b = new Bundle();
                b.putString("index", Integer.toString(count));
                intent.putExtras(b);

                PendingIntent pendingIntent = PendingIntent.getBroadcast(
                        Lenditem.this, (int) Math.random(), intent, 0);

                AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
                alarmManager.set(AlarmManager.RTC_WAKEUP,
                        System.currentTimeMillis() + timeToTrigger,
                        pendingIntent);
                count++;
                Toast.makeText(
                        getBaseContext(),
                        "Sms Scheduled after:" + (timeToTrigger / (1000*60*60))+" Hours "+(timeToTrigger/(1000*60))+" Minutes "
                                +(timeToTrigger/1000)+ " sec.", Toast.LENGTH_SHORT).show();

                Log.d("MYAPP", "Set Time:" + (setTime / 1000) + "Sec. \n"
                        + "Cur time:" + System.currentTimeMillis() / 1000);
                Log.d("MYAPP", "Time to trigger:" + (timeToTrigger / 1000)
                        + "sec.");
            } else {
                Toast.makeText(getBaseContext(),
                        "Please Enter a valid time", Toast.LENGTH_SHORT)
                        .show();
                Calendar calendar = Calendar.getInstance();
                int h = calendar.get(Calendar.HOUR);
                int m = calendar.get(Calendar.MINUTE);

                Log.d("MYAPP", "cur HH:" + h + "\ncur MM:" + m);
            }

        }
    });







}





@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (data != null) {
        Uri uri = data.getData();

        if (uri != null) {
            Cursor c = null;
            try {
                c = getContentResolver().query(uri, new String[]{ 
                            ContactsContract.CommonDataKinds.Phone.NUMBER,  
                            ContactsContract.CommonDataKinds.Phone.TYPE },
                        null, null, null);

                if (c != null && c.moveToFirst()) {
                    String number = c.getString(0);
                    int type = c.getInt(1);
                    showSelectedNumber(type, number);
                }
            } finally {
                if (c != null) {
                    c.close();
                }
            }
        }
    }
}
public void showSelectedNumber(int type, String number) {
    et3.setText(number);

}

}

这是广播课

public class MyBroadcastRecieverli extends BroadcastReceiver {

@Override
public void onReceive(Context arg0, Intent intent) {
    // TODO Auto-generated method stub

    int myCount;
    String cnt=intent.getStringExtra("index");
    if(cnt==null)
        Log.d("MYAPP","Data not received");
    Log.d("MYAPP", "Count:"+cnt);
    myCount=Integer.parseInt(cnt);

    Log.d("MYAPP","Broadcast receiver called...");
    SQLiteDatabase db=arg0.openOrCreateDatabase("MYDB",Context.MODE_PRIVATE, null);

    Cursor c=db.rawQuery("SELECT Number, Msg FROM mySmsSchedulerli WHERE SlNo=="+myCount, null);
    Log.d("MYAPP", "Cursor reference obtained...");
    if(c!=null)
    {
        c.moveToFirst();
    }
    else
        Log.d("MYAPP", "cursor is null");
   /* c.moveToFirst();*/
    String num=c.getString(c.getColumnIndex("Number"));
    String myMsg=c.getString(c.getColumnIndex("Msg"));

    Log.d("MYAPP", "number:"+num+"\nMsg:"+myMsg);
    SmsManager sm = SmsManager.getDefault();
    sm.sendTextMessage(num, null, myMsg, null, null);
    Log.d("MYAPP", "Message Sent");
    Toast.makeText(arg0, "Msg sent successfully", Toast.LENGTH_LONG).show();
    String table="mySmsSchedulerli";
    String whereClause = "SlNo = ?";
    String[] whereArgs = new String[] { Integer.toString(Sms.count) };
    db.delete(table, whereClause, whereArgs);
    db.close();
    Log.d("MYAPP", "Entry deleted..");


}
}

它显示你的msg将在xxxx秒后发送,但不会在预定时间发送msg。 任何人都可以帮我plzzz

1 个答案:

答案 0 :(得分:0)

首先尝试使用Broadcast Receive,然后启动服务。

类似的东西:

创建一个函数:

public static void setRecurringAlarm(Context context, Class<?> cls, int time, int minute) {
    Calendar updateTime = Calendar.getInstance();
    updateTime.setTimeZone(TimeZone.getDefault());
    updateTime.set(Calendar.HOUR_OF_DAY, time);
    updateTime.set(Calendar.MINUTE, minute);

    Intent alarm = new Intent(context, cls);
    PendingIntent recurringAlarm = PendingIntent.getBroadcast(context, 654789, alarm, PendingIntent.FLAG_CANCEL_CURRENT);

    AlarmManager alarms = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    alarms.setRepeating(AlarmManager.RTC_WAKEUP, updateTime.getTimeInMillis(), AlarmManager.INTERVAL_DAY, recurringAlarm);
}   

如果您不想设置定期闹钟,只需将setRepeating更改为设置。

在您的代码中,您需要致电:

// to start the receiver at 9:00am
setRecurringAlarm(this, AlarmManagerReceiver.class, 9, 0);

因此,您需要创建AlarmManagerReceiver.java:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class AlarmManagerReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent alarmService = new Intent(context, AlarmManagerService.class);
        context.startService(alarmService);     
    }

}

现在,你需要这项服务:

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.preference.PreferenceManager;

public class AlarmManagerService extends Service {

    private Context context;

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        context = this.getApplicationContext();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);

                // Do what you need to do.

        stopSelf();
    }
}

在清单中:

<receiver android:name=".AlarmManagerReceiver" >
        <intent-filter>
            <action android:name=".AlarmManagerReceiver" />
        </intent-filter>
</receiver>
<service
    android:name=".AlarmManagerService"
    android:enabled="true" >
    <intent-filter>
        <action android:name=".AlarmManagerService" />
    </intent-filter>
</service>