定时弹出 demo ,代码如下:
1.MainActivity.java
public class MainActivity extends Activity implements OnClickListener { private static Context sContext = null; private EditText date; private EditText time; private Button btn; private Date_TimeUtil dtUtil; private String mTime; private String mDate; private LinearLayout llDate; private LinearLayout llTime; public static Context getContext() { return sContext; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sContext = this; dtUtil = new Date_TimeUtil(this); initView(); init(); } private void initView() { date = (EditText) findViewById(R.id.date); time = (EditText) findViewById(R.id.time); btn = (Button) findViewById(R.id.btn); llDate = (LinearLayout) findViewById(R.id.ll_date); llTime = (LinearLayout) findViewById(R.id.ll_time); } private void init() { //date.setOnClickListener(this); //time.setOnClickListener(this); btn.setOnClickListener(this); llDate.setOnClickListener(this); llTime.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.ll_date: dtUtil.setDate(date); break; case R.id.ll_time: dtUtil.setTime(time); break; case R.id.btn: mDate = date.getText().toString(); mTime = time.getText().toString(); Log.e("xx","日期= "+mDate+" 时间= "+mTime); if(TextUtils.isEmpty(mDate)){ Toast.makeText(getApplicationContext(), "请选择提醒日期", 0).show(); break; }else if(TextUtils.isEmpty(mTime)){ Toast.makeText(getApplicationContext(), "请选择提醒时间", 0).show(); break; } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date; long value = 0; String str_date = mDate+" "+mTime; try { date = sdf.parse(str_date); value = date.getTime(); System.out.println("当前设置时间:"+value); } catch (ParseException e) { e.printStackTrace(); } Log.e("str_date=",str_date); Log.e("value=",value+""); long value2 = System.currentTimeMillis(); if(value<=value2){ Toast.makeText(getApplicationContext(), "选择时间不能小于当前系统时间", 0).show(); return; } int delaytime = (int)(value - value2); AlarmService.addNotification(delaytime,"tick","title","text"); break; } } }
2. 服务类
@SuppressLint("NewApi") public class AlarmService extends Service { static Timer timer = null; // 清除通知 public static void cleanAllNotification() { NotificationManager mn = (NotificationManager) MainActivity .getContext().getSystemService(NOTIFICATION_SERVICE); mn.cancelAll(); if (timer != null) { timer.cancel(); timer = null; } } // 添加通知 public static void addNotification(int delayTime, String tickerText, String contentTitle, String contentText) { Intent intent = new Intent(MainActivity.getContext(), AlarmService.class); intent.putExtra("delayTime", delayTime); intent.putExtra("tickerText", tickerText); intent.putExtra("contentTitle", contentTitle); intent.putExtra("contentText", contentText); MainActivity.getContext().startService(intent); } public void onCreate() { Log.e("addNotification", "===========create======="); } @Override public IBinder onBind(Intent intent) { return null; } public int onStartCommand(final Intent intent, int flags, int startId) { long period = 24 * 60 * 60 * 1000; // 24小时一个周期 int delay = intent.getIntExtra("delayTime", 0); if (null == timer) { timer = new Timer(); } timer.schedule(new TimerTask() { @Override public void run() { NotificationManager mn = (NotificationManager) AlarmService.this .getSystemService(NOTIFICATION_SERVICE); Notification.Builder builder = new Notification.Builder( AlarmService.this); Intent notificationIntent = new Intent(AlarmService.this, MainActivity.class);// 点击跳转位置 PendingIntent contentIntent = PendingIntent.getActivity( AlarmService.this, 0, notificationIntent, 0); builder.setContentIntent(contentIntent); builder.setSmallIcon(R.drawable.ic_launcher);// 设置通知图标 builder.setTicker(intent.getStringExtra("tickerText")); // 测试通知栏标题 builder.setContentText(intent.getStringExtra("contentText")); // 下拉通知啦内容 builder.setContentTitle(intent.getStringExtra("contentTitle"));// 下拉通知栏标题 builder.setAutoCancel(true);// 点击弹出的通知后,让通知将自动取消 builder.setVibrate(new long[] { 0, 2000, 1000, 4000 }); // 震动需要真机测试-延迟0秒震动2秒延迟1秒震动4秒 // builder.setSound(Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, // "5"));//获取Android多媒体库内的铃声 // builder.setSound(Uri.parse("file:///sdcard/xx/xx.mp3")) // ;//自定义铃声 builder.setDefaults(Notification.DEFAULT_ALL);// 设置使用系统默认声音 // builder.addAction("图标", title, intent); //此处可设置点击后 打开某个页面 Notification notification = builder.build(); notification.flags = notification.FLAG_INSISTENT;// 声音无限循环 mn.notify((int) System.currentTimeMillis(), notification); } }, delay, period); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { Log.e("addNotification", "===========destroy======="); super.onDestroy(); } }
3.配置文件
<!-- 震动权限 --> <uses-permission android:name="android.permission.VIBRATE" /> <service android:name=".AlarmService" android:enabled="true" android:process="system" > </service>
4.日期工具类 和布局
public class Date_TimeUtil { private Calendar calendar = Calendar.getInstance();; private int mYear, mMonth, mDay; private int mHour; private Integer mMinute; private Context context; public Date_TimeUtil(Context context) { this.context = context; } public void setTime(final EditText time) { // 点击"时间"按钮布局 设置时间 time.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 自定义控件 AlertDialog.Builder builder = new AlertDialog.Builder(context); View view = (LinearLayout) View.inflate(context, R.layout.time_dialog, null); final TimePicker timePicker = (TimePicker) view .findViewById(R.id.time_picker); // 初始化时间 calendar.setTimeInMillis(System.currentTimeMillis()); timePicker.setIs24HourView(true); timePicker.setCurrentHour(calendar.get(Calendar.HOUR_OF_DAY)); timePicker.setCurrentMinute(Calendar.MINUTE); // 设置time布局 builder.setView(view); builder.setTitle("设置时间信息"); builder.setPositiveButton("确 定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mHour = timePicker.getCurrentHour(); mMinute = timePicker.getCurrentMinute(); // 时间小于10的数字 前面补0 如01:12:00 time.setText(new StringBuilder() .append(mHour < 10 ? "0" + mHour : mHour) .append(":") .append(mMinute < 10 ? "0" + mMinute : mMinute).append(":00")); dialog.cancel(); } }); builder.setNegativeButton("取 消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.create().show(); } }); } public void setDate(final EditText date) { // 点击"日期"按钮布局 设置日期 date.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 通过自定义控件AlertDialog实现 AlertDialog.Builder builder = new AlertDialog.Builder(context); View view = (LinearLayout) View.inflate(context, R.layout.date_dialog, null); final DatePicker datePicker = (DatePicker) view .findViewById(R.id.date_picker); // 设置日期简略显示 否则详细显示 包括:星期周 datePicker.setCalendarViewShown(false); // 初始化当前日期 calendar.setTimeInMillis(System.currentTimeMillis()); datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), null); // 设置date布局 builder.setView(view); builder.setTitle("设置日期信息"); builder.setPositiveButton("确 定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // 日期格式 StringBuffer sb = new StringBuffer(); sb.append(String.format("%d-%02d-%02d", datePicker.getYear(), datePicker.getMonth() + 1, datePicker.getDayOfMonth())); date.setText(sb); // 赋值后面闹钟使用 mYear = datePicker.getYear(); mMonth = datePicker.getMonth(); mDay = datePicker.getDayOfMonth(); dialog.cancel(); } }); builder.setNegativeButton("取 消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.create().show(); } }); } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="10dip" > <DatePicker android:datePickerMode="spinner" android:calendarViewShown="false" android:id="@+id/date_picker" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="5dip" android:layout_gravity="center" > </DatePicker> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="10dip" > <TimePicker android:timePickerMode="spinner" android:id="@+id/time_picker" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="5dip" android:layout_gravity="center" > </TimePicker> </LinearLayout>
最后上个图吧