andorid下實現定時發短信的功能

第一,   要實現發短信的功能,必須要用到android系統中發短信的權限,即在AndoridManifest.xml中添加如下內容    

<uses-permissionandroid:name=”android.permission.SEND_SMS”/>

 

第二,   使用AlarmManager來實現一個倒計時的功能,當時間到時發送短   信。AlarmManager有兩個相似的用法:1.在指定時常時候執行某項操作。2.周期性的執行某項操作。AlarmManager對象需要配合Intent對象使用,可以定時開啟一個Activity,發送一個Broadcast,或者開啟一個Service。以下是核心代碼片段:

 

[java] <span style="font-size:16px;">AlarmManager aManager=(AlarmManager)getSystemService(Context.ALARM_SERVICE);  
 
        Intent intent=new Intent(this,AlarmReceiver.class);  
        intent.setAction("AlarmReceiver"); 
 
        PendingIntent pendingIntent=PendingIntent.getBroadcast(this, 0, intent, 0);  
        //aManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);  
        aManager.setRepeating(AlarmManager.RTC, 0, 60*1000, pendingIntent) 
</span> 
<span style="font-size:16px;">AlarmManager aManager=(AlarmManager)getSystemService(Context.ALARM_SERVICE);

  Intent intent=new Intent(this,AlarmReceiver.class);
  intent.setAction("AlarmReceiver");

  PendingIntent pendingIntent=PendingIntent.getBroadcast(this, 0, intent, 0);
  //aManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
  aManager.setRepeating(AlarmManager.RTC, 0, 60*1000, pendingIntent)
</span>

 

第三,   實現時間的設定方式。1.可以直接使用AlarmManager對象的set方法來設定具體的鬧鐘時間。2.可以使用TImePicker的方式來設定時間,這種方式比較靈活。

 

第四,   新建一個AlarmReceiver類,來對鬧鐘進行響應。

1.      現在AndroidMainfest.xml裡添加Receiver的聲明

 

[html] <span style="font-size:16px;"><receiver  
android:name=".AlarmReceiver" 
            android:label="@string/app_name"> 
            <intent-filter> 
                <action android:name="AlarmReceiver" />            
            </intent-filter> 
        </receiver> 
</span> 
<span style="font-size:16px;"><receiver
android:name=".AlarmReceiver"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="AlarmReceiver" />          
            </intent-filter>
        </receiver>
</span>

 

在AlarmReceiver.java中實現對時間的獲取以及發送短信的功能。發送短信需要用到SmsManager類,利用類 SmsManager 發送信息, smsManager 為 SmsManager 一個默認的實例.

 

SmsManager smsManager =SmsManager.getDefault();它的方法如下

smsManager.sendTextMessage(destinationAddress,scAddress, text, sentIntent, deliveryIntent)

其中各個參數的含義如下

  destinationAddress: 收件人號碼

  scAddress: 短信中心服務號碼, 這裡設置為null

  text: 發送內容

sentIntent: 發送短信結果狀態信號(是否成功發送),new 一個Intent , 操作系統接收到信號後將廣播這個Intent.此過程為異步.

  deliveryIntent: 對方接收狀態信號(是否已成功接收).

最後附上詳細的代碼

 

