public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//跳到服务
Intent intent=new Intent(this,AlarmclockSerivce.class);
startService(intent);
}
}
public class AlarmclockSerivce extends IntentService {
public AlarmclockSerivce() {
super("重写父类IntentService");
}
@Override
protected void onHandleIntent(Intent intent) {// 这里是子线程,且不用再关闭了
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
long triggerAtTime=SystemClock.elapsedRealtime()+1*60*1000;//1min后执行
Intent i=new Intent(this,AlarmclockReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(this, 0, i, 0);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
Log.i("当前时间", System.currentTimeMillis()+"");
}
public class AlarmclockReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification.Builder(context)
.setTicker("闹钟提示").setContentTitle("起床时间")
.setContentText("主人,今天有重要约会啊")
.setSmallIcon(android.R.drawable.btn_star)
.setVibrate(new long[]{0,2000,1000,2000,1000,2000,1000})
.build();
notificationManager.notify(1, notification);
Intent i = new Intent(context, AlarmclockSerivce.class);
context.startService(i);
}
}