BroadcastReceiver and Notification 搭配使用

MainActivity :
package com.amaker.zzl;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
	MyReceiver r = new MyReceiver();
    private Button btn_send;
    public static final String MY_ACTION = "com.amaker.zzl.action";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        btn_send = (Button) findViewById(R.id.send_button1);
        
        btn_send.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//发出一个广播,指定一个action
				sendBroadcast(new Intent(MY_ACTION));
			}
		});
    }
    //在onResume这个方法里面注册广播接收器
    //这里采用动态方法来注册广播接收器
    @Override
    protected void onResume() {
    	super.onResume();
    	IntentFilter f = new IntentFilter();
    	f.addAction(MY_ACTION);
    	registerReceiver(r, f);
    }
  //在onPause这个方法里取消注册
	@Override
	protected void onPause() {
		super.onPause();
		unregisterReceiver(r);
	}
		
}



MyReceiver:
package com.amaker.zzl;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyReceiver extends BroadcastReceiver{
	private NotificationManager nm;
	private Notification n;
	public static final int ID = 1;
	/**
	 * 广播接收器收到广播后,发出一个通知
	 * ZZL
	 */
	@Override
	public void onReceive(Context context, Intent intent) {
		String service = context.NOTIFICATION_SERVICE;
		nm = (NotificationManager) context.getSystemService(service);
		n = new Notification();
		//定义通知的一些属性
		n.icon = R.drawable.icon;
		n.tickerText = "tickerText...";
		n.when = System.currentTimeMillis();
		PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(), 0);
		n.setLatestEventInfo(context, "通知标题", "具体的通知内容", contentIntent);
		
		//利用通知管理器把封装好的通知发出
		nm.notify(ID, n);
	}

}


main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent">
	<Button
		android:text="SEND"
		android:id="@+id/send_button1"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content" />
</LinearLayout>

你可能感兴趣的:(notification)