notification栏增加常驻通知以及开机启动的处理
发表于 2011/08/07 由 sunweidong022
在开发的过程中,碰到了要求为应用程序增加notification栏当中的常驻通知,当用户点击这个常驻通知时,就可以跳转到该应用程序的主界面,实现的方法如下:
NotificationManager nm ;
Notification n = new Notification(R.drawable.icon, getString(R.string.info), System.currentTimeMillis());
n.flags = Notification.FLAG_ONGOING_EVENT;
Intent i = new Intent(taskAcitivy.this, taskAcitivy.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(
taskAcitivy.this,
R.string.app_name,i,
0);
n.setLatestEventInfo(
taskAcitivy.this,getString(R.string.info),”",contentIntent);
nm.notify(R.string.app_name, n);
shared.edit().putBoolean(“flag”, true).commit();
通过以上方法可以想notification栏中增加一个常驻通知,当我们想要消除这个通知时,可以使用 nm.cancel(R.string.app_name);
如果我们想要实现该通知开机启动的话,可以使用接受开机广播来实现,具体处理方法如下:
首先 编写一个接受广播的类
public class Receiver extends BroadcastReceiver{
public void onReceive(Context arg0, Intent arg1)
{
Intent intent = new Intent();
intent.setAction(“com.leefj.application.taskmanager.TaskService”);
arg0.startService(intent);
}}
并在android配置文件中增加
然后我们跳转到TaskService当中
public class TaskService extends Service{
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public void onStart(Intent intent, int startId)
{
startX();
}
public void startX()
{
SharedPreferences shared=getSharedPreferences(“info”, MODE_PRIVATE);
if(shared.getBoolean(“flag”, true))
{
NotificationManager nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification n = new Notification(R.drawable.icon,getString(R.string.info), System.currentTimeMillis());
n.flags = Notification.FLAG_ONGOING_EVENT;
Intent i = new Intent(this, taskAcitivy.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(
this,
R.string.app_name,i,
0);
n.setLatestEventInfo(
this,getString(R.string.info),”",contentIntent);
nm.notify(R.string.app_name, n);
}
onDestroy();
}
}
执行并且销毁这个service,这样功能就可以实现了。