设为首页 加入收藏

TOP

Android实现电蚊香/Service服务管理类
2014-11-24 08:24:45 来源: 作者: 【 】 浏览:1
Tags:Android 实现 蚊香 /Service 服务 管理

实现这个实例需要的就是Service这个类的管理,我们用到的是启动Service,并在退出应用程序的时候关闭(Stop)Service,下面我们首先看下这个程序的运行截图:



图中显示的控件一个是ImageView,另一个是ImageButton,我们点击ImageButton之后可以控制程序的运行和关闭,这里我们看到的是关闭的状态。


当我们点击ImageButton之后,程序开始运行,并且在通知栏有相应的显示。


下面给出实现的截图:



下面给出实现的代码:


1.Service类


package irdc.ex10_08;


/* 自定义MyService继承Service */
public class MyService extends Service
{
private String MY_PREFS = "MosPre";
private NotificationManager notiManager;
private int mosStatus;
private int notiId=99;
private MediaPlayer myPlayer;

@Override
public void onCreate()
{
try
{
/* 取得NotificationManager */
notiManager=
(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
/* Create MediaPlayer */
myPlayer=new MediaPlayer();
myPlayer = MediaPlayer.create(MyService.this, R.raw.killmosall);

/* 读取防蚊服务状态(1:启动,0:关闭) */
SharedPreferences pres =
getSharedPreferences(MY_PREFS,Context.MODE_PRIVATE);
if(pres !=null)
{
mosStatus = pres.getInt("status", 0);
}

if(mosStatus==1)
{
/* 加一个Notification */
setNoti(R.drawable.antimos,notiId,"防蚊服务启动");
/* 播放防蚊铃声 */
if(!myPlayer.isPlaying())
{
myPlayer.seekTo(0);
myPlayer.setLooping(true);
myPlayer.start();
}
}
else if(mosStatus==0)
{
/* 删除Notification */
deleteNoti(notiId);
/* 关闭防蚊铃声 */
if(myPlayer.isPlaying())
{
myPlayer.setLooping(false);
myPlayer.pause();
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
super.onCreate();
}

@Override
public void onDestroy()
{
try
{
/* Service关闭时释放MediaPlayer,
* 并删除Notification */
myPlayer.release();
deleteNoti(notiId);
}
catch(Exception e)
{
e.printStackTrace();
}
super.onDestroy();
}



/* 新增Notification的method */
public void setNoti(int iconImg,int iconId,String icontext)
{
/* 建立点选Notification留言条时,会执行的Activity */
Intent notifyIntent=new Intent(this,EX10_08.class);
notifyIntent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK);
/* 建立PendingIntent当为设定递延执行的Activity */
PendingIntent appIntent=PendingIntent.getActivity(this,0,notifyIntent,0);
/* 建立Notification,并设定相关参数 */
Notification myNoti=new Notification();
/* 设定status bar显示的icon */
myNoti.icon=iconImg;
/* 设定notification发生时她时发叨预设声音 */
myNoti.defaults=Notification.DEFAULT_SOUND;
myNoti.setLatestEventInfo(this,"防蚊服务启动",icontext,appIntent);
/* 送出Notification */
notiManager.notify(iconId,myNoti);
}

/* 删除Notification的method */
public void deleteNoti(int iconId)
{
notiManager.cancel(iconId);
}

@Override
public IBinder onBind(Intent arg0)
{
return null;
}
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇为什么log4j的概念模型是错的--zl.. 下一篇Python数据库编程入门教程

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·如何理解c语言指针和 (2025-12-27 01:19:11)
·为什么C标准库没有链 (2025-12-27 01:19:08)
·玩转C语言和数据结构 (2025-12-27 01:19:05)
·MySQL 基础入门视频 (2025-12-26 23:20:22)
·小白入门:MySQL超详 (2025-12-26 23:20:19)