首页 > 代码库 > android 之 service
android 之 service
在Activity中设置两个按钮,分别为启动和关闭Service:
bt01.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(mainActivity.this, MyService.class);
startService(i);
Toast.makeText(mainActivity.this, "Service启动成功",
Toast.LENGTH_LONG).show();
}
});
bt02.setOnClickListener(new Button.OnClickListener() {@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(mainActivity.this, MyService.class);
stopService(i);
Toast.makeText(mainActivity.this, "Service启动成功",
Toast.LENGTH_LONG).show();
}
});
添加MyService.java
public class MyService extends Service {
MyThread myThread;@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}@Override
public void onStart(Intent intent, int startId) {//启动Service
// TODO Auto-generated method stub
myThread = new MyThread();
myThread.start();
super.onStart(intent, startId);
}@Override
public void onDestroy() {//关闭Service
// TODO Auto-generated method stub
myThread.flag = false;
super.onDestroy();
}class MyThread extends Thread {
boolean flag = true;
int c = 0;public void run() {
while (flag) {
Intent i = new Intent("com.sunny.myThread");
i.putExtra("myThread", c);
sendBroadcast(i);//发送广播,在mainActivity中进行捕获,更新数据
c++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}}
mainActivity中,添加广播接收器,过滤接收来自action为com.sunny.myThread的广播:
IntentFilter intentFilter = new IntentFilter("com.sunny.myThread");
MyBroadcastReceiver myBroadcastReceiver = new MyBroadcastReceiver();
registerReceiver(myBroadcastReceiver, intentFilter);//注册广播接收器
其中:
class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle myBundle = intent.getExtras();
int myInt = myBundle.getInt("myThread");
tv01.setText("后台Service运行了" + myInt + "秒");
}}
android 之 service