概述
有一个需求,因为后台没做接口,为了测试,实现基本展示功能,将让设备运动的指令动作,因此,打算将指令做成一个数组,绑定服务,由服务在后台定时发送指令。
服务类:用timer和timertask做定时处理;另外一个方法设置需要发送的指令集,由MainActivity绑定传递。
public class MusicDanceService extends Service {
private MyBinder binder = null;
private final static String TAG = "TestService";
public MusicDanceService() {
}
@Override
public void onCreate() {
super.onCreate();
binder = new MyBinder();
}
@Override
public void onDestroy() {
super.onDestroy();
binder = null;
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return binder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
public class MyBinder extends Binder {
private int[] actions;
public TimerTask mTimerTask = null;
public Timer mTimer = null;
private int position;
/**
* 根据动作数组发送指定指令
*/
public void startMusicDanceActions(final int[] actions ){
if (!(actions.length > 0)) return;
this.actions = actions;
if (mTimerTask != null){
mTimerTask.cancel();
mTimerTask = null;
}
if (mTimer != null){
mTimer.cancel();
mTimer = null;
}
position = 0;
mTimerTask = new TimerTask() {
@Override
public void run() {
handleSendCmd(actions[position]);
}
};
mTimer = new Timer();
mTimer.schedule(mTimerTask,0,1500);
}
private void handleSendCmd(int type){
switch (type){
case 1:
Log.d(TAG, "startMusicDanceActions: 前进");
break;
case 2:
Log.d(TAG, "startMusicDanceActions: 后退");
break;
case 3:
Log.d(TAG, "startMusicDanceActions: 左转");
break;
case 4:
Log.d(TAG, "startMusicDanceActions: 右转");
break;
default:
break;
}
position ++;
if (position >= actions.length) {
position = 0;
}
Log.d(TAG, "handleSendCmd: " + position);
}
}
}
MainActivity类:
private MusicDanceService.MyBinder mMyBinder = null; int[] actions = new int[]{1,4,3,2,3,2,1,2,3,4,3,2};
初始化一个指令集,由于动作只由四种,将1~4分别代表不同的指令,
在connection中得到服务的binder
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
Log.d("Test", "onServiceConnected: ");
mMyBinder = (MusicDanceService.MyBinder) iBinder;
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
Log.d("Test", "onServiceDisconnected: ");
}
};
主要是绑定服务,然后需要调用的时候调用方法,最后,在destroy的时候需要解绑服务。
//连接服务
Intent intent = new Intent(this,MusicDanceService.class);
bindService(intent,mConnection,BIND_AUTO_CREATE);
findViewById(R.id.send_btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mMyBinder != null){
mMyBinder.startMusicDanceActions(actions);
}
}
});
最后
以上就是欣慰学姐为你收集整理的Android 绑定服务,定时往服务器发送指令的全部内容,希望文章能够帮你解决Android 绑定服务,定时往服务器发送指令所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复