Форум программистов, компьютерный форум, киберфорум
Программирование Android
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
 
Рейтинг 4.62/29: Рейтинг темы: голосов - 29, средняя оценка - 4.62
0 / 0 / 0
Регистрация: 29.08.2013
Сообщений: 32
1

Показ уведомлений для определенной даты

08.10.2013, 19:19. Показов 5437. Ответов 20
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Нужно выводить уведомления в определённый день и с периодичностью в один месяц.
Системную дату я получаю, но проверка условия(через if), наступления даты оповещeния, всегда выдаёт TRUE и выскакивает уведомление в статус-баре.
Хотелось бы знать почему так? Как правильно проверять дату? Please, форумчане ответьте...
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package ru.project.testinfomats;
 
 
import java.util.Calendar;
 
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
 
public class NotificationService extends Activity { 
    
    @Override  
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.empty);
        
        final int NOTIFY_ID = 1101;
        long when = System.currentTimeMillis(); // Выясним системное время!!!
        Calendar c = Calendar.getInstance();
        CharSequence date = c.get(Calendar.DAY_OF_MONTH) + "." + c.get(Calendar.MONTH) + "." + c.get(Calendar.YEAR); //Получаем дату в формате dd.mm.yyyy
        
        NotificationManager mNotificationManager = (NotificationManager)
                getSystemService(Context.NOTIFICATION_SERVICE);
    
        int icon = R.drawable.ic_launcher;
        CharSequence contentTitle = date; // Выводим дату в заголовке уведомления
        CharSequence contentText = "Пример уведомления!";
    Notification ntf = new Notification(icon, null, when); // Создаем экземпляр уведомления, и передаем ему наши параметры
    Context context = getApplicationContext();     
    Intent notificationIntent = new Intent(this, MainMenu.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    ntf.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    mNotificationManager.notify(NOTIFY_ID, ntf); // Показываем наше уведомление через менеджер передав его ID 
    }
}
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
08.10.2013, 19:19
Ответы с готовыми решениями:

Изменение системной даты и времени только для определенной программы
Всем привет. Вопрос несколько необычный. Существует ли способ задать дату только для одной...

Программа должна работать до определенной даты у пользователя, независимо, что он выставит в настройках даты и времени
Добрый день, уважаемые! Уже сломал голову, но ничего не могу придумать. Дело вот в чем: есть...

При выборе даты в календаре - заполнять ячейки по порядку до определенной даты и рядом высвечивать день недели
Здравствуйте. Нужна ваша помощь. В программе есть написанный на VBA календарь. нужно написать код,...

Лаунчер для игры: сделать авторизацию, запуск клиента, показ скина, и показ личного счета
Доброго времени суток ! Я создаю лаунчер одной игры( Minecraft ) Можете ли вы мне помочь с этим?...

20
374 / 361 / 52
Регистрация: 02.10.2009
Сообщений: 712
Записей в блоге: 4
08.10.2013, 19:55 2
Что-то никакой проверки в коде я не вижу.
0
0 / 0 / 0
Регистрация: 29.08.2013
Сообщений: 32
08.10.2013, 20:03  [ТС] 3
Я убрал её, т. к. она не работала...
Но теперь вот полный код:
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package ru.project.testinfomats;
 
 
import java.util.Calendar;
 
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
 
public class NotificationService extends Activity { 
    
