Notification,顾名思义就是通知、提醒的意思。那么我们今天就来做这样一个通知。
在Android中实现通知,需要借助NotificationManager和Notification类。对于UI布局,我们采用一个最为简单的形式,即两个按钮,一个用来打开通知,一个用来关闭通知。布局代码如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/BtnStart"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/StartNotification" />
<Button
android:id="@+id/BtnStop"
android:layout_width="284dp"
android:layout_height="wrap_content"
android:text="@string/StopNotification" />
</LinearLayout>
同样地,后台控制代码如下:
package com.Android.Notification;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
Button BtnStart,BtnStop;
Notification n;
NotificationManager nm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String Service=NOTIFICATION_SERVICE;
nm=(NotificationManager)getSystemService(Service);
n=new Notification();
n.icon=R.drawable.ic_launcher;
n.tickerText="Android4.2版本更新啦";
n.when=System.currentTimeMillis();
n.flags|=Notification.DEFAULT_LIGHTS;
n.flags|=Notification.DEFAULT_SOUND;
n.flags|=Notification.FLAG_SHOW_LIGHTS;
n.ledOnMS=500;
n.ledOffMS=1000;
n.sound=Uri.parse("file:///"+Environment.getExternalStorageDirectory().getPath()+"/Audio/秋千坠.mp3");
BtnStart=(Button)findViewById(R.id.BtnStart);
BtnStart.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0)
{
Intent intent = new Intent(MainActivity.this,MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
n.setLatestEventInfo(MainActivity.this, "Android4.2版本更新啦!", "立即升级", pi);
nm.notify(1, n);
}
});
BtnStop=(Button)findViewById(R.id.BtnStop);
BtnStop.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0)
{
nm.cancel(1);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
程序运行效果如下图所示:
我想到这里你已经明白了什么是通知,联系到国内Android市场的现状,你一定明白了手机里那些广告是怎么回事了吧,呵呵,如果我们把一个安卓程序反编译,然后在其中加入这种推荐性的通知,反倒不失为一种营销的手段啊,当然,这么做是不对啊啦,哈哈。