在我們的相應程式啟動並執行時候為了不打斷當前程式的運行,我們經常會使用Notification來告知使用者有新來電或新的簡訊。
下面先介紹一下toast的簡單提醒:
private void baseToast(){ Toast.makeText(getApplicationContext(), "Hello toast!", Toast.LENGTH_SHORT).show(); }
第一個參數是得到上下文,第二個是提醒的具體內容,第三個是提醒的時間。
接下來看一下如何自訂一個Toast提醒:
//自訂toast private void customToast(){ //得到inflater對象和view LayoutInflater inflater=getLayoutInflater(); View layout=inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root)); //得到view下的相應的控制項 ImageView image = (ImageView) layout.findViewById(R.id.image); image.setImageResource(R.drawable.ic_launcher); TextView text = (TextView) layout.findViewById(R.id.text); text.setText("Hello! This is a custom toast!"); //設定toast Toast toast=new Toast(getApplicationContext()); toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); toast.setDuration(Toast.LENGTH_SHORT); toast.setView(layout); toast.show(); }
在layout 下定義了toast_layout.xml布局檔案:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/toast_layout_root" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="10dp" android:background="#DAAA" > <ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="fill_parent" android:layout_marginRight="10dp" /> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="fill_parent" android:textColor="#FFF" /></LinearLayout>
運行後效果:
我們自訂的toast要比系統預設的好多了,當然如果願意還可以自訂更複雜好看的Toast。
下面看一下Notification通知的一個例子:
private void showNotification(){ //得到一個NotificationManager對象 NotificationManager manager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); //執行個體化一個Notification int icon=R.drawable.ic_launcher; CharSequence text = "未接來電通知"; long when=System.currentTimeMillis(); Notification notification=new Notification(icon, text, when); //設定最新事件訊息和PendingIntent Context context = getApplicationContext(); CharSequence contentTitle = "你好"; CharSequence contentText = "你的未接電話!"; Intent intent=new Intent(Intent.ACTION_CALL,Uri.parse("tel:5554")); PendingIntent pendingIntent=PendingIntent.getActivity(this, 0, intent, 0); notification.setLatestEventInfo(context, contentTitle, contentText, pendingIntent); //啟動提醒 manager.notify(1, notification); }
該例子中用到了撥打到電話所以不要忘了添加許可權:
<uses-permission android:name="android.permission.CALL_PHONE"/>
運行後效果:
把上面提示欄拉下來後:
點擊相應的內容就會撥打到電話了: