Имеется такой рабочий код с сайта старт андроид:
package ru.startandroid.develop.p0991servicenotification;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
public final static String FILE_NAME = "filename";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.tv);
Intent intent = getIntent();
String fileName = intent.getStringExtra(FILE_NAME);
if (!TextUtils.isEmpty(fileName))
tv.setText(fileName);
}
public void onClickStart(View v) {
startService(new Intent(this, MyService.class));
}
public void onClickStop(View v) {
stopService(new Intent(this, MyService.class));
}
}
и сервис:
package ru.startandroid.develop.p0991servicenotification;
import java.util.concurrent.TimeUnit;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class MyService extends Service {
NotificationManager nm;
@Override
public void onCreate() {
super.onCreate();
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
public int onStartCommand(Intent intent, int flags, int startId) {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
sendNotif();
return super.onStartCommand(intent, flags, startId);
}
void sendNotif() {
// 1-я часть
Notification notif = new Notification(R.drawable.ic_launcher, "Text in status bar",
System.currentTimeMillis());
// 3-я часть
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra(MainActivity.FILE_NAME, "somefile");
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
// 2-я часть
notif.setLatestEventInfo(this, "Notification's title", "Notification's text", pIntent);
// ставим флаг, чтобы уведомление пропало после нажатия
notif.flags |= Notification.FLAG_AUTO_CANCEL;
// отправляем
nm.notify(1, notif);
}
public IBinder onBind(Intent arg0) {
return null;
}
}
Работает все на ура, только вот вопрос, может, кто знает, как удалить уведомление при закрытии приложения?