2016年12月5日月曜日

Android FTP 文件上传

Android FTP 文件上传

package com.example.e560.m1126a.ToolsClass;

import android.util.Log;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;

/**
 * Created by E560 on 2016/12/04.
 */

public class sun_FTP {

    private String ftp_url, ftp_user, ftp_password;
    private boolean ftp_open;
    private String TAG = "sun_FTP";

    public sun_FTP(String ftp_url, String ftp_user, String ftp_password) {
        this.ftp_url = ftp_url;
        this.ftp_user = ftp_user;
        this.ftp_password = ftp_password;
        this.ftp_open = true;
    }

    public void Ftp_connect(String file_mode, File file) throws IOException {
        InetAddress inetAddress = InetAddress.getByName(ftp_url);
        Socket socket21 = new Socket(inetAddress.getHostAddress(), 21);
        BufferedReader ftpcmd_input = new BufferedReader(new InputStreamReader(socket21.getInputStream()));
        BufferedWriter ftpcmd_output = new BufferedWriter(new OutputStreamWriter(socket21.getOutputStream()));
        sendFTPcommand(ftpcmd_output, "USER " + ftp_user);
        sendFTPcommand(ftpcmd_output, "PASS " + ftp_password);
        sendFTPcommand(ftpcmd_output, "PASV ");

        switch (file_mode) {
            case "upFile":
                while (ftp_open) {
                    String temp = ftpcmd_input.readLine();
                    Log.i(TAG, temp);
                    String code = temp.substring(0, 3);
                    //进入被动模式(IP 地址、ID 端口)
                    if (code.equals("227")) {
                        String[] temp2 = get227(temp);
                        sendFTPcommand(ftpcmd_output, "TYPE " + "I");
                        sendFTPcommand(ftpcmd_output, "STOR " + file.getName());
                        upFile(temp2, file);
                        sendFTPcommand(ftpcmd_output, "QUIT");
                        ftpcmd_output.
                    }
                }
                break;
            case "downFile":

                break;
            case "Del_file":

                break;
        }
    }

    private void upFile(String[] urltemp, File file) throws IOException {
        Socket dataSocket = new Socket(urltemp[0], Integer.parseInt(urltemp[1]));
        OutputStream outputStream = dataSocket.getOutputStream();
        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] buff = new byte[20480];
        int len = 0;
        while ((len = fileInputStream.read(buff)) != -1) {
            outputStream.write(buff, 0, len);
            outputStream.flush();
        }
        outputStream.close();
        fileInputStream.close();
        dataSocket.close();
        ftp_open = false;
    }

    protected void sendFTPcommand(BufferedWriter ftpcmd_output, String command) throws IOException {
        ftpcmd_output.write(command + "\r\n");
        ftpcmd_output.flush();
        if (command.equals("QUIT")) {
            ftpcmd_output.close();
        }
    }

    protected Socket ftpSocket() throws IOException {
        Socket socket = new Socket(ftp_url, 21);

        return null;
    }

    protected String[] get227(String string) {
        //227 Entering Passive Mode (208,71,106,43,237,147).
        int start = string.indexOf("(") + 1;
        int end = string.indexOf(")");
        String substring = string.substring(start, end);
        Log.i(TAG, substring);
        String[] temp = substring.split(",");
        String ip = temp[0] + "." + temp[1] + "." + temp[2] + "." + temp[3];
        int port = Integer.parseInt(temp[4]) * 256 + Integer.parseInt(temp[5]);
        String sport = String.valueOf(port);
        Log.i(TAG, "POST " + port);
        String[] res = {ip, sport};
        return res;
    }
}

2016年12月3日土曜日

Java Socket 连接

Java Socket 连接





import java.net.*;
import java.io.*;

public class main {
public static void main(String[] args) {
TserverSocket();
}

public static void TserverSocket() {
try {
int port = 1024;
ServerSocket ss = new ServerSocket(port);
while (true) {
Socket soc = ss.accept();
System.out.println(soc);
OutputStream os = soc.getOutputStream();
OutputStreamWriter oos = new OutputStreamWriter(os);
System.out.println("server accept");
for (int i = 0; i < 1024; i++) {
oos.write(i);
oos.flush();
}
oos.close();
}
} catch (Exception e) {
}
}
}





import java.io.*;
import java.net.*;

class main {
public static void main(String[] args) {
client();
}

public static void client() {
try {
Socket s = new Socket("192.168.11.107", 1024);
InputStream is = s.getInputStream();
InputStreamReader iis = new InputStreamReader(is);
int i = 0;
while ( (i = iis.read() ) != -1 ) {
System.out.println(i);
}
System.out.println(s);
iis.close();

} catch (Exception e) {

}
}
}

2016年12月2日金曜日

Android 网络信息和IP地址

Android 网络信息和IP地址






