开发者社区> 小弟的谷哥> 正文
阿里云
为了无法计算的价值
打开APP
阿里云APP内打开

Android定时发送短信完整详细示例

简介: MainActivity如下: package cc.testsms; import java.util.Calendar; import java.
+关注继续查看

MainActivity如下:

package cc.testsms;

import java.util.Calendar;
import java.util.Locale;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;

/**
 * Demo描述:
 * 手机定时发送短信的实现
 * 
 * 参考资料:
 * 1 http://blog.csdn.net/pku_android/article/details/7548385
 * 2 http://blog.csdn.net/zjbpku/article/details/7577590
 *   Thank you very much
 *   
 *  暂存问题:
 *  1 设置定时短信后关机重启,定时短信失效
 *    可以考虑将定时短信存入数据库或者本地
 *  2 连续多次设置定时短信,但只有最后一个会被触发.
 *     解决方式可以参见闹钟的源码.
 */
public class MainActivity extends Activity {
	public int year;
	public int month;
	public int day;
	public int hour;
	public int minute;
	public int timedYear;
	public int timedMonth;
	public int timedDay;
	public int timedHour;
	public int timedMinute;
	private Context mContext;
	public Calendar calendar;
	private Button mDatePickerButton;
	private Button mTimePickerButton;
	private EditText mContentEditText;
	private Button mSendButton;
	private Button mCancelButton;
	public final static int DATE_PICKER = 9527;
	public final static int TIME_PICKER = 9528;
	public DatePickerDialog mDatePickerDialog;
	public TimePickerDialog mTimePickerDialog;
	private PendingIntent mTimedMessagePendingIntent=null;
	private DatePickerDialog.OnDateSetListener mDateSetListener;
	private TimePickerDialog.OnTimeSetListener mTimeSetListener;
	public boolean isCreatePickerDialog = true;
	private AlarmManager mAlarmManager;

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

	private void init() {
		mContext=this;
		mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		
		mContentEditText = (EditText) findViewById(R.id.contentEditText);
		mSendButton = (Button) findViewById(R.id.sendButton);
		mSendButton.setOnClickListener(new OnClickListenerImpl());
		
		mDatePickerButton = (Button) findViewById(R.id.datePickButton);
		mDatePickerButton.setOnClickListener(new OnClickListenerImpl());

		mTimePickerButton = (Button) findViewById(R.id.timePickButton);
		mTimePickerButton.setOnClickListener(new OnClickListenerImpl());
		
		mCancelButton=(Button) findViewById(R.id.cancelButton);
		mCancelButton.setOnClickListener(new OnClickListenerImpl());

		// 监听DatePicker的set按钮
		mDateSetListener = new DatePickerDialog.OnDateSetListener() {
			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) {
				//保存定时短信的年月日
				System.out.println("---> DatePicker设置后: year=" + year + ", month="+ monthOfYear + ",day=" + dayOfMonth);
				timedYear=year;
				timedMonth=monthOfYear;
				timedDay=dayOfMonth;
			}
		};

		// 监听TimePicker的set按钮
		mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
			@Override
			public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
				//保存定时短信的时分
				System.out.println("---> TimePicker设置后: hour=" + hourOfDay + ",minute="+ minute);
				timedHour=hourOfDay;
				timedMinute=minute;
			}
		};

	}

	private class OnClickListenerImpl implements View.OnClickListener {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.datePickButton:
				showDialog(DATE_PICKER);
				break;
			case R.id.timePickButton:
				showDialog(TIME_PICKER);
				break;
			case R.id.sendButton:
				sendTimedMessage();
				break;
			case R.id.cancelButton:
				cancelTiimedMessage();
				break;
			default:
				break;
			}
		}
	}

	// 覆写Activty的onCreateDialog(int id)方法
	// 注意:
	// 1 第一次显示pickerDialog的时候会调用onCreateDialog()和onPrepareDialog()
	// 2 随后每次只会调用onPrepareDialog()方法
	// 所以需要在onPrepareDialog()方法中获取最新时间再设置
	@Override
	protected Dialog onCreateDialog(int id) {
		getCurrentTime();
		switch (id) {
		case DATE_PICKER:
			mDatePickerDialog = new DatePickerDialog(this, mDateSetListener,year, month, day);
			return mDatePickerDialog;
		case TIME_PICKER:
			mTimePickerDialog = new TimePickerDialog(this, mTimeSetListener,hour, minute, true);
			return mTimePickerDialog;
		default:
			break;
		}
		return super.onCreateDialog(id);
	}

	// 覆写Activty的onPrepareDialog(int id, Dialog dialog)方法
	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		super.onPrepareDialog(id, dialog);
		if (!isCreatePickerDialog) {
			getCurrentTime();
			switch (id) {
			case DATE_PICKER:
				mDatePickerDialog.updateDate(year, month, day);
				break;
			case TIME_PICKER:
				mTimePickerDialog.updateTime(hour, minute);
				break;
			default:
				break;
			}
		}
		isCreatePickerDialog = false;
	}

    //发送定时短信
	private void sendTimedMessage() {
		String content = mContentEditText.getText().toString();
		if (!TextUtils.isEmpty(content)) {
			Intent intent=new Intent(this,AlarmBroadcastReceiver.class);
			intent.setAction("alarmBroadcastReceiverAction");
			intent.putExtra("content", content);
			mTimedMessagePendingIntent=PendingIntent.getBroadcast(this, 0, intent, 0);
			//设置定时时间
			Calendar calendar = Calendar.getInstance();
			calendar.set(Calendar.YEAR, timedYear);
			calendar.set(Calendar.MONTH, timedMonth);
			calendar.set(Calendar.DAY_OF_MONTH, timedDay);
			calendar.set(Calendar.HOUR_OF_DAY, timedHour);
			calendar.set(Calendar.MINUTE, timedMinute);
			if (calendar.getTimeInMillis()<=System.currentTimeMillis()) {
				Toast.makeText(mContext, "请重新设置时间", Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(mContext, "成功设置定时短信", Toast.LENGTH_SHORT).show();
				mAlarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), mTimedMessagePendingIntent);
			}
		}
	}
	
	//取消定时短信
	private void cancelTiimedMessage(){
		if(mTimedMessagePendingIntent!=null){
			mAlarmManager.cancel(mTimedMessagePendingIntent);
			Toast.makeText(mContext, "取消定时短信", Toast.LENGTH_SHORT).show();
		}
	}

	private void getCurrentTime() {
		// 设置时间为中国
		calendar = Calendar.getInstance(Locale.CHINA);
		// 获取日期
		year = calendar.get(Calendar.YEAR);
		month = calendar.get(Calendar.MONTH);
		day = calendar.get(Calendar.DAY_OF_MONTH);
		hour = calendar.get(Calendar.HOUR_OF_DAY);
		minute = calendar.get(Calendar.MINUTE);
		System.out.println("-----> 获取当前时间 year=" + year + ",month=" + month+ 
				           ",day=" + day + ",hour=" + hour + ",minute=" + minute);
	}
}

