09.02.2017 Views

creez-des-applications-pour-android

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

5 Concepts avancés<br />

private TextView mAffichageCompteur = null ;<br />

private int mCompteur = 0 ;<br />

public final static String EXTRA_COMPTEUR = "sdz.chapitreQuatre.intentservice.example<br />

@Override<br />

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

super.onCreate(savedInstanceState);<br />

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

mAffichageCompteur = (TextView) findViewById(R.id.affichage);<br />

mBouton = (Button) findViewById(R.id.bouton);<br />

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

@Override<br />

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

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

i.putExtra(EXTRA_COMPTEUR, mCompteur);<br />

mCompteur ++;<br />

mAffichageCompteur.setText("" + mCompteur);<br />

}<br />

}<br />

}<br />

});<br />

startService(i);<br />

Cliquer sur le bouton incrémente le compteur et envoie un intent qui lance un service qui s’appelle<br />

IntentServiceExample. L’intent est ensuite reçu et traité :<br />

package sdz.chapitreQuatre.intentservice.example;<br />

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

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

import <strong>android</strong>.util.Log;<br />

public class IntentServiceExample extends IntentService {<br />

private final static String TAG = "IntentServiceExample" ;<br />

public IntentServiceExample() {<br />

super(TAG);<br />

}<br />

@Override<br />

protected void onHandleIntent(Intent intent) {<br />

Log.d(TAG, "Le compteur valait : " + intent.getIntExtra(MainActivity.EXTRA_COMPTEUR<br />

int i = 0 ;<br />

354

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

Saved successfully!

Ooh no, something went wrong!