警报pipe理器示例

我想在我的项目中实现计划function。 所以我用Googlesearch闹钟pipe理器程序,但是我找不到任何例子。

任何人都可以帮助我一个基本的报警pipe理程序?

这是工作代码。 它每隔10分钟唤醒CPU,直到电话closures。

添加到Manifest.xml:

... <uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission> ... <receiver android:process=":remote" android:name=".Alarm"></receiver> ... 

你class上的代码:

 package yourPackage; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.PowerManager; import android.widget.Toast; public class Alarm extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, ""); wl.acquire(); // Put here YOUR code. Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example wl.release(); } public void setAlarm(Context context) { AlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE); Intent i = new Intent(context, Alarm.class); PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0); am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 10, pi); // Millisec * Second * Minute } public void cancelAlarm(Context context) { Intent intent = new Intent(context, Alarm.class); PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); alarmManager.cancel(sender); } } 

设置来自服务的警报:

 package yourPackage; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.IBinder; public class YourService extends Service { Alarm alarm = new Alarm(); public void onCreate() { super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { alarm.setAlarm(this); return START_STICKY; } @Override public void onStart(Intent intent, int startId) { alarm.setAlarm(this); } @Override public IBinder onBind(Intent intent) { return null; } } 

如果您想在电话启动时重复设置闹钟:

将权限和服务添加到Manifest.xml:

 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission> ... <receiver android:name=".AutoStart"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"></action> </intent-filter> </receiver> ... <service android:name=".YourService" android:enabled="true" android:process=":your_service" > </service> 

并创build新的类:

 package yourPackage; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class AutoStart extends BroadcastReceiver { Alarm alarm = new Alarm(); @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { alarm.setAlarm(context); } } } 

我尝试了XXX的解决scheme,虽然它起初工作,但在某些时候停止工作。 onReceive从来没有再被调用。 我花了数小时试图弄清楚它可能是什么。 我意识到的是,无论出于什么神秘的原因, Intent都不再被称呼。 为了解决这个问题,我发现你确实需要在清单中为接收者指定一个动作。 例:

 <receiver android:name=".Alarm" android:exported="true"> <intent-filter> <action android:name="mypackage.START_ALARM" > </action> </intent-filter> </receiver> 

请注意,名称是带有句点的".Alarm" 。 在XXX的setAlarm方法中,按如下所示创buildIntent

 Intent i = new Intent("mypackage.START_ALARM"); 

START_ALARM消息可以是任何你想要的。 为了演示的目的,我给了它这个名字。

我没有看到清单中定义的接收器,没有指定动作的意图filter。 以XXX的方式创build它似乎有点虚假。 通过指定操作名称,Android将被迫使用与操作对应的类来创buildBroadcastReceiver的实例。 如果您依赖上下文,请注意,Android有几个不同的对象,都是所谓的上下文,可能不会导致您的BroadcastReceiver创build。 强制Android仅使用动作消息来创build类的实例要比依赖某些可能永远不会工作的iffy上下文要好得多。

这是一个相当独立的例子。 5秒后按下红色button。

  public void SetAlarm() { final Button button = buttons[2]; // replace with a button from your own UI BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive( Context context, Intent _ ) { button.setBackgroundColor( Color.RED ); context.unregisterReceiver( this ); // this == BroadcastReceiver, not Activity } }; this.registerReceiver( receiver, new IntentFilter("com.blah.blah.somemessage") ); PendingIntent pintent = PendingIntent.getBroadcast( this, 0, new Intent("com.blah.blah.somemessage"), 0 ); AlarmManager manager = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE )); // set alarm to fire 5 sec (1000*5) from now (SystemClock.elapsedRealtime()) manager.set( AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000*5, pintent ); } 

请记住,即使应用程序未运行,AlarmManager也会触发。 如果您调用此function并点击主页button,请等待5秒钟,然后返回到您的应用程序,该button将变成红色。

如果你的应用根本不在内存中,我不知道你会得到什么样的行为,所以要注意你试图保存的是什么样的状态。

你可以看到这个例子提醒重复functionGitHub链接此链接适用于4.0testing

在这里输入图像描述

此代码将帮助您发出重复警报。 重复的时间可以由你设定。

activity_main.xml中

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="#000000" android:paddingTop="100dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" > <EditText android:id="@+id/ethr" android:layout_width="50dp" android:layout_height="wrap_content" android:ems="10" android:hint="Hr" android:singleLine="true" > <requestFocus /> </EditText> <EditText android:id="@+id/etmin" android:layout_width="55dp" android:layout_height="wrap_content" android:ems="10" android:hint="Min" android:singleLine="true" /> <EditText android:id="@+id/etsec" android:layout_width="50dp" android:layout_height="wrap_content" android:ems="10" android:hint="Sec" android:singleLine="true" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:paddingTop="10dp"> <Button android:id="@+id/setAlarm" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="onClickSetAlarm" android:text="Set Alarm" /> </LinearLayout> </LinearLayout> 

MainActivity.java

 public class MainActivity extends Activity { int hr = 0; int min = 0; int sec = 0; int result = 1; AlarmManager alarmManager; PendingIntent pendingIntent; BroadcastReceiver mReceiver; EditText ethr; EditText etmin; EditText etsec; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ethr = (EditText) findViewById(R.id.ethr); etmin = (EditText) findViewById(R.id.etmin); etsec = (EditText) findViewById(R.id.etsec); RegisterAlarmBroadcast(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override protected void onDestroy() { unregisterReceiver(mReceiver); super.onDestroy(); } public void onClickSetAlarm(View v) { String shr = ethr.getText().toString(); String smin = etmin.getText().toString(); String ssec = etsec.getText().toString(); if(shr.equals("")) hr = 0; else { hr = Integer.parseInt(ethr.getText().toString()); hr=hr*60*60*1000; } if(smin.equals("")) min = 0; else { min = Integer.parseInt(etmin.getText().toString()); min = min*60*1000; } if(ssec.equals("")) sec = 0; else { sec = Integer.parseInt(etsec.getText().toString()); sec = sec * 1000; } result = hr+min+sec; alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), result , pendingIntent); } private void RegisterAlarmBroadcast() { mReceiver = new BroadcastReceiver() { // private static final String TAG = "Alarm Example Receiver"; @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "Alarm time has been reached", Toast.LENGTH_LONG).show(); } }; registerReceiver(mReceiver, new IntentFilter("sample")); pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("sample"), 0); alarmManager = (AlarmManager)(this.getSystemService(Context.ALARM_SERVICE)); } private void UnregisterAlarmBroadcast() { alarmManager.cancel(pendingIntent); getBaseContext().unregisterReceiver(mReceiver); } } 

如果您只需要一次报警,请更换

 alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), result , pendingIntent); 

  alarmManager.set( AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + result , pendingIntent ); 

我已经尽我所能地以最简单的方式做到这一点。

 import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import junit.framework.Assert; /** * Created by Daniel on 28/08/2016. */ public abstract class AbstractSystemServiceTask { private final Context context; private final AlarmManager alarmManager; private final BroadcastReceiver broadcastReceiver; private final PendingIntent pendingIntent; public AbstractSystemServiceTask(final Context context, final String id, final long time, final AlarmType alarmType, final BackgroundTaskListener backgroundTaskListener) { Assert.assertNotNull("ApplicationContext can't be null", context); Assert.assertNotNull("ID can't be null", id); this.context = context; this.alarmManager = (AlarmManager) this.context.getSystemService(Context.ALARM_SERVICE); this.context.registerReceiver( this.broadcastReceiver = this.getBroadcastReceiver(backgroundTaskListener), new IntentFilter(id)); this.configAlarmManager( this.pendingIntent = PendingIntent.getBroadcast(this.context, 0, new Intent(id), 0), time, alarmType); } public void stop() { this.alarmManager.cancel(this.pendingIntent); this.context.unregisterReceiver(this.broadcastReceiver); } private BroadcastReceiver getBroadcastReceiver(final BackgroundTaskListener backgroundTaskListener) { Assert.assertNotNull("BackgroundTaskListener can't be null.", backgroundTaskListener); return new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { backgroundTaskListener.perform(context, intent); } }; } private void configAlarmManager(final PendingIntent pendingIntent, final long time, final AlarmType alarmType) { long ensurePositiveTime = Math.max(time, 0L); switch (alarmType) { case REPEAT: this.alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), ensurePositiveTime, pendingIntent); break; case ONE_TIME: default: this.alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + ensurePositiveTime, pendingIntent); } } public interface BackgroundTaskListener { void perform(Context context, Intent intent); } public enum AlarmType { REPEAT, ONE_TIME; } } 

唯一的下一步,就是实施它。

 import android.content.Context; import android.content.Intent; import android.util.Log; import ...AbstractSystemServiceTask; import java.util.concurrent.TimeUnit; /** * Created by Daniel on 28/08/2016. */ public class UpdateInfoSystemServiceTask extends AbstractSystemServiceTask { private final static String ID = "UPDATE_INFO_SYSTEM_SERVICE"; private final static long REPEAT_TIME = TimeUnit.SECONDS.toMillis(10); private final static AlarmType ALARM_TYPE = AlarmType.REPEAT; public UpdateInfoSystemServiceTask(Context context) { super(context, ID, REPEAT_TIME, ALARM_TYPE, new BackgroundTaskListener() { @Override public void perform(Context context, Intent intent) { Log.i("MyAppLog", "-----> UpdateInfoSystemServiceTask"); //DO HERE WHATEVER YOU WANT... } }); Log.i("MyAppLog", "UpdateInfoSystemServiceTask started."); } } 

我喜欢使用这个实现,但另一种可能的好方法是,不要使AbstractSystemServiceTask类抽象化,并通过Builder构build它。

我希望它能帮助你。

更新改进,以允许在同一BroadCastReceiver几个BackgroundTaskListener

 import android.app.AlarmManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import junit.framework.Assert; import java.util.HashSet; import java.util.Set; /** * Created by Daniel on 28/08/2016. */ public abstract class AbstractSystemServiceTask { private final Context context; private final AlarmManager alarmManager; private final BroadcastReceiver broadcastReceiver; private final PendingIntent pendingIntent; private final Set<BackgroundTaskListener> backgroundTaskListenerSet; public AbstractSystemServiceTask(final Context context, final String id, final long time, final AlarmType alarmType) { Assert.assertNotNull("ApplicationContext can't be null", context); Assert.assertNotNull("ID can't be null", id); this.backgroundTaskListenerSet = new HashSet<>(); this.context = context; this.alarmManager = (AlarmManager) this.context.getSystemService(Context.ALARM_SERVICE); this.context.registerReceiver( this.broadcastReceiver = this.getBroadcastReceiver(), new IntentFilter(id)); this.configAlarmManager( this.pendingIntent = PendingIntent.getBroadcast(this.context, 0, new Intent(id), 0), time, alarmType); } public synchronized void registerTask(final BackgroundTaskListener backgroundTaskListener) { Assert.assertNotNull("BackgroundTaskListener can't be null", backgroundTaskListener); this.backgroundTaskListenerSet.add(backgroundTaskListener); } public synchronized void removeTask(final BackgroundTaskListener backgroundTaskListener) { Assert.assertNotNull("BackgroundTaskListener can't be null", backgroundTaskListener); this.backgroundTaskListenerSet.remove(backgroundTaskListener); } public void stop() { this.backgroundTaskListenerSet.clear(); this.alarmManager.cancel(this.pendingIntent); this.context.unregisterReceiver(this.broadcastReceiver); } private BroadcastReceiver getBroadcastReceiver() { return new BroadcastReceiver() { @Override public void onReceive(final Context context, final Intent intent) { for (BackgroundTaskListener backgroundTaskListener : AbstractSystemServiceTask.this.backgroundTaskListenerSet) { backgroundTaskListener.perform(context, intent); } } }; } private void configAlarmManager(final PendingIntent pendingIntent, final long time, final AlarmType alarmType) { long ensurePositiveTime = Math.max(time, 0L); switch (alarmType) { case REPEAT: this.alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), ensurePositiveTime, pendingIntent); break; case ONE_TIME: default: this.alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + ensurePositiveTime, pendingIntent); } } public interface BackgroundTaskListener { void perform(Context context, Intent intent); } public enum AlarmType { REPEAT, ONE_TIME; } } 

MainActivity.java

 package com.example.alarmexample; import android.app.Activity; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity { Button b1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startAlert(); } public void startAlert() { int timeInSec = 2; Intent intent = new Intent(this, MyBroadcastReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast( this.getApplicationContext(), 234, intent, 0); AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (timeInSec * 1000), pendingIntent); Toast.makeText(this, "Alarm set to after " + i + " seconds",Toast.LENGTH_LONG).show(); } } 

MyBroadcastReceiver.java

 package com.example.alarmexample; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.media.MediaPlayer; import android.widget.Toast; public class MyBroadcastReceiver extends BroadcastReceiver { MediaPlayer mp; @Override public void onReceive(Context context, Intent intent) { mp=MediaPlayer.create(context, R.raw.alarm); mp.start(); Toast.makeText(context, "Alarm", Toast.LENGTH_LONG).show(); } } 

AndroidManifest.xml中

 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.alarmexample" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="16" /> <uses-permission android:name="android.permission.VIBRATE" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.alarmexample.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name="MyBroadcastReceiver" > </receiver> </application> </manifest>