package com.xiangqiao.notification;
import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, IntentService.class);
startService(intent);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.notify);
button.setOnClickListener(listener);
}
@Override
protected void onStart() {
super.onStart();
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(IntentService.NOTIFY_ID);
}
}
package com.xiangqiao.notification;
import android.R.anim;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class IntentService extends android.app.IntentService {
public static final int NOTIFY_ID = 1;
public IntentService() {
super("IntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.i("sys", "开始下载");
showNotify(false);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("sys", "下载完毕");
showNotify(true);
}
public void showNotify(boolean finish) {
Notification notification;
Intent intent = new Intent();
intent.setClass(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (!finish) {
notification = new Notification(android.R.drawable.ic_dialog_alert,
"开始下载", System.currentTimeMillis());
notification.setLatestEventInfo(this, "下载", "正在下载", contentIntent);
} else {
notification = new Notification(android.R.drawable.ic_dialog_alert,
"下载完毕", System.currentTimeMillis());
notification.setLatestEventInfo(this, "下载", "下载完毕", contentIntent);
}
// option选项
notification.defaults = Notification.DEFAULT_ALL;
notificationManager.notify(NOTIFY_ID, notification);
}
}