Service не коректная работа

Размещайте ссылки на ваши собственные приложения с целью пиара или для бета-тестирования.
Правила форума
О возможности разместить информацию о вашем приложении на главной странице сайта читайте здесь: http://startandroid.ru/ru/about/pomosch ... henii.html
Ответить
ANdriy123456
Сообщения: 138
Зарегистрирован: 27 июн 2014, 01:41

Service не коректная работа

Сообщение ANdriy123456 » 12 янв 2015, 00:30

есть сервис который должен отправлять notifications через равные промежутки времени. если я пользуюсь телефоном, то проблем нет. если заблокировать его и оставить на нескольки минут, то через несколько секунд все они появляються одновремено. как это исправить?

Код: Выделить всё

public class S_GetLastSound extends Service {
	
	public static Timer t = null;
	  
	  @Override
	  public void onCreate() {
		t = new Timer();
	    super.onCreate();
	  }

	  public int onStartCommand(Intent intent, int flags, int startId) {
		    
		  
		  int TIME_OUT = 1*60*1000; 
		  t.scheduleAtFixedRate(new TimerTask() {
				@Override
				public void run() {
					sendNotif();
				}
	        }, 0, TIME_OUT); 	    
	    return Service.START_STICKY;
	  }
	  
	  void sendNotif() {
		  Context context = getApplicationContext();

	        Intent notificationIntent = new Intent(context, MainActivity.class);
	        PendingIntent contentIntent = PendingIntent.getActivity(context,
	                0, notificationIntent,
	                PendingIntent.FLAG_CANCEL_CURRENT);

	        Resources res = context.getResources();
	        Notification.Builder builder = new Notification.Builder(context);

	        builder.setContentIntent(contentIntent)
	                .setSmallIcon(R.drawable.ic_launcher)
	                // большая картинка
	                .setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.ic_launcher))
	                .setTicker("Последнее китайское предупреждение!")
	                .setWhen(System.currentTimeMillis())
	                .setAutoCancel(true)
	                .setContentTitle("Напоминание")
	                .setContentText("Пора покормить кота"); // Текст уведомленимя

	        // Notification notification = builder.getNotification(); // до API 16
	        Notification notification = builder.build();

	        NotificationManager notificationManager = (NotificationManager) context
	                .getSystemService(Context.NOTIFICATION_SERVICE);        
	        notificationManager.notify((int) System.currentTimeMillis() + 1, notification); 
	  }
	  
	  @Override
	public void onDestroy() {
		t.cancel();
		super.onDestroy();
	}
	  
	  public IBinder onBind(Intent arg0) {
	    return null;
	  }
	}

Код: Выделить всё

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.emple.noti"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".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>
        
        <service
            android:name="com.emple.noti.S_GetLastSound"
            android:enabled="true"
            android:exported="true"
            android:process=":lastsound">
        </service> 
    </application>
</manifest>

Аватара пользователя
klblk
Сообщения: 1097
Зарегистрирован: 18 окт 2012, 11:17
Откуда: г. Красноярск

Re: Service не коректная работа

Сообщение klblk » 12 янв 2015, 08:11

Вероятно правильнее использовать не сервис а AlarmManager (есть урок).
Если же нужен именно сервис, то необходим будет режим Foreground (есть урок) и WakeLock (урока нет, но в документации все просто описано). Без первого система может убить сервис когда ей захочется, без второго таймер будет засыпать вместе с процессором (вероятно именно это и происходит в вашем случае)

Ответить