How to listen to change in time in Android

2019-04-15 16:09发布

问题:

If the phone time has changed, I need to do some actions. How do I listen for time change?

More specifically, I want to send an SMS when comes specific date that user input.

I run it through the Service. The point is I need always check if the date has come to send the SMS

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);        
    }  


}

回答1:

Create a BroadCastReceiver with action "android.intent.action.TIME_SET" and set the Receiver class.

In AndroidManifest file,

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

Your BroadCastReceiver Class

MyReceiver.java

public class MyReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(final Context arg0, Intent arg1) {
        Log.d("MyReceiver", "Time Changed");
    }
}


回答2:

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

But the problem is that on changing the date the receiver is already destroyed as I am unregistering the receiver in on pause of the activity.