屏幕控制--UDP

来源:互联网 发布:c语言常用函数速查手册 编辑:程序博客网 时间:2024/06/05 02:07
public class ScreenControlActivity extends Activity {
/** Called when the activity is first created. */
TextView mIp;
Button searchBtn,clearBtn;
ListView lv;
ProgressBar progress;
LayoutInflater inflater;

List<STB> stbs;
BaseAdapter ba;
Handler handler;
DatagramSocket s = null;
String mip;

private static final String testTitle = "xxxx";//
private static final int testDuration = 304;
private static final String testUrl = "http://xxxxx.mp4";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mip = getLocalIpAddress();
stbs = new ArrayList<STB>();
try {
s = new DatagramSocket(6801);
} catch (SocketException e) {
e.printStackTrace();
}
findByIds();
Thread mReceiveThread= new Thread(mReceiveRunnable);  
        mReceiveThread.start();
}


private void findByIds() {
inflater = LayoutInflater.from(this);
mIp = (TextView) findViewById(R.id.mIp);
searchBtn = (Button) findViewById(R.id.search);
clearBtn = (Button) findViewById(R.id.clear);
lv = (ListView) findViewById(R.id.listView1);
progress = (ProgressBar) findViewById(R.id.progressBar1);
mIp.setText("本机ip:" + mip);
searchBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
String destIp = mip.substring(0, mip.lastIndexOf(".")+1);
System.out.println("destIp---->"+destIp);
for(int i = 2;i<255;i++){
search(destIp+i);
}
}
}).start();
}
});
clearBtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
stbs.removeAll(stbs);
ba.notifyDataSetChanged();
}
});
ba = new MyAdapter();
handler = new Handler(){


@Override
public void handleMessage(Message msg) {
ba.notifyDataSetChanged();
lv.setAdapter(ba);
super.handleMessage(msg);
}
};
}






public void search(String destip) {
try {
byte [] data = ReqXmlUtil.SearchReq( "123456",getLocalIpAddress());
InetAddress stbIp = InetAddress.getByName(destip);
DatagramPacket p = new DatagramPacket(data, data.length, stbIp,ReqXmlUtil.stbPort);
s.send(p);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf
.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
ex.printStackTrace();
}
return null;
}


    Runnable mReceiveRunnable = new Runnable() {  
        public void run() {  
        startReceive();
        }  
    };  
    
protected void startReceive() {
try {  
            byte[] buffer = new byte[1024];  
            DatagramPacket packet = new DatagramPacket(buffer,buffer.length);  
            while (true) {  
                s.receive(packet);  
                if (packet.getLength() > 0) {  
                    String str = new String(buffer, 0, packet  
                            .getLength());
                    System.out.println("receive-->"+str);
                    MscpDataParser.getInstance().init(this);
               //得到udp数据: datagramPacket
               MscpDataParser.getInstance().parse(packet,new MscpDataParser.CallBack() {
                      @Override
                      public void onParseCompleted(HashMap<String, String> map) {
                          // TODO Auto-generated method stub
                          if( map != null ){
                              // handle your map
                         String req = map.get("cmd");
                         System.out.println("req--->"+req);
                         if(req!=null){
                         if(req.equals("stbresp")){//搜索回应
                         STB stb = new STB(map.get("IP"), map.get("taskno"),
                         map.get("username"), map.get("password"), map.get("mcid"));
                         System.out.println("Stb-->"+stb.toString());
                         checkStbIsExist(stb);
                         }else if(req.equals("playresp")){//播放状态回应--待处理--应该提供STB的Mcid/ip?
                         PlayStatus playStatus = new PlayStatus();
                         System.out.println("==========playresp===========");
                         System.out.println("taskno-->"+map.get("taskno"));
//                         <!— 播放状态:1-成功,0-失败,2-暂停 3-播放完成 -->
                         System.out.println("status-->"+map.get("status"));
                         playStatus.setStatus(Integer.parseInt(map.get("status")));
//                         <!— 播放位置:pos是秒 -->
                         System.out.println("pos-->"+map.get("pos"));
                         playStatus.setPos(Integer.parseInt(map.get("pos")));
//                         <!— 片长:秒 -->
                         System.out.println("duration-->"+map.get("duration"));
                         playStatus.setPos(Integer.parseInt(map.get("duration")));
//                         <!— 音量 -->
                         System.out.println("volume-->"+map.get("volume"));
                         playStatus.setPos(Integer.parseInt(map.get("volume")));
//                         <!— 最大音量 -->
                         System.out.println("maxvol-->"+map.get("maxvol"));
                         playStatus.setPos(Integer.parseInt(map.get("maxvol")));
                         System.out.println("=============================");
                         
                         }
                         }
                          }
                      }


private void checkStbIsExist(STB stb) {
boolean isStbExist = false;
 for(int i=0;i<stbs.size();i++){
 String tempIp = stbs.get(i).getIp();
 if(stb.getIp().equals(tempIp)){
 isStbExist = true;
 }
 }
 if(!isStbExist)
 stbs.add(stb);
 System.out.println("checkStbIsExist--->"+isStbExist);
}
                   
                     @Override
                      public void onError(int code, String desc) {
                         // TODO Auto-generated method stub
                      }
                  });
                    
                    handler.sendEmptyMessageDelayed(1, 100);
                }  
            }
        } catch (SocketException e) {  
            e.printStackTrace();
        } catch (IOException e) {  
            e.printStackTrace();
        }
}
    
