安卓手机实现同wifi局域网下互相传输数据,图片,视频,文档。实现查看手机存储卡所有内容,点击该文件即可触发是否进行传输,送该刚学习安卓的朋友参考!
public class MainActivity extends AppCompatActivity {
private List<Fruit> fruitList = new ArrayList<>();//加载完成的滚动控件数据
RecyclerView recyclerView;//滚动控件
private String path = "/sdcard/脚本/";
EditText editText ;
EditText editText1 ;
Button button_a ;//刷新
Button button_b;//上层
Button button_c;//接收
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
editText = (EditText) findViewById(R.id.edit_a);
editText1 = (EditText) findViewById(R.id.edit_b);
button_a = (Button) findViewById(R.id.but_a);
button_b = (Button) findViewById(R.id.but_b);
button_c = (Button) findViewById(R.id.but_c);
//初始化滚动控件
recyclerView = (RecyclerView) findViewById(R.id.recylerview_a);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
if(!(new File(path).exists())){
path = "/sdcard";
}
load_fruitlist(path);
set_recyclerview();
//
button_a.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
load_fruitlist(editText.getText()+"");
set_recyclerview();
}
});
button_b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
File f = new File(editText.getText()+"");
if(f.getAbsolutePath().equals("/sdcard")){
Toast.makeText(MainActivity.this,"已到达最顶层",Toast.LENGTH_SHORT).show();
}else{
load_fruitlist(f.getParent());
set_recyclerview();
}
}
});
button_c.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("本设备ip:");
progressDialog.setCancelable(true);
progressDialog.show();
det_date(progressDialog);
}
});
}
//发送数据
public void send_date(final String name){
final String ip1 = editText1.getText()+"";
AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
dialog.setTitle("确认发送:"+name+"到"+ip1);
dialog.setPositiveButton("确认", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
File f = new File(path+"/"+name);
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setTitle("正在发送:"+f.getName());
progressDialog.setCancelable(true);
progressDialog.show();
new Thread(new send_date(f,ip1,progressDialog)).start();
}
});
dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
dialog.show();
}
//发送数据的线程
class send_date extends Thread{
File f;
String ip;
String str="";
ProgressDialog progressDialog;
private Handler handler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
progressDialog.setMessage(str);
}
};
Message message = new Message();
public send_date(File f, String ip,ProgressDialog progressDialog){
this.f=f;
this.ip=ip;
this.progressDialog=progressDialog;
}
public void run() {
setmes("正在准备数据");
String chh = f.getName()+","+f.length();
setmes(chh);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
setmes("正在连接");
try {
Socket socket = new Socket(ip, 3838);
OutputStream outputStream = socket.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,"utf-8");
outputStreamWriter.write(chh.toCharArray());
outputStreamWriter.close();
outputStream.close();
socket.close();
setmes("文件信息已发送,再次连接发送数据");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
socket = new Socket(ip, 3838);
outputStream = socket.getOutputStream();
byte[] b = new byte[1024];
int a = 0;
int b1 = 0;
InputStream inputStream = new FileInputStream(f);
while(a!=-1){
a = inputStream.read(b);
if(a!=-1){
outputStream.write(b,0,a);
b1+=a;
setmes("正在发送:"+b1 + "/"+ f.length());
}
}
inputStream.close();
outputStream.close();
socket.close();
setmes("数据成功发送到目标设备,返回即可");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
progressDialog.dismiss();
} catch (IOException e) {
e.printStackTrace();
}
}
public void setmes(String str1){
message = new Message();
message.what = 1;
str = str1;
handler.sendMessage(message);
}
}
//接收数据
public void det_date(ProgressDialog progressDialog){
String ip = getIpAddress(MainActivity.this);
if(ip=="null"){
Toast.makeText(MainActivity.this,"未连接wifi",Toast.LENGTH_SHORT).show();
}else{
progressDialog.setMessage("等待连接");
progressDialog.setTitle("本设备ip:"+ip);
new Thread(new get_date_th(ip, progressDialog)).start();
}
}
//接收数据的线程
class get_date_th extends Thread{
String ip;
String str="";
ProgressDialog progressDialog;
public static final int UPDATE_TEXT = 1;
private Handler handler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
progressDialog.setMessage(str);
}
};
Message message = new Message();
public get_date_th(String ip, ProgressDialog progressDialog){
this.ip=ip;
this.progressDialog=progressDialog;
}
@Override
public void run() {
message = new Message();
message.what = UPDATE_TEXT;
str = "正在创建服务器";
handler.sendMessage(message);
try {
ServerSocket serverSocket = new ServerSocket(3838, 1, InetAddress.getByName(ip));
str = "等待连接,端口:"+serverSocket.getLocalPort();
message = new Message();
message.what = UPDATE_TEXT;
handler.sendMessage(message);
Socket socket = serverSocket.accept();
str = "连接成功!";
message = new Message();
message.what = UPDATE_TEXT;
handler.sendMessage(message);
InputStream inputStream = socket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"utf-8");
char[] b = new char[1024];
String sty = "";
int a = 0;
while(a!=-1){
a = inputStreamReader.read(b);
if(a!=-1){
sty+=new String(b,0,a);
}
}
inputStreamReader.close();
inputStream.close();
socket.close();
serverSocket.close();
str = "准备接收文件:"+ sty;
message = new Message();
message.what = UPDATE_TEXT;
handler.sendMessage(message);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
serverSocket = new ServerSocket(3838, 1, InetAddress.getByName(ip));
socket = serverSocket.accept();
str = "连接成功正在接收文件:"+ sty;
message = new Message();
message.what = UPDATE_TEXT;
handler.sendMessage(message);
inputStream = socket.getInputStream();
String[] std= sty.split(",");//格式:文件名,大小
if(!(new File(path+"/"+std[0]).exists())){
new File(path+"/"+std[0]).createNewFile();
}
OutputStream outputStream = new FileOutputStream(new File(path+"/"+std[0]));
byte[] b1 = new byte[1024];
a = 0;
int add = 0;
while(a != -1){
a = inputStream.read(b1);
if(a!= -1){
outputStream.write(b1,0,a);
add+=a;
str = "接收中"+add+"/"+std[1];
message = new Message();
message.what = UPDATE_TEXT;
handler.sendMessage(message);
}
}
inputStream.close();
outputStream.close();
socket.close();
serverSocket.close();
str = "总大小:"+std[1]+",已写入:"+add+",完成,返回即可";
message = new Message();
message.what = UPDATE_TEXT;
handler.sendMessage(message);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
progressDialog.dismiss();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//加载滚动控件数据fruitlist
private void load_fruitlist(String path1){
editText.setText(path1);
path = path1;
fruitList = new ArrayList<>();//加载完成的滚动控件数据
String[] list_fplder = read_folder_list(path1);
for(String fpath:list_fplder){
File f = new File(path+"/"+fpath);
if(f.isDirectory()){//判断是否文件夹
fruitList.add(new Fruit(fpath, R.drawable.folder_pic));
}else{
fruitList.add(new Fruit(fpath, R.drawable.file_pic));
}
}
}
//判断点击的文件是否文件夹,是的话就打开,不是就弹出是否进行发送该文件
public void is_or_goto(String path1){
File f = new File(path+"/"+path1);
if(f.isDirectory()){
load_fruitlist(path+"/"+path1);
set_recyclerview();
}else{
// Toast.makeText(MainActivity.this,path1+" ,不是文件夹",Toast.LENGTH_SHORT).show();
send_date(f.getName());
}
}
//更改滚动控件内容
private void set_recyclerview(){
recyclerView.setAdapter(new FruitAdapter(fruitList, this));
}
//读取指定文件夹下所以文件,返回所有文件名
private String[] read_folder_list(String path){
return new File(path).list();
}
public static String getIpAddress(Context context) {
// 获取WiFi服务
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
// 判断WiFi是否开启
if (wifiManager.isWifiEnabled()) {
// 已经开启了WiFi
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
String ip = intToIp(ipAddress);
return ip;
} else {
// 未开启WiFi
return null;
}
}
private static String intToIp(int ipAddress) {
return (ipAddress & 0xFF) + "." +
((ipAddress >> 8) & 0xFF) + "." +
((ipAddress >> 16) & 0xFF) + "." +
(ipAddress >> 24 & 0xFF);
}
}
public class FruitAdapter extends RecyclerView.Adapter<FruitAdapter.ViewHolder> {
private List<Fruit> mFruieList;
MainActivity ma;
static class ViewHolder extends RecyclerView.ViewHolder{
View fruitView;
ImageView fruitImage;
TextView fruitName;
public ViewHolder(@NonNull View itemView) {
super(itemView);
fruitView = itemView;
fruitImage = (ImageView) itemView.findViewById(R.id.fruit_image);
fruitName = (TextView) itemView.findViewById(R.id.fruit_name);
}
}
public FruitAdapter(List<Fruit> fruitList, MainActivity ma){
mFruieList = fruitList;
this.ma=ma;
}
@NonNull
@Override
public FruitAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fruit_item, parent, false);
final ViewHolder holder = new ViewHolder(view);
holder.fruitView.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
int position = holder.getAdapterPosition();
Fruit fruit = mFruieList.get(position);
ma.is_or_goto(fruit.getName());
}
});
return holder;
}
@Override
public void onBindViewHolder(@NonNull FruitAdapter.ViewHolder holder, int position) {
Fruit fruit = mFruieList.get(position);
holder.fruitImage.setImageResource(fruit.getImageId());
holder.fruitName.setText(fruit.getName());
}
@Override
public int getItemCount() {
return mFruieList.size();
}
}
public class Fruit {
private String name;
private int imageId;
public Fruit(String name, int imageId ){
this.name = name;
this.imageId = imageId;
}
public String getName() {
return name;
}
public int getImageId() {
return imageId;
}
}
//下面是两个布局文件代码
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="1dp"
tools:layout_editor_absoluteY="1dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:id="@+id/edit_a"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="textPersonName"
android:text="/sdcard/脚本/" />
<Button
android:id="@+id/but_a"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="刷新" />
<Button
android:id="@+id/but_b"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="上层" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="发送到目标设备ip" />
<EditText
android:id="@+id/edit_b"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="192.168.1.74" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recylerview_a"
android:layout_width="match_parent"
android:layout_height="500dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal">
<Button
android:id="@+id/but_c"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="接收" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
fruit_item.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:orientation="horizontal"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ImageView
android:id="@+id/fruit_image"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
tools:srcCompat="@tools:sample/avatars" />
<TextView
android:id="@+id/fruit_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="20sp"
android:text="TextView" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
注册信息,权限申明
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.filelinkto">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:requestLegacyExternalStorage="true">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>