package com.example.java.m1202a;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        System.out.println(this.getClass().getCanonicalName());
        test_network();
        test_ipadd();
    }

    /**
     * <uses-permission android:name="android.permission.INTERNET"/>
     * <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
     */

    protected void test_network() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(getApplicationContext().CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        System.out.println("toString  " + networkInfo.toString());
        System.out.println("getType  " + networkInfo.getType());
        System.out.println("getTypeName  " + networkInfo.getTypeName());
        System.out.println("getState  " + networkInfo.getState());
        System.out.println("getDetailedState  " + networkInfo.getDetailedState());
        System.out.println("getReason  " + networkInfo.getReason());
        System.out.println("getSubtypeName  " + networkInfo.getSubtypeName());
        System.out.println("getExtraInfo  " + networkInfo.getExtraInfo());
        System.out.println("describeContents  " + networkInfo.describeContents());
        System.out.println(networkInfo.getClass().getCanonicalName());
    }


    protected void test_ipadd() {
        System.out.println("test_ipadd 7777");
        try {
            Enumeration<NetworkInterface> networkInterfaces = null;
            networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface2 = networkInterfaces.nextElement();
                Enumeration<InetAddress> ipadd = networkInterface2.getInetAddresses();
                while (ipadd.hasMoreElements()) {
                    System.out.println(ipadd.nextElement().toString());
                }
            }
            System.out.println(networkInterfaces.getClass().getCanonicalName());
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }
}







2016年12月1日木曜日

Android 保存 GridView 的位置

保存 GridView 的位置

gridView.getFirstVisiblePosition();


        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                cursor.moveToPosition(position);
                String name = cursor.getString(cursor.getColumnIndex("name"));
                String img_url = cursor.getString(cursor.getColumnIndex("img_url"));
                Toast.makeText(ListPage.this, img_url, Toast.LENGTH_SHORT).show();
                grp = gridView.getFirstVisiblePosition();
                Intent intent = new Intent(getApplicationContext(), Idolpiclist.class);
                intent.putExtra("name", name);
                startActivity(intent);
            }
        });




       
    private class Myhand extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            cursor = (Cursor) msg.obj;
            System.out.println(cursor.getCount());
            GridView gridView = (GridView) findViewById(R.id.List_page_gridview);
            gridView.setSelection(grp+1);
            gridView.setAdapter(new Myadapter());
        }
    }

android.os.Process.setThreadPriority(-8);

android.os.Process.setThreadPriority(-8);


    private class MyThread extends Thread {
        @Override
        public void run() {
            android.os.Process.setThreadPriority(-8);
            super.run();
            FlickrSQL flickrSQL = new FlickrSQL(getApplicationContext());
            Message message = myhand.obtainMessage();
            message.obj = flickrSQL.SelectallIdol();
            myhand.sendMessage(message);
        }
    }

Android getDrawable,getColor 过时的替代方法

Android getDrawable,getColor 过时的替代方法

public class ContextCompat{}








public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.activity_main);
        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        relativeLayout.addView(linearLayout);

        for (int i = 0; i < 3; i++) {
            ImageView imageView = new ImageView(this);
//          过时
//          imageView.setImageDrawable(getDrawable(R.drawable.android));
//          替代方法
            imageView.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.firefox));
            TextView textView = new TextView(this);
            textView.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), android.R.color.holo_orange_dark));
            textView.setText(String.valueOf(i));
            imageView.setId(i);
            textView.setId(i);
            linearLayout.addView(imageView);
            linearLayout.addView(textView);
            imageView.setOnClickListener(this);
            textView.setOnClickListener(this);
        }
    }

    @Override
    public void onClick(View v) {
        String idinfo = "";
        switch (v.getId()) {
            case 1:
                idinfo = "Button1";
                break;
            case 2:
                idinfo = "Button2";
                break;
            case 0:
                idinfo = "Button1";
                break;
        }
        Toast.makeText(this, idinfo, Toast.LENGTH_SHORT).show();
    }
}

2016年11月30日水曜日

Java BackCall 的返回值运行在新的Thread上。

Java BackCall 的返回值运行在新的Thread上。

所以,在Android 上不能咋 BackCall上更新 主线程。


https://paiza.io/projects/dBt6EFZZnt8GdS0MDW8I-g



import java.io.*;
import java.net.*;

public class Main {
        public static void main(String[] args) throws Exception {
                // Here your code !
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                String line = br.readLine();
                Handel h = new Handel();
                System.out.println("Call by BackCall thread name >>" + Thread.currentThread().getName());
                h.Down(new Handel.BackCall() {
                        public void restout(String xx) {
                                System.out.println("BackCall thread name >>" + Thread.currentThread().getName());
                                System.out.println(xx);
                        }
                });
        }
}

class Handel {
        public interface BackCall {
                public void restout (String json);
        }
        public void Down(BackCall bc) {
                new Thread(new Runnable() {
                        public void run() {
                                try {
                                        URL u = new URL("http://www.yahoo.co.jp");
                                        HttpURLConnection c = (HttpURLConnection)u.openConnection();
                                        c.setConnectTimeout(3000);
                                        c.setReadTimeout(3000);
                                        c.setDoInput(true);
                                        c.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.6) Gecko/20040225 Firefox/0.8");
                                        InputStream is = null;
                                        c.setRequestMethod("GET");
                                        String bbb = "";
                                        if (c.getResponseCode() == 200) {
                                                is = c.getInputStream();
                                                BufferedReader br = new BufferedReader( new InputStreamReader(is));
                                                bbb = br.readLine();
                                        }
                                        bc.restout(bbb);
                                } catch (Exception e) {
                                        e.printStackTrace();
                                }
                        }
                } ).start();
        }
}