Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android定時發送短信完整詳細示例

Android定時發送短信完整詳細示例

編輯:關於Android編程

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 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如下:



    
    
    
    

    
        
            
                

                
            
        
        
        
            
                
            
        
    


main.xml如下:




    
    
    


  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved