我想在我的项目中实现计划功能。所以我用谷歌搜索了一个警报管理器程序,但我找不到任何例子。
谁能帮我一个基本的警报管理器程序?
这是工作代码。 它每 10 分钟唤醒一次 CPU,直到手机关机。
添加到 Manifest.xml:
... <uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission> ... <receiver android:process=":remote" android:name=".Alarm"></receiver> ...
你班上的代码:
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>
并创建一个新类:
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); } } }