[java] <span style="font-size:16px;">public class YoulainaozhongActivity extends Activity { 
    TextView onetextview; 
    TextView twotextview;    
    TextView threetextview;  
    Button onebutton; 
    Button twobutton; 
    Dialog dialog = null; 
    //新建日歷對象,用來設置鬧鐘時間  
    Calendar calendar = Calendar.getInstance(); 
    private SharedPreferences sharedPreferences;  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
         
        calendar.setTimeInMillis(System.currentTimeMillis()); 
         
        LinearLayout relativeLayout  =(LinearLayout) findViewById(R.id.LinearLayout); 
            relativeLayout.setBackgroundResource(R.drawable.bejing); 
         
        onebutton=(Button) findViewById(R.id.onebutton); 
        onebutton.setOnClickListener(new OnClickListener() { 
             
            @Override 
            public void onClick(View v) { 
             
                dialog(); 
            } 
        }); 
        twobutton=(Button) findViewById(R.id.twobutton); 
        twobutton.setOnClickListener(new OnClickListener() { 
             
            @Override 
            public void onClick(View v) { 
                finish(); 
                 
            } 
        }); 
        onetextview=(TextView) findViewById(R.id.onetextview); 
        twotextview=(TextView) findViewById(R.id.twotextview); 
        threetextview=(TextView) findViewById(R.id.threetextview); 
        sharedPreferences=getSharedPreferences("alarm_record", Activity.MODE_PRIVATE);  
        AlarmManager aManager=(AlarmManager)getSystemService(Context.ALARM_SERVICE);  
 
        Intent intent=new Intent(this,AlarmReceiver.class);  
        intent.setAction("AlarmReceiver"); 
 
        PendingIntent pendingIntent=PendingIntent.getBroadcast(this, 0, intent, 0);  
//      aManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);  
        aManager.setRepeating(AlarmManager.RTC, 0, 60*1000, pendingIntent);  
 
    } 
    public void dialog(){ 
        View view=getLayoutInflater().inflate(R.layout.shijian, null);//   
 
        final TimePicker timePicker=(TimePicker)view.findViewById(R.id.timepicker);  
        final  EditText  oneeditext=(EditText)view.findViewById(R.id.oneeditext); 
        final  EditText  twoeditext=(EditText)view.findViewById(R.id.twoeditext); 
        timePicker.setIs24HourView(true); 
 
        new AlertDialog.Builder(this) 
        .setTitle("設置") 
        .setView(view) 
        .setPositiveButton("確定", new DialogInterface.OnClickListener() {  
 
        public void onClick(DialogInterface dialog, int which) {  
 
        String timeStr=String.valueOf(timePicker.getCurrentHour())+":"+String.valueOf(timePicker.getCurrentMinute());  
         
        /*calendar.set(Calendar.HOUR_OF_DAY,timePicker.getCurrentHour());
        calendar.set(Calendar.MINUTE, 55);*/ 
         
        onetextview.setText("您設置的時間為: "+timeStr);  
        twotextview.setText("您設置的號碼為: "+oneeditext.getText().toString());  
        threetextview.setText("您設置的內容為: "+twoeditext.getText().toString());  
        sharedPreferences.edit().putString(timeStr, timeStr).commit();  
        sharedPreferences.edit().putString("haoma", oneeditext.getText().toString()).commit();  
        sharedPreferences.edit().putString("neirong", twoeditext.getText().toString()).commit();  
 
 
        }  
 
        }).setNegativeButton("取消", null).show();  
 
    } 
}  
public class AlarmReceiver extends BroadcastReceiver { 
 
    /**
     * 通過廣播進行掃描,是否到達時間後再響起鬧鈴
     * */ 
 
    @Override 
    public void onReceive(Context context, Intent intent) { 
        SharedPreferences sharedPreferences = context.getSharedPreferences( 
                "alarm_record", Activity.MODE_PRIVATE); 
 
        String hour = String.valueOf(Calendar.getInstance().get( 
                Calendar.HOUR_OF_DAY)); 
 
        String minute = String.valueOf(Calendar.getInstance().get( 
                Calendar.MINUTE)); 
 
        String time = sharedPreferences.getString(hour + ":" + minute, null);// 小時與分,  
        String haoma = sharedPreferences.getString("haoma", null); 
        String neirong = sharedPreferences.getString("neirong", null); 
 
        if (time != null) {// 判斷是否為空,然後通過創建,  
 
//          MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.a);  
            Toast.makeText(context, "短信已經發送成功", Toast.LENGTH_LONG).show(); 
//          mediaPlayer.start();// 開始 ;  
            sendMsg(haoma, neirong); 
        } 
    } 
 
