1

如果电话时间变了,我需要做一些动作。如何聆听时间变化?

更具体地说,我想在用户输入的特定日期到来时发送短信。

我通过服务运行它。关键是我需要经常检查发送短信的日期是否到了

import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.telephony.gsm.SmsManager;

public class SmsService extends Service{
    String date, messege, numberphone;
    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        date=intent.getStringExtra("date"); 
        String[] dateArray = date.split(",");
        Date dateTime = new Date();


        if(dateArray[0].equals(Integer.toString(dateTime.getDate(
                ))) &&dateArray[1].equals(Integer.toString(dateTime.getMonth(
                ))) && dateArray[2].equals(Integer.toString(dateTime.getYear())))   
            sendSMS(intent.getStringExtra("numberphone"),intent.getStringExtra("message"));
        return super.onStartCommand(intent, flags, startId);
    }



    @SuppressWarnings("deprecation")
    private void sendSMS(String phoneNumber, String message)
    {        
        PendingIntent pi = PendingIntent.getActivity(this, 0,
                new Intent(this, SmsActivity.class), 0);

        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, pi, null);        
    }  


}
4

2 回答 2

3

使用操作创建一个 BroadCastReceiver"android.intent.action.TIME_SET"并设置 Receiver 类。

在 AndroidManifest 文件中,

 <receiver android:name=".MyReceiver">
            <intent-filter >
                <action android:name="android.intent.action.TIME_SET"/>
            </intent-filter>
 </receiver>

您的广播接收器类

MyReceiver.java

public class MyReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(final Context arg0, Intent arg1) {
        Log.d("MyReceiver", "Time Changed");
    }
}
于 2012-05-07T14:10:38.820 回答
0

getActivity().registerReceiver(networkreceiever,new IntentFilter("android.intent.action.TIME_SET"));

但问题是,在更改日期时,接收器已经被销毁,因为我在活动暂停时取消注册接收器。

于 2014-09-18T08:01:05.797 回答