Abndroid手机上有一个状态栏。当系统有一些信息(收到新信息,未接来电等)要通知用户时,系统通常会把信息显示在状态栏,有的仅显示小图标,有的显示图标和文字。
在程序中,Android API为了管理提示信息(Notification)已经定义了NotificationManager,只要把Notification添加NotificationManager,即可将信息显示在状态栏。运行截图:
package com.lyc;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
public class NotificationManagerActivity extends Activity {
private NotificationManager myNotiManager;
private Spinner mySpinner;
private ArrayAdapter<String> myAdapter;
private static final String[] status = {"在线","离开","忙碌着","离线"};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myNotiManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mySpinner = (Spinner) findViewById(R.id.spinner1);
myAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,status);
// myAdapter.setDropDownViewResource(R.layout.myspinner_dropdown);
mySpinner.setAdapter(myAdapter);
mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
if(status[arg2].equals("在线")){
setNotiType(R.drawable.online,"在线 ");
}else if(status[arg2].equals("离开")){
setNotiType(R.drawable.offline,"离开");
}else if(status[arg2].equals("忙碌着")){
setNotiType(R.drawable.busy,"忙碌着");
}else{
setNotiType(R.drawable.away,"离线");
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
private void setNotiType(int iconId, String string) {
// TODO Auto-generated method stub
Intent notifyIntent = new Intent(this,another.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent appIntent = PendingIntent.getActivity(NotificationManagerActivity.this, 0, notifyIntent,0);
Notification myNoti = new Notification();
myNoti.icon=iconId;
myNoti.tickerText=string;
myNoti.defaults=Notification.DEFAULT_SOUND;
myNoti.setLatestEventInfo(NotificationManagerActivity.this, "QQ登录状态", string, appIntent);
myNotiManager.notify(0,myNoti);
}
}
package com.lyc;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
public class another extends Activity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast.makeText(another.this, "模拟切换状态", Toast.LENGTH_SHORT).show();
finish();
}
}