通过WindowManager添加View,如何适应横竖屏

crazy_taro 2014-10-16 02:40:41
Hi,大神们

在Service里通过WindowManager添加了一个layout到屏幕最上层,想在屏幕旋转的时候这个layout用对应配置的xml,比如当前是横屏就用layout-land里的,竖屏用layout-port里的,应该如何实现?
...全文
195 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复
模仿qq炫舞游戏做出的单机版游戏 package cn.itcast.game; import java.io.InputStream; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.SoundPool; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Display; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.SurfaceHolder.Callback; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast; import android.widget.RadioGroup.OnCheckedChangeListener; public class MainActivity extends Activity { AnimView mAnimView = null; public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // 检测幕的方向:纵向或横向 if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { // 当前为横, 在此处添加额外的处理代码 } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { // 当前为竖, 在此处添加额外的处理代码 } } public void onBackPressed() { // TODO Auto-generated method stub super.onBackPressed(); android.os.Process.killProcess(android.os.Process.myPid()); } public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // 强制为横 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); Display display = getWindowManager().getDefaultDisplay(); // 显示自定义的游戏View mAnimView = new AnimView(this, display.getWidth(), display.getHeight()); setContentView(mAnimView); } public boolean onTouchEvent(MotionEvent event) { // 获得触摸的坐标 int x = (int) event.getX(); int y = (int) event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mAnimView.UpdateEvent(x, y); break; case MotionEvent.ACTION_MOVE: break; case MotionEvent.ACTION_UP: break; } return false; } public class AnimView extends SurfaceView implements Callback, Runnable { private Paint mpaint = null; private Bitmap bitmap = null; private Context mContext = null; private Canvas mCanvas = null; private boolean mIsRunning = false; private Thread mthread = null; private SurfaceHolder mSurfaceHolder = null; private Bitmap bitmap_main_1 = null; private Bitmap bitmap_main_2 = null; private Bitmap bitmap_main_3 = null; private Bitmap bitmap_main_4 = null; private int temp = 0; private int bitmap_main_1_Width = 0; private int bitmap_main_1_Height = 0; private int bitmap_main_2_Width = 0; private int bitmap_main_2_Height = 0; private int bitmap_main_3_Width = 0; private int bitmap_main_3_Height = 0; private int bitmap_main_4_Width = 0; private int bitmap_main_4_Height = 0; private MediaPlayer mMediaPlayer = null; private SoundPool mSoundPool = null; private int button_sound = 0; private Bitmap bitmap_up = null; // 幕尺寸 private int mScreenWidth = 0; // private int mScreenHeight = 0; // 炫舞吧 图片尺寸 private int bitmap_up_width = 0; private Handler handler = new Handler() { public void handleMessage(Message msg) { try { Log.e("MainActivity", "wenxi11111"); dialog_show(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; private RadioGroup m_RadioGroup = null; private RadioButton m_Radio2 = null; private RadioButton m_Radio1 = null; private RadioButton m_Radio3 = null; protected int choose_music = 1; protected int music_play = 0; public int start_music = 0; protected int now_checkid = 0; public AnimView(Context context, int width, int height) { super(context); mScreenWidth = width; // mScreenHeight = height; mContext = context; mpaint = new Paint(); /** 获取mSurfaceHolder **/ mSurfaceHolder = getHolder(); mSurfaceHolder.addCallback(this); init(); } public void dialog_show() { Log.e("MainActivity", "wenxi2222222"); AlertDialog.Builder builder = new AlertDialog.Builder(mContext); Log.e("MainActivity", "wenxi2222223"); LayoutInflater inflater = LayoutInflater.from(mContext); Log.e("MainActivity", "wenxi2222224"); final View textEntryView = inflater.inflate(R.layout.music, null); Log.e("MainActivity", "wenxi2222225"); builder.setIcon(R.drawable.xiyangyang_1); builder.setTitle("请选择背景音乐"); builder.setCancelable(false); builder.setView(textEntryView); Log.e("MainActivity", "wenxi2222226"); m_RadioGroup = (RadioGroup) textEntryView .findViewById(R.id.RadioGroup01); m_Radio1 = (RadioButton) textEntryView .findViewById(R.id.RadioButton1); m_Radio2 = (RadioButton) textEntryView .findViewById(R.id.RadioButton2); m_Radio3 = (RadioButton) textEntryView .findViewById(R.id.RadioButton3); // now_checkid = m_RadioGroup.getCheckedRadioButtonId(); m_RadioGroup.check(now_checkid); m_RadioGroup .setOnCheckedChangeListener(new OnCheckedChangeListener() { public void onCheckedChanged(RadioGroup group, int checkedId) { if (checkedId == m_Radio1.getId()) { Log.e("MainActivity", Integer .toString(checkedId)); Log.e("MainActivity", Integer.toString(m_Radio1 .getId())); choose_music = 1; Toast toast = Toast.makeText(mContext, "你选择了music1", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER_HORIZONTAL, toast.getXOffset(), toast.getYOffset()); toast.show(); } else if (checkedId == m_Radio2.getId()) { choose_music = 2; Toast toast = Toast.makeText(mContext, "你选择了music2", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER_HORIZONTAL, toast.getXOffset(), toast.getYOffset()); toast.show(); } else if (checkedId == m_Radio3.getId()) { choose_music = 3; Toast toast = Toast.makeText(mContext, "你选择了music3", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER_HORIZONTAL, toast.getXOffset(), toast.getYOffset()); toast.show(); } now_checkid = checkedId; } }); builder.setPositiveButton("保存", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel();// 取消弹出框 if (choose_music == 1) { mMediaPlayer.release(); /** 创建MediaPlayer对象 **/ mMediaPlayer = MediaPlayer.create(mContext, R.raw.bgmusic_1); /** 设置为循环播放 **/ mMediaPlayer.setLooping(true); mMediaPlayer.start(); } else if (choose_music == 2) { mMediaPlayer.release(); /** 创建MediaPlayer对象 **/ mMediaPlayer = MediaPlayer.create(mContext, R.raw.bgmusic_2); /** 设置为循环播放 **/ mMediaPlayer.setLooping(true); mMediaPlayer.start(); } else if (choose_music == 3) { mMediaPlayer.release(); mMediaPlayer = MediaPlayer.create(mContext, R.raw.bgmusic_3); /** 设置为循环播放 **/ mMediaPlayer.setLooping(true); mMediaPlayer.start(); } } }); builder.setNegativeButton("放弃", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel();// 取消弹出框 choose_music = start_music; } }); builder.create().show(); } private void init() { // 主界面静态图 bitmap = ReadBitmap(mContext, R.drawable.main_2_picture); bitmap_up = ReadBitmap(mContext, R.drawable.xuanwuba); bitmap_up_width = bitmap_up.getWidth(); bitmap_main_1 = ReadBitmap(mContext, R.drawable.main_1); bitmap_main_2 = ReadBitmap(mContext, R.drawable.main_2); bitmap_main_3 = ReadBitmap(mContext, R.drawable.main_3); bitmap_main_4 = ReadBitmap(mContext, R.drawable.main_4); bitmap_main_1_Width = bitmap_main_1.getWidth(); bitmap_main_1_Height = bitmap_main_1.getHeight(); bitmap_main_2_Width = bitmap_main_2.getWidth(); bitmap_main_2_Height = bitmap_main_2.getHeight(); bitmap_main_3_Width = bitmap_main_3.getWidth(); bitmap_main_3_Height = bitmap_main_3.getHeight(); bitmap_main_4_Width = bitmap_main_4.getWidth(); bitmap_main_4_Height = bitmap_main_4.getHeight(); // 主界面一个动态图显示 // mAnimation = new Animation(mContext,new int // []{R.drawable.a,R.drawable.b,R.drawable.c,R.drawable.d,R.drawable.e,R.drawable.f,R.drawable.g,R.drawable.h,R.drawable.i,R.drawable.j},true); // mAnimation = new Animation(mContext,new int // []{R.drawable.a_1,R.drawable.a_2,R.drawable.a_3,R.drawable.a_4,R.drawable.a_5,R.drawable.a_6,R.drawable.a_7,R.drawable.a_8,R.drawable.a_9,R.drawable.a_10,R.drawable.a_11,R.drawable.a_12,R.drawable.a_13,R.drawable.a_14,R.drawable.a_15,R.drawable.a_16,R.drawable.a_17,R.drawable.a_18,R.drawable.a_19,R.drawable.a_20},true); // mAnimation = new Animation(mContext,new int // []{R.drawable.b_1,R.drawable.b_2,R.drawable.b_3,R.drawable.b_4,R.drawable.b_5,R.drawable.b_6,R.drawable.b_7,R.drawable.b_8,R.drawable.b_9,R.drawable.b_10, // R.drawable.b_11,R.drawable.b_12,R.drawable.b_14,R.drawable.b_15,R.drawable.b_16,R.drawable.b_17,R.drawable.b_18,R.drawable.b_19,R.drawable.b_20, // R.drawable.b_21,R.drawable.b_22,R.drawable.b_23,R.drawable.b_24,R.drawable.b_25,R.drawable.b_26,R.drawable.b_27,R.drawable.b_28,R.drawable.b_29,R.drawable.b_30, // R.drawable.b_31,R.drawable.b_32,R.drawable.b_33 // },true); /** 创建MediaPlayer对象 **/ mMediaPlayer = MediaPlayer.create(mContext, R.raw.bgmusic_2); /** 设置为循环播放 **/ mMediaPlayer.setLooping(true); /** 创建一个声音播放池 **/ // 参数1为声音池同时播放的流的最大数量 // 参数2为播放流的类型 // 参数3为音乐播放效果 setmSoundPool(new SoundPool(2, AudioManager.STREAM_MUSIC, 100)); } public void UpdateEvent(int x, int y) { temp = IsClick(x, y); switch (temp) { case 1: button_sound++; Intent intent = new Intent(MainActivity.this, MenuActivity.class); startActivity(intent); break; case 2: button_sound++; if (button_sound % 2 == 1) { mMediaPlayer.setVolume(0, 0); } else { mMediaPlayer.setVolume(2, 2); } break; case 3: handler.sendMessage(new Message()); start_music = choose_music; mIsRunning = false; break; case 4: mMediaPlayer.release(); android.os.Process.killProcess(android.os.Process.myPid()); break; } } private int IsClick(int x, int y) { int a = 0; if (x >= 170 + 20 && x <= 170 + bitmap_main_1_Width - 20 && y >= 110 + 20 && y <= 110 + bitmap_main_1_Height - 20) a = 1; else if (x >= 170 + 35 && x <= 170 + bitmap_main_2_Width - 35 && y >= 160 + 20 && y <= 160 + bitmap_main_2_Height - 20) a = 2; else if (x >= 170 + 20 && x <= 170 + bitmap_main_3_Width - 40 && y >= 210 + 20 && y <= 210 + bitmap_main_3_Height - 20) a = 3; else if (x >= 170 + 40 && x <= 170 + bitmap_main_4_Width - 35 && y >= 260 + 20 && y <= 260 + bitmap_main_4_Height - 20) a = 4; return a; } private void Draw() { mCanvas.drawBitmap(bitmap, 0, 0, mpaint); mCanvas.drawBitmap(bitmap_up, (mScreenWidth - bitmap_up_width) / 2, 5, mpaint); mCanvas.drawBitmap(bitmap_main_1, 170, 110, mpaint); mCanvas.drawBitmap(bitmap_main_2, 170, 160, mpaint); mCanvas.drawBitmap(bitmap_main_3, 170, 210, mpaint); mCanvas.drawBitmap(bitmap_main_4, 170, 260, mpaint); mMediaPlayer.start(); mMediaPlayer.setVolume(2, 2); } private Bitmap ReadBitmap(Context context, int id) { BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inPreferredConfig = Bitmap.Config.RGB_565; opt.inPurgeable = true; opt.inInputShareable = true; InputStream is = context.getResources().openRawResource(id); return BitmapFactory.decodeStream(is, null, opt); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // TODO Auto-generated method stub } @Override public void surfaceCreated(SurfaceHolder holder) { // TODO Auto-generated method stub mIsRunning = true; mthread = new Thread(this); mthread.start(); } @Override public void surfaceDestroyed(SurfaceHolder holder) { // TODO Auto-generated method stub mIsRunning = false; } @Override public void run() { while (mIsRunning) { synchronized (mSurfaceHolder) { mCanvas = mSurfaceHolder.lockCanvas(); Draw(); mSurfaceHolder.unlockCanvasAndPost(mCanvas); } try { Thread.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); } } } public void setmSoundPool(SoundPool mSoundPool) { this.mSoundPool = mSoundPool; } public SoundPool getmSoundPool() { return mSoundPool; } } }
/** * 为程序创建桌面快捷方式 */ private void addShortcut(){ Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT"); //快捷方式的名称 shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name)); shortcut.putExtra("duplicate", false); //不允许重复创建 //指定当前的Activity为快捷方式启动的对象: 如 //com.everest.video.VideoPlayer //注意: ComponentName的第二个参数必须加上点号(.),否则快捷方式无法启动相应程序 ComponentName comp = new ComponentName(this.getPackageName(), "."+this.getLocalClassName()); shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(Intent.ACTION_MAIN).setComponent(comp)); //快捷方式的图标 ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(this, R.drawable.icon); shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes); sendBroadcast(shortcut); } /** * 删除程序的快捷方式 */ private void delShortcut(){ Intent shortcut = new Intent("com.android.launcher.action.UNINSTALL_SHORTCUT"); //快捷方式的名称 shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name)); //指定当前的Activity为快捷方式启动的对象: 如 //com.everest.video.VideoPlayer //注意: ComponentName的第二个参数必须是完整的类名(包名+类名),否则无法删除快捷方式 String appClass = this.getPackageName() + "." +this.getLocalClassName(); ComponentName comp = new ComponentName(this.getPackageName(), appClass); shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(Intent.ACTION_MAIN).setComponent(comp)); sendBroadcast(shortcut); } 全显示 this.requestWindowFeature(Window.FEATURE_NO_TITLE); this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); 横竖显示 private void changedScreen(){ int request = this.getRequestedOrientation(); if(request == -1){ Toast.makeText(TaskRunActivity.this, "None 1", Toast.LENGTH_SHORT).show(); }else{ if(getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE){ this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); }else if(getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT){ this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } } } 获取手机分辩率 DisplayMetrics dm = new DisplayMetrics(); this.getWindowManager().getDefaultDisplay().getMetrics(dm); int width = dm.widthPixels; int height = dm.heightPixels; 图形用户界面 文本框(TextView) 列表(ListView) 卷轴视图(ScrollView) 编辑框(EditText) 按钮(Button) 下载列表(Spinner) 多项选择(CheckBok) 图形用户界面 菜单(Menu) 提示(toast) 对话框(Dialog) 日期(DatePicker) 时间(TimePicker) 单项选择(RadioGroup RadioButton) 图形用户界面 线性布局(LinearLayout) 相对布局(RelativeLayout) 绝对布局(AbsoluteLayout) 表格布局(TableLayout) 数据据存储 系统偏好 文件 网络 数据库 显示网页: 1. Uri uri = Uri.parse("http://www.google.com"); 2. Intent it = new Intent(Intent.ACTION_VIEW,uri); 3. startActivity(it); 显示地图: 1. Uri uri = Uri.parse("geo:38.899533,-77.036476"); 2. Intent it = new Intent(Intent.Action_VIEW,uri); 3. startActivity(it); 路径规划: 1. Uri uri = Uri.parse("http://maps.google.com/maps?f=d&saddr=startLat%20startLng&daddr=endLat%20endLng&hl=en"); 2. Intent it = new Intent(Intent.ACTION_VIEW,URI); 3. startActivity(it); 拨打电话: 调用拨号程序 1. Uri uri = Uri.parse("tel:xxxxxx"); 2. Intent it = new Intent(Intent.ACTION_DIAL, uri); 3. startActivity(it); 1. Uri uri = Uri.parse("tel.xxxxxx"); 2. Intent it =new Intent(Intent.ACTION_CALL,uri); 3. 要使用这个必须在配置文件中加入 发送SMS/MMS 调用发送短信的程序 1. Intent it = new Intent(Intent.ACTION_VIEW); 2. it.putExtra("sms_body", "The SMS text"); 3. it.setType("vnd.android-dir/mms-sms"); 4. startActivity(it); 发送短信 1. Uri uri = Uri.parse("smsto:0800000123"); 2. Intent it = new Intent(Intent.ACTION_SENDTO, uri); 3. it.putExtra("sms_body", "The SMS text"); 4. startActivity(it); 发送彩信 1. Uri uri = Uri.parse("content://media/external/images/media/23"); 2. Intent it = new Intent(Intent.ACTION_SEND); 3. it.putExtra("sms_body", "some text"); 4. it.putExtra(Intent.EXTRA_STREAM, uri); 5. it.setType("image/png"); 6. startActivity(it); 发送Email 1. 2. Uri uri = Uri.parse("mailto:xxx@abc.com"); 3. Intent it = new Intent(Intent.ACTION_SENDTO, uri); 4. startActivity(it); 1. Intent it = new Intent(Intent.ACTION_SEND); 2. it.putExtra(Intent.EXTRA_EMAIL, "me@abc.com"); 3. it.putExtra(Intent.EXTRA_TEXT, "The email body text"); 4. it.setType("text/plain"); 5. startActivity(Intent.createChooser(it, "Choose Email Client")); 1. Intent it=new Intent(Intent.ACTION_SEND); 2. String[] tos={"me@abc.com"}; 3. String[] ccs={"you@abc.com"}; 4. it.putExtra(Intent.EXTRA_EMAIL, tos); 5. it.putExtra(Intent.EXTRA_CC, ccs); 6. it.putExtra(Intent.EXTRA_TEXT, "The email body text"); 7. it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text"); 8. it.setType("message/rfc822"); 9. startActivity(Intent.createChooser(it, "Choose Email Client")); 添加附件 1. Intent it = new Intent(Intent.ACTION_SEND); 2. it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text"); 3. it.putExtra(Intent.EXTRA_STREAM, "[url=]file:///sdcard/mysong.mp3[/url]"); 4. sendIntent.setType("audio/mp3"); 5. startActivity(Intent.createChooser(it, "Choose Email Client")); 播放多媒体 1. 2. Intent it = new Intent(Intent.ACTION_VIEW); 3. Uri uri = Uri.parse("[url=]file:///sdcard/song.mp3[/url]"); 4. it.setDataAndType(uri, "audio/mp3"); 5. startActivity(it); 1. Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "1"); 2. Intent it = new Intent(Intent.ACTION_VIEW, uri); 3. startActivity(it); Uninstall 程序 1. Uri uri = Uri.fromParts("package", strPackageName, null); 2. Intent it = new Intent(Intent.ACTION_DELETE, uri); 3. startActivity(it); //调用相册 public static final String MIME_TYPE_IMAGE_JPEG = "image/*"; public static final int ACTIVITY_GET_IMAGE = 0; Intent getImage = new Intent(Intent.ACTION_GET_CONTENT); getImage.addCategory(Intent.CATEGORY_OPENABLE); getImage.setType(MIME_TYPE_IMAGE_JPEG); startActivityForResult(getImage, ACTIVITY_GET_IMAGE); //调用系统相机应用程序,并存储拍下来的照片 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); time = Calendar.getInstance().getTimeInMillis(); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment .getExternalStorageDirectory().getAbsolutePath()+"/tucue", time + ".jpg"))); startActivityForResult(intent, ACTIVITY_GET_CAMERA_IMAGE); uninstall apk Uri uninstallUri = Uri.fromParts("package", "xxx", null); returnIt = new Intent(Intent.ACTION_DELETE, uninstallUri); install apk Uri installUri = Uri.fromParts("package", "xxx", null); returnIt = new Intent(Intent.ACTION_PACKAGE_ADDED, installUri); play audio Uri playUri = Uri.parse("[url=]file:///sdcard/download/everything.mp3[/url]"); returnIt = new Intent(Intent.ACTION_VIEW, playUri); //发送附件 Intent it = new Intent(Intent.ACTION_SEND); it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text"); it.putExtra(Intent.EXTRA_STREAM, "[url=]file:///sdcard/eoe.mp3[/url]"); sendIntent.setType("audio/mp3"); startActivity(Intent.createChooser(it, "Choose Email Client")); //搜索应用 Uri uri = Uri.parse("market://search?q=pname:pkg_name"); Intent it = new Intent(Intent.ACTION_VIEW, uri); startActivity(it); //where pkg_name is the full package path for an application //进入联系人页面 Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.setData(People.CONTENT_URI); startActivity(intent); //查看指定联系人 Uri personUri = ContentUris.withAppendedId(People.CONTENT_URI, info.id);//info.id联系人ID Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.setData(personUri); startActivity(intent); 在进行Android开发的过程中,免不了,要开发TCP/UDP通讯的程序,下面这两段代码,分别介绍了TCP/UCP通过的一个实例: 代码一: private void tcpdata() { try { Socket s = new Socket("192.168.0.25", 65500); // outgoing stream redirect to socket OutputStream out = s.getOutputStream(); // 注意第二个参数据为true将会自动flush,否则需要需要手动操作out.flush() PrintWriter output = new PrintWriter(out, true); output.println("Hello IdeasAndroid! 伪IP为:" + SIMCardToIP("13512345006")); InputStream inputStream = s.getInputStream(); DataInputStream input = new DataInputStream(inputStream); byte[] b = new byte[10000]; int length = input.read(b); inputReader = new InputStreamReader(inputStream); String Msg = new String(b, 0, length, "gb2312"); Toast.makeText(TcpTest.this, Msg, 1000).show(); Log.d("Tcp Demo", "message From Server:" + Msg); s.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } 下面的代码是UDP通讯的过程: public String send(String msg) { StringBuilder sb = new StringBuilder(); InetAddress local = null; try { local = InetAddress.getByName("192.168.0.25"); // 本机测试 } catch (UnknownHostException e) { e.printStackTrace(); } try { dSocket = new DatagramSocket(); // 注意此处要先在配置文件里设置权限,否则会抛权限不足的异常 } catch (SocketException e) { e.printStackTrace(); } int msg_len = msg == null ? 0 : msg.length(); DatagramPacket dPacket = new DatagramPacket(msg.getBytes(), msg_len, local, SERVER_PORT); try { dSocket.send(dPacket); } catch (IOException e) { e.printStackTrace(); } try { dSocket.receive(dPacket); sb.append(new String(dPacket.getData())); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } dSocket.close(); return sb.toString(); }

80,350

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