    @Override  
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.empty);
        
        final int NOTIFY_ID = 1101;
        long when = System.currentTimeMillis(); // Выясним системное время!!!
        Calendar c = Calendar.getInstance();
        CharSequence date = c.get(Calendar.DAY_OF_MONTH) + "." + c.get(Calendar.MONTH) + "." + c.get(Calendar.YEAR); //Получаем дату в формате dd.mm.yyyy
        
        if(date  != "3.9.2033") {
        NotificationManager mNotificationManager = (NotificationManager)
                getSystemService(Context.NOTIFICATION_SERVICE);
    
        int icon = R.drawable.ic_launcher;
        CharSequence contentTitle = date; // Выводим дату в заголовке уведомления
        CharSequence contentText = "Пример уведомления!";
    Notification ntf = new Notification(icon, null, when); // Создаем экземпляр уведомления, и передаем ему наши параметры
    Context context = getApplicationContext();     
    Intent notificationIntent = new Intent(this, MainMenu.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    ntf.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    mNotificationManager.notify(NOTIFY_ID, ntf); // Показываем наше уведомление через менеджер передав его ID 
    }
    }
}
0
1162 / 986 / 1
Регистрация: 28.06.2012
Сообщений: 3,462
08.10.2013, 20:10 4
странная у вас проверка. строки сравниваются через equal если что.
1
374 / 361 / 52
Регистрация: 02.10.2009
Сообщений: 712
Записей в блоге: 4
08.10.2013, 20:12 5
ну, все понятно.
Java
1
if(date.equals("3.9.2033"))
1
1162 / 986 / 1
Регистрация: 28.06.2012
Сообщений: 3,462
08.10.2013, 20:13 6
также для сравнения дат у календаря есть compareTo.
может вам AlarmManager нужен?
0
0 / 0 / 0
Регистрация: 29.08.2013
Сообщений: 32
08.10.2013, 20:25  [ТС] 7
Спасибо огромное! Теперь всё работает.
Если вас не затруднит, не могли бы вы рассказать(или предоставить ссылки, материал для изучения) как запускать уведомления через фоновой процесс(Service).
0
1162 / 986 / 1
Регистрация: 28.06.2012
Сообщений: 3,462
08.10.2013, 20:31 8
http://developer.android.com/g... vices.html
0
0 / 0 / 0
Регистрация: 29.08.2013
Сообщений: 32
08.10.2013, 20:57  [ТС] 9
Извините, а как проверить несколько условий? Через or не получается...
0
374 / 361 / 52
Регистрация: 02.10.2009
Сообщений: 712
Записей в блоге: 4
08.10.2013, 21:27 10
Java
1
2
if(condition1 || condition2) // или
if(condition1 && condition2) // и
1
0 / 0 / 0
Регистрация: 29.08.2013
Сообщений: 32
08.10.2013, 21:54  [ТС] 11
Да, блин, точно... Чё то я даже логическое или(||) позабыл. Простите...
И теперь ещё один вопрос, исходя из того что я не нашёл полезным(http://developer.android.com/g... ces.html): как код ниже "засунуть" в фоновой процесс?
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import java.util.Calendar;
 
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
 
public class NotificationService extends Activity {
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.empty);
        
        final int NOTIFY_ID = 1101;
        long when = System.currentTimeMillis(); // Выясним системное время!!!
        Calendar c = Calendar.getInstance();
        CharSequence date = c.get(Calendar.DAY_OF_MONTH) + "." + c.get(Calendar.MONTH) + "." + c.get(Calendar.YEAR);
        
        if((date.equals("8.9.2013")) || (date.equals("8.10.2013"))) {
        NotificationManager mNotificationManager = (NotificationManager)
                getSystemService(Context.NOTIFICATION_SERVICE);
    
        int icon = R.drawable.ic_launcher;
        CharSequence contentTitle = date; // Текст заголовка уведомления
        CharSequence contentText = "Пример уведомления! =)"; //Текст уведомления
    
        Notification ntf = new Notification(icon, null, when);
        Context context = getApplicationContext();     
    
        Intent notificationIntent = new Intent(this, MainMenu.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        ntf.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
        mNotificationManager.notify(NOTIFY_ID, ntf);
        }
    }
}
0
66 / 56 / 6
Регистрация: 28.12.2011
Сообщений: 322
08.10.2013, 22:33 12
Цитата Сообщение от SherlockH Посмотреть сообщение
"засунуть" в фоновой процесс
http://developer.android.com/r... cTask.html
0
0 / 0 / 0
Регистрация: 29.08.2013
Сообщений: 32
08.10.2013, 22:58  [ТС] 13
Нет. Извините я не совсем это имел ввиду...
Нужно чтобы код работал даже при закрытом приложении. Примерно как будильник...
0
66 / 56 / 6
Регистрация: 28.12.2011
Сообщений: 322
08.10.2013, 23:11 14
Если вам требуется чтобы что-то выполнилось по расписанию (как будильник), то используйте класс AlarmManager.
Если без расписания, а по выполнению какого-то условия, то создаете службу (класс IntentService).

По реализации обоих объектов много примеров в сети, я уверен вы их найдете
0
0 / 0 / 0
Регистрация: 29.08.2013
Сообщений: 32
08.10.2013, 23:46  [ТС] 15
Да, скорее IntentService.
Но как всё реализовать, прописать? Что обязательно в коде(Creat, Start, Stop)? Что прописать в Манифест?
0
374 / 361 / 52
Регистрация: 02.10.2009
Сообщений: 712
Записей в блоге: 4
09.10.2013, 01:11 16
IntentService не подойдет, потому, что, для того, что бы он начал работать, ему нужно отправить Intent, а откуда его отправлять если приложение должно работать в фоне ?
Вам нужен простой Service, возможно, он должен стартовать при включении девайса, что бы создать AlarmManager, который сработает через определенное время.
Все что вам нужно по сервису, можно найти здесь:
http://startandroid.ru/ru/urok... rimer.html
0
0 / 0 / 0
Регистрация: 29.08.2013
Сообщений: 32
09.10.2013, 01:34  [ТС] 17
Вот я своими силами реализовал вот такое: в главном меню нажимается одна кнопка, и, предположительно, запускается мой фоновой процесс(NotificationService). Так?
Java
1
2
3
4
5
6
7
8
9
final Button StartServiceAndViewAList = (Button)findViewById(R.id.List_cities_and_districts_of_RT); 
 
        StartServiceAndViewAList.setOnClickListener(new View.OnClickListener() {
        public void onClick(View s) {
            startService(new Intent(MainMenu.this, NotificationService.class)); 
            Intent i = new Intent(MainMenu.this, ListCitiesAndDistrictsOfRT.class);
            startActivity(i);   
        }
        });
А сам процесс выглядит так:
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package ru.project.testinfomats;
 
import java.util.Calendar;
 
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
 
public class NotificationService extends Service {
 
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    public void onCreate() {
        Toast.makeText(this, "Service Created", 0); 
 
        
        final int NOTIFY_ID = 1101;
        long when = System.currentTimeMillis();
        
        Calendar c = Calendar.getInstance();
        CharSequence date = c.get(Calendar.DAY_OF_MONTH) + "." + c.get(Calendar.MONTH) + "." + c.get(Calendar.YEAR);
            if((date.equals("9.9.2013")) || (date.equals("9.10.2013")) || (date.equals("9.11.2013")) ||
               (date.equals("9.0.2014")) || (date.equals("9.1.2014")) || (date.equals("9.2.2014")) ||
               (date.equals("9.3.2014")) || (date.equals("9.4.2014")) || (date.equals("9.5.2014")) ||
               (date.equals("9.6.2014")) || (date.equals("9.7.2014")) || (date.equals("9.8.2014")) ||
               (date.equals("9.9.2014")) || (date.equals("9.10.2014")) || (date.equals("9.11.2014"))) { 
                
                    NotificationManager mNotificationManager = (NotificationManager)
                        getSystemService(Context.NOTIFICATION_SERVICE);
            
                    int icon = R.drawable.ic_launcher;
                    CharSequence contentTitle = "Уважаемый пользователь!";
                    CharSequence contentText = "Пора оплачивать квитанции! =)";
            
                    @SuppressWarnings("deprecation")
                    Notification ntf = new Notification(icon, contentTitle, when);
                    Context context = getApplicationContext();     
                    
                    Intent notificationIntent = new Intent(this, MainMenu.class);
                    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
                    
                    mNotificationManager.notify(NOTIFY_ID, ntf);
            }
        
    }
}
Но в логах выдаётся ошибка:
XML
1
10-09 00:53:44.651: E/AndroidRuntime(16659): FATAL EXCEPTION: main java.lang.RuntimeException: Unable to create service ru.project.testinfomats.NotificationService: java.lang.IllegalArgumentException: contentView required: pkg=ru.project.testinfomats id=1101 notification=Notification(vibrate=null,sound=null,defaults=0x0,flags=0x0)
0
0 / 0 / 0
Регистрация: 29.08.2013
Сообщений: 32
09.10.2013, 02:54  [ТС] 18
Товарищи! Ну помогите!!!
Никак не могу разобраться с логом и кодом.
Всё это прилагается:
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class MainMenu extends Activity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_menu);
        startService(new Intent(MainMenu.this, NotificationService.class));
        
        Button openURL = (Button) findViewById(R.id.openURL);
        openURL.setOnClickListener(new OnClickListener() {
            
        public void onClick(View v) {
            String url = "https://uslugi.tatar.ru/"; 
                    Intent intent1 = new Intent(Intent.ACTION_VIEW);
                    intent1.setData(Uri.parse(url));
                    startActivity(intent1);            
            }
        });
        
        final Button StartServiceAndViewAList = (Button)findViewById(R.id.List_cities_and_districts_of_RT); 
 
        StartServiceAndViewAList.setOnClickListener(new View.OnClickListener() {
        public void onClick(View s) { 
            startActivity(new Intent(MainMenu.this, ListCitiesAndDistrictsOfRT.class));   
        }
        });
              
        Button About = (Button) findViewById(R.id.about_program);
        About.setOnClickListener(new View.OnClickListener() {
        public void onClick(View s) {           
            startActivity(new Intent(MainMenu.this, About.class));   
        }
        });
        
    }
}
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public class NotificationService extends Service {
 
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    void someTask() { }
    
    public int onStartCommand(Intent intent, int flags, int startId) {
        someTask();
        return super.onStartCommand(intent, flags, startId);
    }
 
    public void onDestroy() {
        super.onDestroy();
    }
    
    public void onCreate() {
        final int NOTIFY_ID = 1;
        long when = System.currentTimeMillis();
        
        Calendar c = Calendar.getInstance();
        CharSequence date = c.get(Calendar.DAY_OF_MONTH) + "." + c.get(Calendar.MONTH) + "." + c.get(Calendar.YEAR);
            if((date.equals("9.9.2013")) || (date.equals("9.10.2013")) || (date.equals("9.11.2013")) ||
               (date.equals("9.0.2014")) || (date.equals("9.1.2014")) || (date.equals("9.2.2014")) ||
               (date.equals("9.3.2014")) || (date.equals("9.4.2014")) || (date.equals("9.5.2014")) ||
               (date.equals("9.6.2014")) || (date.equals("9.7.2014")) || (date.equals("9.8.2014")) ||
               (date.equals("9.9.2014")) || (date.equals("9.10.2014")) || (date.equals("9.11.2014"))) { 
                
                    NotificationManager mNotificationManager = (NotificationManager)
                        getSystemService(Context.NOTIFICATION_SERVICE);
            
                    int icon = R.drawable.ic_launcher;
                    CharSequence contentTitle = "Уважаемый пользователь!";
                    CharSequence contentText = "Пора оплачивать квитанции! =)";
            
                    @SuppressWarnings("deprecation")
                    Notification ntf = new Notification(icon, contentTitle, when);
                    Context context = getApplicationContext();
                    
                    Intent notificationIntent = new Intent(this, MainMenu.class);
                    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
                    
                    mNotificationManager.notify(NOTIFY_ID, ntf);
            }
    }
}
Миниатюры
Показ уведомлений для определенной даты  
0
1162 / 986 / 1
Регистрация: 28.06.2012
Сообщений: 3,462
09.10.2013, 03:32 19
нужно выкладывать код полностью чтобы сопоставить с логами.

Добавлено через 30 секунд
а логи можно просто скопировать.

Добавлено через 1 минуту
http://stackoverflow.com/quest... -a-service

Добавлено через 1 минуту
http://stackoverflow.com/quest... streceiver
1
0 / 0 / 0
Регистрация: 29.08.2013
Сообщений: 32
09.10.2013, 05:54  [ТС] 20
Спасибо! Удалось решить...
Теперь новая проблема: не обрабатывается нажатие на уведомление. Нужно чтобы при нажатии на уведомление открывался MainMenu.class?

Добавлено через 34 минуты
Предыдущая проблема решена!
Но возникла одна трудность: после просмотра уведомления оно снова запускается, значок висит в трее... Как-будто не исчезал оттуда.
Как можно(нужно) предотвратить эту настойчивость моего приложения???
0
09.10.2013, 05:54
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
09.10.2013, 05:54
Помогаю со студенческими работами здесь

Показ даты в DBMemo
Привет! Я делаю программу с базой данных, есть пункт "Что сказал клиент при последнем звонке?" -...

Access 2007: отключить показ даты создания/изменения объектов
Как в основном окне Access'a отключить показ даты создания/изменения объектов?

Как в области уведомлений панели задач переместить значок Центра уведомлений?
Всем привет. Переставил Винду и внезапно в самом краю не часы, а этот центр. 7 лет пользуюсь пк и...

Отсчёт времени до определённой даты
Нужно реализовать: Например 20.11.2016 в 15-30 будет какое-то событие (например день печенек)...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
20
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru