现在的位置: 首页 > 综合 > 正文

Notification顶部状态栏和下拉任务栏通知

2018年05月06日 ⁄ 综合 ⁄ 共 5316字 ⁄ 字号 评论关闭

界面很简单,功能也实现的很简单,

一个简单的DEMO,

尴尬欢迎转载,请加地址http://blog.csdn.net/jing110fei/article/details/39055809

1主页面

2点击开启发送后

      

设置每隔10秒发送1次直到用户点击通知栏或点击停止发送

点击通知栏,会跳转

首先的一点是,为了能使所有Actvity都能方便的调用同一对象或者方法,我自定义了Application

public class AllApplication extends Application{
	public ScheduledExecutorService scheduledThreadPool;
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		scheduledThreadPool=null;
	}	
}

为了使这个Application生效,需要在AndroidManifest.xml中替换原来的

<application
        android:name=".AllApplication"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
</application>

不多说,直接上代码,注释就在代码里

首先是两个简单的布局文件

activity_notification_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
	<Button 
	    android:id="@+id/Button1"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="开启发送通知栏"/>
	<Button 
	    android:id="@+id/Button2"
	    android:layout_width="fill_parent"
	    android:layout_height="wrap_content"
	    android:text="停止发送通知栏"/>
   
</LinearLayout>

activity2.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
	<TextView 
	    android:id="@+id/text1"
	    android:layout_width="fill_parent"
	    android:layout_height="fill_parent"
	    android:background="@drawable/setbar_bg"
	    />
</LinearLayout>

主文件NotificationMainActivity.java

public class NotificationMainActivity extends Activity implements OnClickListener {
	private static Button button1,button2;
	private AllApplication application;
	public NotificationManager mNotificationManager;
	//定义count为通知内容用以测试
	public int count=0;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notification_main);
       // 获取全局上下文对象
        application=(AllApplication) getApplication();
        button1=(Button)findViewById(R.id.Button1);
        button1.setOnClickListener(this);
        findViewById(R.id.Button2).setOnClickListener(this);
       
        
    }
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.Button1:
			count=0;
			 /**创建一个可安排在给定延迟后运行命令或者定期地执行的线程池。 效果类似于Timer定时器
	         * ScheduledThreadPool是一个固定大小的线程池,与FixedThreadPool类似,执行的任务是定时执行。 
	         *  */
			application.scheduledThreadPool = Executors.newScheduledThreadPool(1);
			//5秒后执行,以后每10秒执行一次
			application.scheduledThreadPool.scheduleWithFixedDelay(new CustomTask(), 5, 10,
							TimeUnit.SECONDS);
			
			break;
		case R.id.Button2:
			application.scheduledThreadPool.shutdown();
			application.scheduledThreadPool=null;	
			//取消通知栏显示
			mNotificationManager.cancel(100);
			break;
		}
	}
	class CustomTask implements Runnable {

		public void run() {
			// TODO Auto-generated method stub
			Bundle date=new Bundle();
			date.putInt("count", count++);
			Message message = Message.obtain(sHandler, 1);	
			message.setData(date);
			message.sendToTarget();
		}
		
	}
	private Handler sHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 1:
				int counts=msg.getData().getInt("count");
				mNotificationManager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
				//手机最上方提示栏的内容
				Notification notification = new Notification(R.drawable.ic_launcher,
						"count值发生变化当前为"+count, System.currentTimeMillis());
				/**
				 * 设置添加声音
				 * 或者使用以下几种方式 
				 * notification.sound = Uri.parse("file:///sdcard/notification/ringer.mp3"); 
				 * notification.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6"); 
				 * 如果想要让声音持续重复直到用户对通知做出反应,则可以在notification的flags字段增加"FLAG_INSISTENT" 
				 * 如果notification的defaults字段包括了"DEFAULT_SOUND"属性,则这个属性将覆盖sound字段中定义的声音 
				 * 还可以添加震动 notification.defaults |= Notification.DEFAULT_VIBRATE; 
				 * 或者可以定义自己的振动模式: 
				 * long[] vibrate = {0,100,200,300}; //0毫秒后开始振动,振动100毫秒后停止,再过200毫秒后再次振动300毫秒 
				 * notification.vibrate = vibrate; 
				 * */
				notification.defaults |= Notification.DEFAULT_SOUND;
				/**
				 * notification.flags |= FLAG_AUTO_CANCEL; //在通知栏上点击此通知后自动清除此通知 
				 * notification.flags |= FLAG_INSISTENT; //重复发出声音,直到用户响应此通知 
				 */
				notification.flags = Notification.FLAG_AUTO_CANCEL;
				//通知栏的title
				CharSequence contentTitle = "测试";
				//通知栏的内容
				CharSequence contentText="count值发生变化快去看看吧";
				//当点击通知栏时给其设置一个跳转的页面
				Intent notificationIntent = new Intent();			
				notificationIntent.setClass(getApplicationContext(),
						Activity2.class);	
				//在这里传值给点击跳转的Intent
				notificationIntent.putExtra("count", counts);
				PendingIntent contentIntent = PendingIntent.getActivity(
				getApplicationContext(), 0, notificationIntent,
				PendingIntent.FLAG_UPDATE_CURRENT);		
				//将上面的设置加入通知栏
				notification.setLatestEventInfo(getApplicationContext(),
					contentTitle, contentText, contentIntent);

			// 用mNotificationManager的notify方法通知用户生成标题栏消息通知
			//这里的ID100,用来定义状态栏通知以及下拉任务栏通知,并且用来在需要的时候,将这两样取消
			mNotificationManager.notify(100, notification);
				break;
			default:
				break;
			}
		}
		
	};
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	
}

点击跳转后的文件Activity2.java

public class Activity2 extends Activity{

	private AllApplication application;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		 application=(AllApplication) getApplication();
		application.scheduledThreadPool.shutdown();
		 application.scheduledThreadPool=null;	
		 setContentView(R.layout.activity2);
		 Bundle bundle=getIntent().getExtras();
		 int count=bundle.getInt("count");
		 TextView textView=(TextView)findViewById(R.id.text1);
		 textView.setText("当前count值为"+count);
	}
	
}

好了,全部代码都在这里了。。。有不足的地方欢迎大家指正可怜

抱歉!评论已关闭.