Уведомление о тревоге Android - PullRequest
2 голосов
/ 27 мая 2011

Я пытаюсь реализовать функцию Alarm в моих мобильных приложениях. Ниже приведен мой пример использования

  1. Пользователь может установить напоминание из действия "A" после установки напоминания, пользователь получит уведомление за 10 минут до установленного времени. Теперь пользователь может удалить напоминание из другого действия, для которого допустим, что "B" .

  2. Кроме того, я также хочу, чтобы пользователь мог перенести свои настройки напоминания из окна уведомлений.

Ниже приведен код, который я написал для варианта использования 1

private void setAlarm(){
    Intent intent = new Intent(A.this, RepeatAlarm.class);

    mAlarmSender = PendingIntent.getService(A.this,
        0, new Intent(A.this, RepeatAlarm.class), 0);

    // We want the alarm to go off 30 seconds from now.
        long firstTime = SystemClock.elapsedRealtime();

        // Schedule the alarm!
        AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
        am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
        firstTime, 30*1000, mAlarmSender);

        // Tell the user about what we did.
        Toast.makeText(A.this, R.string.repeating_scheduled,
                Toast.LENGTH_LONG).show();

}

private void stopAlarm(){

    // And cancel the alarm.
        AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
        am.cancel(mAlarmSender);

        // Tell the user about what we did.
        Toast.makeText(B.this, R.string.repeating_unscheduled,
                Toast.LENGTH_LONG).show();

}

==============

public class RepeatAlarm extends Service {
    NotificationManager mNM;
    @Override
    public void onCreate() {
        mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);


        showNotification();

        Thread thr = new Thread(null, mTask, "RepeatAlarm");
        thr.start();

    }

    @Override
    public void onDestroy() {

        mNM.cancel(R.string.alarm_service_started);
        Toast.makeText(this, R.string.alarm_service_finished, Toast.LENGTH_SHORT).show();
    }

    /**
     * The function that runs in our worker thread
     */
    Runnable mTask = new Runnable() {
        public void run() {

            long endTime = System.currentTimeMillis() + 15*1000;
            while (System.currentTimeMillis() < endTime) {
                synchronized (mBinder) {
                    try {
                        mBinder.wait(endTime - System.currentTimeMillis());

                    } catch (Exception e) {
                    }
                }
            }


            RepeatAlarm.this.stopSelf();
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub

        return mBinder;
    }

    /**
     * Show a notification while this service is running.
     */
    private void showNotification() {

        CharSequence text = getText(R.string.alarm_service_started);

        Notification notification = new Notification(R.drawable.icon, text,
                System.currentTimeMillis());

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, B.class), 0);

        // Set default sound
        notification.defaults |= Notification.DEFAULT_SOUND;
        //Set the default Vibration
        notification.defaults |= Notification.DEFAULT_VIBRATE;
        // Set the light pattern
        notification.ledARGB = 0xff00ff00;
        notification.ledOnMS = 300;
        notification.ledOffMS = 1000;
        notification.flags |= Notification.FLAG_SHOW_LIGHTS;


        //Custom notification view
        RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.notification);
        contentView.setImageViewResource(R.id.image, R.drawable.icon);
        contentView.setTextViewText(R.id.text, "Notification");
        notification.contentView = contentView;

        notification.contentIntent = contentIntent;

        // Send the notification.
        // We use a layout id because it is a unique number.  We use it later to cancel.
        mNM.notify(R.string.alarm_service_started, notification);
    }

    /**
     * This is the object that receives interactions from clients.  See RemoteService
     * for a more complete example.
     */
    private final IBinder mBinder = new Binder(){
        @Override
        protected boolean onTransact(int code, Parcel data, Parcel reply,
                int flags) throws RemoteException {
                return super.onTransact(code, data, reply, flags);
            }
    };
}

Сейчас я пытаюсь попробовать второй случай, для этого я поместил 2 кнопки в макет уведомлений, которые называются Reschedule и Cancel, но в этом случае мой вид не отображается в окне уведомлений, я гуглил последние 2 дня но не повезло, сейчас это очень тревожная ситуация для меня, я должен завершить ее любым способом к концу дня. Поэтому любые предложения или обходные пути будут чрезвычайно полезны для меня.

Спасибо

Ashish

...