得意犹堪夸世俗,诏黄新湿字如鸦。这篇文章主要讲述android 之 service相关的知识,希望能为你提供帮助。
在Activity中设置两个按钮,分别为启动和关闭Service:
bt01.setOnClickListener(new Button.OnClickListener() {添加MyService.java
@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();
}
});
public class MyService extends Service {mainActivity中,添加广播接收器,过滤接收来自action为com.sunny.myThread的广播:
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();
}
}
}
}
}
【android 之 service】 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 之 GridView
- android 之 View
- android 之 TabHost
- android屏幕适配的全攻略
- android 之 ListView相关
- Dijkstra的算法分析
- 离散数学二叉树
- [OpenCV实战]17 基于卷积神经网络的OpenCV图像着se
- yaml文件及语法基础