在状态栏显示通知



mainactivity

package com.example.androit_test;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
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  {

	private Button bt_notification;
	private int notificationId = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		bt_notification = (Button) findViewById(R.id.bt_notifi);
		bt_notification.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				displayNotification();
			}
		});
	}
	
	public void displayNotification(){
		Intent i = new Intent(MainActivity.this,NotificationView.class);
		i.putExtra("notificationId", notificationId);
		
		//pending对象可以代表应用程序帮助在后面某个时候执行一个动作,而不考虑应用程序是否正在运行
		//参数:应用程序上下文,请求码,intent,标志
		PendingIntent intent = PendingIntent.getActivity(MainActivity.this, 0, i, 0);
		NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		
		Notification notification = new Notification(R.drawable.ic_launcher, "This is Test one", System.currentTimeMillis());
		
		CharSequence title = "Test_1";
		CharSequence contactTest = "if i can success?";
		
		notification.setLatestEventInfo(MainActivity.this, title, contactTest, intent);
		
		notification.vibrate = new long[]{100,250,100,500};
		nm.notify(notificationId, notification);
		
	}
}

package com.example.androit_test;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.Intent;
import android.os.Bundle;

public class NotificationView extends Activity {
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.a);
		
		NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		
		nm.cancel(getIntent().getExtras().getInt("notificationId"));
	}
}


你可能感兴趣的:(在状态栏显示通知)