当一个广播接收器接收到广播消息,并不能通过可视化的界面来显示广播信息。这里我们可以通过状态提示栏(State Bar)来显示广播信息的内容,图标以及震动等信息。这就需要使用Notification控件和Notification Manager。
下面以一个实例,来说明状态提示栏的应用。在这个实例中,由广播接收器接收一个收到短信的广播消息,然后开启一个Service,由这个服务将通知信息显示在状态提示栏中。
广播接收器:
|
- public class MyReciever extends BroadcastReceiver {
-
- Intent i;
-
-
@Override
-
public void onReceive(Context context, Intent intent) {
-
-
//当广播接收器接收到广播消息时,将开启一个Service
-
i=new Intent();
-
i.setAction("SERVICE_ACTION");
-
context.startService(i);
-
- }
-
-
- }
|
服务:
|
- public class Myservice extends Service {
-
private NotificationManager mNM;
-
private Notification nF;
-
private Intent i;
-
private PendingIntent pi;
-
@Override
-
public void onCreate() {
-
- }
-
-
@Override
-
public int onStartCommand(Intent intent, int flags, int startId) {
- //初始化消息管理器对象
- mNM=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
- //设置当点击通知消息时的转移操作,当用户点击消息时,将转移到After
-
i=new Intent();
-
i.setClass(Myservice.this, After.class);
-
pi =PendingIntent.getActivity(Myservice.this, 0, i, 0);
- // 对通知进行初始化并进行参数进行设置。
-
nF=new Notification();
- //设置图标
- nF.icon=R.drawable.icon;
- //设置通知内容
-
nF.tickerText="收到通知";
- //设置通知栏上显示的信息标题,内容以及点击通知时的转向
-
nF.setLatestEventInfo(this, "通知", "成功", pi);
- //执行通知
-
mNM.notify(0, nF);
-
-
return 0;
- }
-
-
@Override
-
public void onDestroy() {
-
-
-
-
-
Toast.makeText(this, "destroy", Toast.LENGTH_SHORT).show();
- }
-
-
@Override
-
public IBinder onBind(Intent intent) {
-
-
return null;
- }
- }
|
AndroidManifest.xml
|
- <?xml version="1.0" encoding="utf-8"?>
-
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
-
package="com.bt"
-
android:versionCode="1"
-
android:versionName="1.0">
-
<application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true">
-
<activity android:name=".BroadcastTest"
-
android:label="@string/app_name">
-
<intent-filter>
-
<action android:name="android.intent.action.MAIN" />
-
<category android:name="android.intent.category.LAUNCHER" />
-
-
</intent-filter>
-
</activity>
- //接收器的部署
-
<receiver android:name=".MyReciever">
-
<intent-filter>
-
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
-
-
</intent-filter>
-
</receiver>
- //对服务的部署
-
<service android:name=".Myservice">
-
<intent-filter>
-
<action android:name="SERVICE_ACTION"/>
-
</intent-filter>
-
</service>
-
<activity android:name=".After"
-
android:label="an">
-
-
</activity>
-
</application>
-
<uses-sdk android:minSdkVersion="8" />
- //设置该应用可以有接收短信的权限
-
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
-
-
-
-
</manifest>
|
对于Notification和Notification Manager的使用,有以下几点是需要注意的:
A. 只有Activity和Serviece可以开启通知,其他的组件包括广播接收器并不能直接开启。如果需要对系统广播进行消息提示的话,则需要在广播接收器中转移到Activity或者Service中,由他们开启通知。
B. 除了上述实例中设置的通知参数之外,还有其他一些参数,例如震动,声音等,具体可以参考SDK文档中的说明。
本文出自 “我的Android开发志” 博客,请务必保留此出处http://52android.blog.51cto.com/2554429/500661