首页 > 代码库 > Android -- 闹钟服务的使用(启动与停止)
Android -- 闹钟服务的使用(启动与停止)
1. 效果图
2. 实现代码
public class firstActivity extends Activity { private static final String AM_ACTION = "iflab.test.AM_ACTION"; // ACTION常量 /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button btn1 = (Button) findViewById(R.id.button1); // 获取对象 Button btn2 = (Button) findViewById(R.id.button2); final AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);// 获取系统服务 Intent intent = new Intent(); // Intent对象 intent.setAction(AM_ACTION); // 设置Action intent.putExtra("message", "该下班啦!"); // 传递字符串 final PendingIntent pendingIntent = PendingIntent.getBroadcast( firstActivity.this, 0, intent, 0); final long time = System.currentTimeMillis(); // 设置当前时间 btn1.setOnClickListener(new View.OnClickListener() { // 监听器 @Override public void onClick(View v) { // TODO Auto-generated method stub //设置重复闹钟提醒 alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, 8 * 1000, pendingIntent); } }); btn2.setOnClickListener(new View.OnClickListener() { // 监听器 @Override public void onClick(View v) { // TODO Auto-generated method stub alarmManager.cancel(pendingIntent); // 取消闹钟 } }); }}
public class myReceiver extends BroadcastReceiver{ @Override public void onReceive(Context arg0, Intent arg1) { // TODO Auto-generated method stub String str; str="触发重复闹钟:"+arg1.getStringExtra("message"); Toast.makeText(arg0, str,Toast.LENGTH_LONG).show(); //显示 }}
<receiver android:name="myReceiver"> <intent-filter> <action android:name="iflab.test.AM_ACTION"/> </intent-filter> </receiver>
Android -- 闹钟服务的使用(启动与停止)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。