我们在插入USB的时候会在StatusBar上提示USB插入的信息,这是怎么做到的呢?其实很简单。下面是一个简单的例子。
先看下效果图
图1(通知在Notifications上面,位于Ongoing下)
图2(通知在Notifications下方)
代码很简单,不作分析,自己看吧。
public class SendNotification extends Activity { private NotificationManager nm; private Button btnSend; private Button btnCancel; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); setupViews(); } private void setupViews() { btnSend = (Button) findViewById(R.id.send); btnCancel = (Button) findViewById(R.id.cancel); String service = Context.NOTIFICATION_SERVICE; nm = (NotificationManager) getSystemService(service); // get system service final Context context = SendNotification.this; btnSend.setOnClickListener(new OnClickListener() { public void onClick(View v) { Notification n = new Notification(); n.icon = R.drawable.icon; n.tickerText = "Notification"; n.when = System.currentTimeMillis(); //n.flags=Notification.FLAG_ONGOING_EVENT; Intent intent = new Intent(context, SendNotification.class); PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0); n.setLatestEventInfo(context, "title","content", pi); nm.notify(1, n); } }); btnCancel.setOnClickListener(new OnClickListener() { public void onClick(View v) { nm.cancel(1); } }); } }
如果想在Ongoing列表项中显示通知,加上这一句就OK n.flags=Notification.FLAG_ONGOING_EVENT;
到此为止这个简单的demo完成,更具老板的要求,现在需要在StatusBar上添加Wifi BlueTooth等开关控制,怎么办呢?在Android2.1上稍微复杂点,要到FrameWork下修改statusBar的代码,Android2.3好像可以直接变异成APK,调试等都方便了许多。且听下回我详细分解吧~