09.02.2017 Views

creez-des-applications-pour-android

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

5.2 Les services<br />

Pour faire en sorte qu’un service se lance au premier plan, on appelle void startForeground(int<br />

id, Notification notification). Comme vous pouvez le voir, vous devez fournir un identifiant<br />

<strong>pour</strong> la notification avec id, ainsi que la notification à afficher.<br />

import <strong>android</strong>.app.Activity;<br />

import <strong>android</strong>.app.Notification;<br />

import <strong>android</strong>.app.NotificationManager;<br />

import <strong>android</strong>.app.PendingIntent;<br />

import <strong>android</strong>.content.Context;<br />

import <strong>android</strong>.content.Intent;<br />

import <strong>android</strong>.os.Bundle;<br />

import <strong>android</strong>.view.View;<br />

import <strong>android</strong>.widget.Button;<br />

public class MainActivity extends Activity {<br />

public int ID_NOTIFICATION = 0 ;<br />

@Override<br />

public void onCreate(Bundle savedInstanceState) {<br />

super.onCreate(savedInstanceState);<br />

setContentView(R.layout.activity_main);<br />

Button b = (Button) findViewById(R.id.launch);<br />

b.setOnClickListener(new View.OnClickListener() {<br />

@Override<br />

public void onClick(View view) {<br />

// L'icône sera une petite loupe<br />

int icon = R.drawable.ic_action_search ;<br />

// Le premier titre affiché<br />

CharSequence tickerText = "Titre de la notification" ;<br />

// Daté de maintenant<br />

long when = System.currentTimeMillis();<br />

// La notification est créée<br />

Notification notification = new Notification(icon, tickerText, when);<br />

Intent notificationIntent = new Intent(MainActivity.this, MainActivity.class);<br />

notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);<br />

PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this, 0, n<br />

notification.setLatestEventInfo(MainActivity.this, "Titre", "Texte", contentInt<br />

}<br />

}<br />

}<br />

});<br />

startForeground(ID_NOTIFICATION, notification)<br />

Vous pouvez ensuite enlever le service du premier plan avec void stopForeground(boolean<br />

361

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!