AlarmBroadcastReceiver如下:

package cc.testsms;

import java.util.ArrayList;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsManager;
import android.widget.Toast;

public class AlarmBroadcastReceiver extends BroadcastReceiver{
	private final String TELPHONE_NUMBER="10086";
	@Override
	public void onReceive(Context context, Intent intent) {
		SmsManager manager = SmsManager.getDefault();
		String content=intent.getStringExtra("content");
		System.out.println("-----> 收到广播 content="+content);
		ArrayList<String> messages = manager.divideMessage(content);
		for (String everyMessage : messages) {
			manager.sendTextMessage(TELPHONE_NUMBER, null, everyMessage, null,null);
		}
		Toast.makeText(context, "已经发送定时短信", Toast.LENGTH_SHORT).show();
	}

}

AndroidManifest.xml如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cc.testsms"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />
    
    <!-- 发送短信的权限 -->
    <uses-permission android:name="android.permission.SEND_SMS"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".MainActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- 注册一个广播接受者 -->
        <receiver android:name=".AlarmBroadcastReceiver">
            <intent-filter>
                <action android:name="alarmBroadcastReceiverAction"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>

main.xml如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/TipTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="定时发送短信的实现"
        android:layout_centerHorizontal="true" 
        android:layout_marginTop="30dip"
     />
    
    <Button
        android:id="@+id/datePickButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="请选择日期" 
        android:layout_marginTop="70dip"
      />
    
    <Button
        android:id="@+id/timePickButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="请选择时间" 
        android:layout_marginTop="140dip"
     />
    
    <EditText 
        android:id="@+id/contentEditText"
        android:layout_width="fill_parent"
        android:layout_height="100dip"
        android:layout_marginTop="210dip"
        android:hint="  输入短信内容"
     />
    
    <Button
        android:id="@+id/sendButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="定时发送" 
        android:layout_marginTop="330dip"
        android:layout_marginLeft="60dip"
      />
    
    <Button
        android:id="@+id/cancelButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="取消发送" 
        android:layout_marginTop="330dip"
        android:layout_marginLeft="180dip"
      />

</RelativeLayout>


版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
【Android开发】 ListView使用实战详解,你get到了嘛?
【Android开发】 ListView使用实战详解,你get到了嘛?
53 0
【Android 应用开发】Android开发技巧--Application, ListView排列,格式化浮点数,string.xml占位符,动态引用图片
【Android 应用开发】Android开发技巧--Application, ListView排列,格式化浮点数,string.xml占位符,动态引用图片
88 0
Android开发重要参考资料
=======================博客============================= 秋百万 有心课堂 郭霖 源码 安装ffmpeg 胡凯 官方培训课程 litesuitsway 爱哥 trinea robinRobin Hu...
828 0
+关注
小弟的谷哥
welcome
766
文章
0
问答
文章排行榜
最热
最新
相关电子书
更多
低代码开发师(初级)实战教程
立即下载
阿里巴巴DevOps 最佳实践手册
立即下载
冬季实战营第三期:MySQL数据库进阶实战
立即下载