workmanager studio solo reinicia rato quitar prende permanentes para notificaciones manager las instalar example dev codigo celular cada barra app aplicaciones aparecen aparece alarma android android-notifications android-alarms

studio - notificaciones android app



Cómo crear alarmas persistentes incluso después de reiniciar (1)

¿Con este código se borrarán mis alarmas después de reiniciar? Si es así, cómo superar esto.

Sí, la alarma se eliminará. Para superar esto, debe usar el componente de Android llamado BroadcastReceiver de la siguiente manera:

Primero, necesitas el permiso en tu manifiesto:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

Además, en su manifiesto, defina su servicio y escuche la acción de inicio completado:

<receiver android:name=".receiver.StartMyServiceAtBootReceiver" android:enabled="true" android:exported="true" android:label="StartMyServiceAtBootReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver>

Luego debe definir el receptor que obtendrá la acción BOOT_COMPLETED e iniciar su servicio.

public class StartMyServiceAtBootReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) { Intent serviceIntent = new Intent("com.myapp.NotifyService"); context.startService(serviceIntent); } } }

Y ahora su servicio debería estar funcionando cuando se inicie el teléfono.

2 para vibracion

Una vez más, debe definir un permiso en el archivo AndroidManifest.xml de la siguiente manera:

<uses-permission android:name="android.permission.VIBRATE"/>

Aquí está el código para la vibración,

// Get instance of Vibrator from current Context Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); // Vibrate for 300 milliseconds v.vibrate(300);

Actualmente, estoy trabajando en una aplicación que funciona como "Lista de tareas para hacer". He implementado con éxito NotificationService y SchedularService en mi aplicación. También estoy recibiendo las alertas (Notificaciones) en el momento establecido para las tareas. Aquí están mis consultas de la siguiente manera:

  1. ¿Con este código se borrarán mis alarmas después de reiniciar? Si es así, cómo superar esto.
  2. He mantenido la función de Prioridad para las tareas. Pero quiero un mecanismo tal que si el usuario selecciona la prioridad "Alta", debe recibir notificaciones tres veces, por ejemplo, antes de 30 minutos, antes de 15 minutos y en el tiempo establecido. ¿Cómo lograr esto?
  3. Quiero configurar la función de vibración del teléfono cuando se presentan las notificaciones. ¿Cómo lograr esto?
  4. Y quiero saber qué se puede hacer para los métodos y el constructor en desuso en NotifyService.java. Thesse está en desuso en el nivel 11 de API: Notification notification = new Notification(icon, text, time); y notification.setLatestEventInfo(this, title, text, contentIntent); . En developer.android.com, han sugerido utilizar Notification.Builder lugar. Entonces, ¿cómo hacer mi aplicación compatible con todos los niveles de API.

Aquí está mi código de código para programar la alarma:

... scheduleClient.setAlarmForNotification(c, tmp_task_id); ...

Aquí está la clase ScheduleClient.java:

public class ScheduleClient { private ScheduleService mBoundService; private Context mContext; private boolean mIsBound; public ScheduleClient(Context context) { mContext = context; } public void doBindService() { mContext.bindService(new Intent(mContext, ScheduleService.class), mConnection, Context.BIND_AUTO_CREATE); mIsBound = true; } private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { mBoundService = ((ScheduleService.ServiceBinder) service).getService(); } public void onServiceDisconnected(ComponentName className) { mBoundService = null; } }; public void setAlarmForNotification(Calendar c, int tmp_task_id){ mBoundService.setAlarm(c, tmp_task_id); } public void doUnbindService() { if (mIsBound) { mContext.unbindService(mConnection); mIsBound = false; } } }

Aquí está el ScheduleService.java:

public class ScheduleService extends Service { int task_id; public class ServiceBinder extends Binder { ScheduleService getService() { return ScheduleService.this; } } @Override public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; } @Override public IBinder onBind(Intent intent) { return mBinder; } private final IBinder mBinder = new ServiceBinder(); public void setAlarm(Calendar c, int tmp_task_id) { new AlarmTask(this, c, tmp_task_id).run(); } }

Aquí está la AlarmTask.java:

public class AlarmTask implements Runnable{ private final Calendar date; private final AlarmManager am; private final Context context; int task_id; public AlarmTask(Context context, Calendar date, int tmp_task_id) { this.context = context; this.am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); this.date = date; task_id = tmp_task_id; } @Override public void run() { Intent intent = new Intent(context, NotifyService.class); intent.putExtra(NotifyService.INTENT_NOTIFY, true); intent.putExtra("task_id", task_id); PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0); am.set(AlarmManager.RTC, date.getTimeInMillis(), pendingIntent); } }

Aquí está el NotifyService.java:

public class NotifyService extends Service { public class ServiceBinder extends Binder { NotifyService getService() { return NotifyService.this; } } int task_id; private static final int NOTIFICATION = 123; public static final String INTENT_NOTIFY = "com.todotaskmanager.service.INTENT_NOTIFY"; private NotificationManager mNM; SQLiteDatabase database; @Override public void onCreate() { mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); } @Override public int onStartCommand(Intent intent, int flags, int startId) { String tmp_task_brief = null; task_id = intent.getIntExtra("task_id", 0); loadDatabase(); Cursor cursor = database.query("task_info", new String[]{"task_brief"}, "task_id=?", new String[]{task_id+""}, null, null, null); while(cursor.moveToNext()) { tmp_task_brief = cursor.getString(0); } cursor.close(); if(intent.getBooleanExtra(INTENT_NOTIFY, false)) showNotification(tmp_task_brief); return START_NOT_STICKY; } @Override public IBinder onBind(Intent intent) { return mBinder; } private final IBinder mBinder = new ServiceBinder(); private void showNotification(String tmp_task_brief) { CharSequence title = "To Do Task Notification!!"; int icon = R.drawable.e7ca62cff1c58b6709941e51825e738f; CharSequence text = tmp_task_brief; long time = System.currentTimeMillis(); Notification notification = new Notification(icon, text, time); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, TaskDetails.class), 0); notification.setLatestEventInfo(this, title, text, contentIntent); notification.flags |= Notification.FLAG_AUTO_CANCEL; mNM.notify(NOTIFICATION, notification); stopSelf(); } void loadDatabase() { database = openOrCreateDatabase("ToDoDatabase.db", SQLiteDatabase.OPEN_READWRITE, null); } }