class MyAdapter extends BaseAdapter{


@Override
public int getCount() {
return stbs.size();
}


@Override
public Object getItem(int arg0) {
return null;
}


@Override
public long getItemId(int position) {
return 0;
}


@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = inflater.inflate(R.layout.stbitem, null);
TextView stbName = (TextView) v.findViewById(R.id.stbItem_stbName);
TextView stbIP = (TextView) v.findViewById(R.id.stbItem_stbIp);
Button playBtn = (Button) v.findViewById(R.id.play);
Button pauseBtn = (Button) v.findViewById(R.id.pause);
Button stopBtn = (Button) v.findViewById(R.id.stop);
SeekBar voice = (SeekBar) v.findViewById(R.id.voice);
voice.setMax(100);
SeekBar duration = (SeekBar) v.findViewById(R.id.duration);
final STB stb = stbs.get(position);
stbName.setText(stb.getUsername());
stbIP.setText(stb.getIp());


playBtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
play(stb.getIp(),ReqXmlUtil.stbPort , testTitle,testDuration,testUrl);
System.out.println("--play---");
}
});
pauseBtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
pause(stb.getIp(),ReqXmlUtil.stbPort);
System.out.println("--pause---");
}
});
stopBtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
stop(stb.getIp(), ReqXmlUtil.stbPort, 123456, mip);
System.out.println("--stop---");
}
});

voice.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// voiceChanged(stb.getIp(), ReqXmlUtil.stbPort, 123456, mip,seekBar.getProgress(),100);
// System.out.println("--StopTrackingTouch---"+seekBar.getProgress());
}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {

}

@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
volumeChanged(stb.getIp(), ReqXmlUtil.stbPort, 123456, mip,progress,100);
System.out.println("--onProgressChanged---"+progress);
}
});
duration.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// duriationChanged(stb.getIp(), ReqXmlUtil.stbPort, 123456, mip,seekBar.getProgress());
// System.out.println("--OnSeekBarChangeListener---"+seekBar.getProgress());
}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {

}

@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
duriationChanged(stb.getIp(), ReqXmlUtil.stbPort, 123456, mip,progress);
System.out.println("--onProgressChanged---"+progress);
}
});
return v;

}


protected void volumeChanged(String destIp, int stbport, int taskno, String mip, int volume, int maxvol) {
byte[] data = ReqXmlUtil.VolumeReq(taskno, mip, volume, maxvol);
try {
s.send(new DatagramPacket(data, data.length, InetAddress.getByName(destIp), stbport));
} catch (IOException e) {
e.printStackTrace();
}
}

protected void duriationChanged(String destIp, int stbport, int taskno, String mip,int pos) {
byte[] data = ReqXmlUtil.SeekReq(taskno, mip, pos);
try {
s.send(new DatagramPacket(data, data.length, InetAddress.getByName(destIp), stbport));
} catch (IOException e) {
e.printStackTrace();
}
}


protected void stop(String destIp,int destPort,int taskno, String mip) {
byte[] data = ReqXmlUtil.StopReq(123456, mip);
try {
s.send(new DatagramPacket(data, data.length, InetAddress.getByName(destIp), destPort));
} catch (IOException e) {
e.printStackTrace();
}
}


protected void pause(String destIp,int destPort) {
byte[] data = ReqXmlUtil.PauseReq(123456, destIp);
try {
s.send(new DatagramPacket(data, data.length,InetAddress.getByName(destIp),destPort));
} catch (IOException e) {
e.printStackTrace();
}
}
protected void play(String destIp,int destPort,String title, int duration, String url) {
byte[] data = ReqXmlUtil.PlayReq(123456, mip, title, duration, url);
try {
s.send(new DatagramPacket(data, data.length,InetAddress.getByName(destIp),destPort));
} catch (IOException e) {
e.printStackTrace();
}
}

}
}
原创粉丝点击