    private void sendMsg(String number, String message) { 
        SmsManager smsManager = SmsManager.getDefault(); 
        smsManager.sendTextMessage(number, null, message, null, null); 
 
    } 
 

</span> 
<span style="font-size:16px;">public class YoulainaozhongActivity extends Activity {
 TextView onetextview;
 TextView twotextview; 
 TextView threetextview; 
 Button onebutton;
 Button twobutton;
 Dialog dialog = null;
 //新建日歷對象,用來設置鬧鐘時間 www.aiwalls.com
 Calendar calendar = Calendar.getInstance();
 private SharedPreferences sharedPreferences;
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  
  calendar.setTimeInMillis(System.currentTimeMillis());
  
  LinearLayout relativeLayout  =(LinearLayout) findViewById(R.id.LinearLayout);
         relativeLayout.setBackgroundResource(R.drawable.bejing);
  
  onebutton=(Button) findViewById(R.id.onebutton);
  onebutton.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {
   
    dialog();
   }
  });
  twobutton=(Button) findViewById(R.id.twobutton);
  twobutton.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {
    finish();
    
   }
  });
  onetextview=(TextView) findViewById(R.id.onetextview);
  twotextview=(TextView) findViewById(R.id.twotextview);
  threetextview=(TextView) findViewById(R.id.threetextview);
  sharedPreferences=getSharedPreferences("alarm_record", Activity.MODE_PRIVATE);
  AlarmManager aManager=(AlarmManager)getSystemService(Context.ALARM_SERVICE);

  Intent intent=new Intent(this,AlarmReceiver.class);
  intent.setAction("AlarmReceiver");

  PendingIntent pendingIntent=PendingIntent.getBroadcast(this, 0, intent, 0);
//  aManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
  aManager.setRepeating(AlarmManager.RTC, 0, 60*1000, pendingIntent);

 }
 public void dialog(){
  View view=getLayoutInflater().inflate(R.layout.shijian, null);//

  final TimePicker timePicker=(TimePicker)view.findViewById(R.id.timepicker);
  final  EditText  oneeditext=(EditText)view.findViewById(R.id.oneeditext);
  final  EditText  twoeditext=(EditText)view.findViewById(R.id.twoeditext);
  timePicker.setIs24HourView(true);

  new AlertDialog.Builder(this)
  .setTitle("設置")
  .setView(view)
  .setPositiveButton("確定", new DialogInterface.OnClickListener() {

  public void onClick(DialogInterface dialog, int which) {

  String timeStr=String.valueOf(timePicker.getCurrentHour())+":"+String.valueOf(timePicker.getCurrentMinute());
  
  /*calendar.set(Calendar.HOUR_OF_DAY,timePicker.getCurrentHour());
  calendar.set(Calendar.MINUTE, 55);*/
  
  onetextview.setText("您設置的時間為: "+timeStr);
  twotextview.setText("您設置的號碼為: "+oneeditext.getText().toString());
  threetextview.setText("您設置的內容為: "+twoeditext.getText().toString());
  sharedPreferences.edit().putString(timeStr, timeStr).commit();
  sharedPreferences.edit().putString("haoma", oneeditext.getText().toString()).commit();
  sharedPreferences.edit().putString("neirong", twoeditext.getText().toString()).commit();

  }

  }).setNegativeButton("取消", null).show();

 }
}
public class AlarmReceiver extends BroadcastReceiver {

 /**
  * 通過廣播進行掃描,是否到達時間後再響起鬧鈴
  * */

 @Override
 public void onReceive(Context context, Intent intent) {
  SharedPreferences sharedPreferences = context.getSharedPreferences(
    "alarm_record", Activity.MODE_PRIVATE);

  String hour = String.valueOf(Calendar.getInstance().get(
    Calendar.HOUR_OF_DAY));

  String minute = String.valueOf(Calendar.getInstance().get(
    Calendar.MINUTE));

  String time = sharedPreferences.getString(hour + ":" + minute, null);// 小時與分,
  String haoma = sharedPreferences.getString("haoma", null);
  String neirong = sharedPreferences.getString("neirong", null);

  if (time != null) {// 判斷是否為空,然後通過創建,

//   MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.a);
   Toast.makeText(context, "短信已經發送成功", Toast.LENGTH_LONG).show();
//   mediaPlayer.start();// 開始 ;
   sendMsg(haoma, neirong);
  }
 }

 private void sendMsg(String number, String message) {
  SmsManager smsManager = SmsManager.getDefault();
  smsManager.sendTextMessage(number, null, message, null, null);

 }

}
</span>

 

摘自 北京大學-Google Android實驗室

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *