2016-02-15 3 views
0

Я хочу показать уведомление на главном экране. Это мой код:Продолжительность уведомления Android на главном экране

Notification.Builder mBuilder = new Notification.Builder(getApplicationContext()) 
.setContentTitle("Connection request") 
.setContentText("content text") 
.setSmallIcon(R.drawable.ic_done) 
.setContentIntent(pi) 
.setPriority(Notification.PRIORITY_HIGH); 

if (Build.VERSION.SDK_INT >= 21) 
    mBuilder.setVibrate(new long [0]); 

NotificationManager mNotificationManager = (NotificationManager) getSystemService(getApplicationContext().NOTIFICATION_SERVICE); 

mNotificationManager.notify(1300, mBuilder.build()); 

На этом этапе все работает нормально, НО уведомление исчезает через 5 секунд.

Возможно ли создать уведомление, например, когда мы получим входящий звонок? Или что-то еще продолжительное? Я имею в виду на главном экране.

Я знаю, что это возможно, потому что оно работает в приложениях вроде WhatsApp.

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

Спасибо!

EDIT

public class WaitConnectionService extends Service { 

public final static int START_CONNECTION = 1; 
private NotificationManager mNotificationManager; 

private Looper mServiceLooper; 
private ServiceHandler mServiceHandler; 

private final class ServiceHandler extends Handler { 
    public ServiceHandler(Looper looper) { 
     super(looper); 
    } 

    @Override 
    public void handleMessage(final Message msg) { 

     System.out.println("HANDLE MESSAGE"); 
     if (msg.what == START_CONNECTION) { 

      new Thread(new Runnable() { 
       @Override 
       public void run() { 

//      new TCPServer().run(); 

        Intent i = new Intent(WaitConnectionService.this, ListActivity.class); 

        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | 
          Intent.FLAG_ACTIVITY_SINGLE_TOP); 

        PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0, 
          i, 0); 

        Intent intent = new Intent(getApplicationContext(), SettingsActivity.class); 
        PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(), 
          (int) System.currentTimeMillis(), intent, 0); 

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext()) 
          .setContentTitle("Connection request") 
          .setContentText("content text") 
          .setSmallIcon(R.drawable.ic_done) 
          .setContentIntent(pi) 
          .setPriority(Notification.PRIORITY_MAX) 
          .setWhen(System.currentTimeMillis()) 
          .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) 
          .setUsesChronometer(true) 
          .addAction(new NotificationCompat.Action.Builder(R.drawable.ic_done, 
            "ok", pIntent).build()); 

        if (Build.VERSION.SDK_INT >= 21) 
         mBuilder.setVibrate(new long[0]); 

        NotificationManager mNotificationManager = 
          (NotificationManager) getSystemService(getApplicationContext().NOTIFICATION_SERVICE); 

        mNotificationManager.notify(1300, mBuilder.build()); 

       } 
      }).start(); 

     } 

    } 
} 

@Override 
public void onCreate() { 

    System.out.println("ON CREATE"); 
    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
    HandlerThread thread = new HandlerThread("My handler thread", Process.THREAD_PRIORITY_BACKGROUND); 
    thread.start(); 

    mServiceLooper = thread.getLooper(); 
    mServiceHandler = new ServiceHandler(mServiceLooper); 
} 

@Override 
public int onStartCommand(Intent intent, int flags, final int startId) { 

    System.out.println("ON START COMMAND"); 
    Message msg = mServiceHandler.obtainMessage(); 
    msg.what = START_CONNECTION; 
    msg.arg1 = startId; 
    mServiceHandler.sendMessage(msg); 

    return START_NOT_STICKY; 
} 

@Nullable 
@Override 
public IBinder onBind(Intent intent) { 
    return null; 
} 

@Override 
public void onDestroy() { 
    System.out.println("Service onDestroy("); 
} 
} 

И активность:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    ... 

    Intent intent1 = new Intent(this, WaitConnectionService.class); 
    intent1.putExtra("what", 1); 

    startService(intent1); 
} 

Когда я запускаю этот код начинается основной деятельности, и показывает уведомления только 5 сек.

найти выход из примера

https://github.com/googlesamples/android-LNotifications

ответ

0

Вы возвращающийся START_NOT_STICKY в onStartCommand() службы. Это означает, что ваш сервис автоматически остановится. Вместо этого используйте START_STICKY.

+0

Только 5 секунд ... – jQuick

+0

Вы пытаетесь это сделать. Для меня это не работает. Моя версия для Android - 6.0.1, и я пытаюсь использовать NotificationCompat и Notification, но ... только 5 сек. – jQuick

+0

Попробуйте протестировать его на более низкой версии. На этом устройстве может быть включен режим энергосбережения. Попробуйте изменить настройки. – Piyush

Смежные вопросы