Android 外部存储
https://developer.android.com/guide/topics/data/data-storage.html
protected void saveto() {
// I/System.out: this.getDatabasePath("test")
// I/System.out: /data/user/0/com.example.e560.m1224a/databases/test
// I/System.out: /data/user/0/com.example.e560.m1224a/databases/test
// I/System.out: /data/user/0/com.example.e560.m1224a/databases/test
File f1 = this.getDatabasePath("test");
System.out.println("this.getDatabasePath(\"test\")");
System.out.println(f1.getAbsolutePath());
System.out.println(f1.getPath());
System.out.println(f1.toString());
// I/System.out: /storage/emulated/0/Android/data/com.example.e560.m1224a/files
// I/System.out: /storage/emulated/0/Android/data/com.example.e560.m1224a/files
// I/System.out: /storage/emulated/0/Android/data/com.example.e560.m1224a/files
File f2 = this.getExternalFilesDir(null);
System.out.println("this.getExternalFilesDir(null)");
System.out.println(f2.getAbsolutePath());
System.out.println(f2.getPath());
System.out.println(f2.toString());
// I/System.out: /data
// I/System.out: /data
// I/System.out: /data
File f3 = Environment.getDataDirectory();
System.out.println("Environment.getDataDirectory()");
System.out.println(f3.getAbsolutePath());
System.out.println(f3.getPath());
System.out.println(f3.toString());
// I/System.out: /storage/emulated/0
// I/System.out: /storage/emulated/0
// I/System.out: /storage/emulated/0
File f4 = Environment.getExternalStorageDirectory();
System.out.println("Environment.getExternalStorageDirectory()");
System.out.println(f4.getAbsolutePath());
System.out.println(f4.getPath());
System.out.println(f4.toString());
}
2016年12月25日日曜日
2016年12月24日土曜日
Android IntentService 类
Android IntentService 类
https://developer.android.com/guide/components/services.html
Develop > API Guides > 应用组件
//////////////////////////////////////////////////////////////////////
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.e560.m1217a">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyServer"></service>
</application>
</manifest>
//////////////////////////////////////////////////////////////////////
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
private int i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout linearLayout = new LinearLayout(this);
Button bt = new Button(this);
bt.setText("SaveFiletoAndroidFile");
linearLayout.addView(bt);
setContentView(linearLayout);
i = 0;
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
i++;
SavetoServer(i);
}
});
}
protected void SavetoServer(int i) {
String[] imgURLs = new String[]{
"https://farm4.staticflickr.com/3239/2897452239_d2cf730467.jpg",
"https:\\/\\/farm4.staticflickr.com\\/3050\\/2897460805_781ed40c84.jpg",
"https:\\/\\/farm4.staticflickr.com\\/3553\\/3619665782_e9766aefe5.jpg",
"https:\\/\\/farm4.staticflickr.com\\/3082\\/2716691340_2ea1c206aa.jpg",
"https:\\/\\/farm4.staticflickr.com\\/3082\\/2716691340_2ea1c206aa.jpg",
};
Intent intent = new Intent(this, MyServer.class);
intent.putExtra("URL", imgURLs[i].toString());
startService(intent);
}
}
https://developer.android.com/guide/components/services.html
Develop > API Guides > 应用组件
//////////////////////////////////////////////////////////////////////
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.e560.m1217a">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyServer"></service>
</application>
</manifest>
//////////////////////////////////////////////////////////////////////
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
private int i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout linearLayout = new LinearLayout(this);
Button bt = new Button(this);
bt.setText("SaveFiletoAndroidFile");
linearLayout.addView(bt);
setContentView(linearLayout);
i = 0;
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
i++;
SavetoServer(i);
}
});
}
protected void SavetoServer(int i) {
String[] imgURLs = new String[]{
"https://farm4.staticflickr.com/3239/2897452239_d2cf730467.jpg",
"https:\\/\\/farm4.staticflickr.com\\/3050\\/2897460805_781ed40c84.jpg",
"https:\\/\\/farm4.staticflickr.com\\/3553\\/3619665782_e9766aefe5.jpg",
"https:\\/\\/farm4.staticflickr.com\\/3082\\/2716691340_2ea1c206aa.jpg",
"https:\\/\\/farm4.staticflickr.com\\/3082\\/2716691340_2ea1c206aa.jpg",
};
Intent intent = new Intent(this, MyServer.class);
intent.putExtra("URL", imgURLs[i].toString());
startService(intent);
}
}
//////////////////////////////////////////////////////////////////////
import android.app.IntentService;
import android.content.Intent;
public class MyServer extends IntentService {
public MyServer() {
super("test");
}
@Override
protected void onHandleIntent(Intent intent) {
HTTPClient httpClient = new HTTPClient(getApplicationContext(), intent.getStringExtra("URL"));
}
}
//////////////////////////////////////////////////////////////////////
import android.content.Context;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HTTPClient {
private String urlString;
private String FileName;
private String savePath;
private Context context;
public HTTPClient(Context context, String urlString) {
this.context = context;
this.urlString = urlString.replace("\\", "");
this.savePath = String.valueOf(this.context.getFilesDir());
FileName = getFname(urlString);
System.out.println("Thread.name Httpclient" + Thread.currentThread().getName());
SaveFile();
}
public void SaveFile() {
try {
URL url = new URL(urlString);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(5 * 1000);
httpURLConnection.setReadTimeout(5 * 1000);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("GET");
if (httpURLConnection.getResponseCode() == 200) {
File SaveF = new File(this.savePath + "/" + this.FileName);
InputStream inputStream = httpURLConnection.getInputStream();
FileOutputStream fos = new FileOutputStream(SaveF);
byte[] buff = new byte[4096];
int len = 0;
while ((len = inputStream.read(buff)) != -1) {
fos.write(buff, 0, len);
fos.flush();
}
fos.close();
inputStream.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
protected String getFname(String url) {
String[] temp = url.split("/");
return temp[temp.length - 1];
}
}
2016年12月9日金曜日
2016年12月8日木曜日
Java FTP Socket
Java FTP Socket
添加对文件夹的处理。
import java.io.*;
import java.net.*;
/*
file:///E:/api/index.html
*/
class Tsocket {
public static void main(String[] args) {
try {
// File[] fs = new File[] {new File("Sublime Text Build 3114 x64.zip"), new File("Sublime Text Build 3114 x64 (2).zip"), new File("npp.6.9.2.bin.zip"), new File("Sublime Text Build 3114.zip")};
File f = new File("E:\\Android");
File[] fs = f.listFiles() ;
// UFTP u = new UFTP("xxxx.web.fc2.com", "xxxx", "xxxx");
UFTP u = new UFTP("192.168.11.7", "guest", "guest");
String code = u.FTPconnect();
if (code.equals("ConnectFTPServer")) {
u.upload(fs);
u.close();
System.out.println(code);
} else {
System.out.println(code);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class UFTP {
private String USER, PASSWORD;
private InetAddress FTPServerIP;
private BufferedReader FTPCmdreader;
private BufferedWriter FTPCmdwriter ;
public UFTP(String FURL, String USER, String PASSWORD) throws Exception {
this.FTPServerIP = InetAddress.getByName(FURL);
this.USER = USER;
this.PASSWORD = PASSWORD;
}
public String FTPconnect() {
String errorlevel = "ConnectFTPServer";
try {
Socket socket21 = new Socket (FTPServerIP, 21);
FTPCmdreader = new BufferedReader(new InputStreamReader(socket21.getInputStream()));
FTPCmdwriter = new BufferedWriter(new OutputStreamWriter(socket21.getOutputStream()));
FTPcommand(FTPCmdwriter, "USER " + USER);
FTPcommand(FTPCmdwriter, "PASS " + PASSWORD);
} catch (Exception e) {
errorlevel = "ConnectFTPerror";
}
return errorlevel;
}
public void upload(File[] files) throws Exception {
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
FTPcommand(FTPCmdwriter, "PASV ");
String[] temp = new String[] {};
String recode = new String();
while (true) {
recode = FTPCmdreader.readLine();
System.out.println(recode);
if (recode.substring(0, 3).equals("227")) {
temp = get227(recode);
break;
}
}
Socket socket20 = new Socket(temp[0], Integer.parseInt(temp[1]));
OutputStream ftpOutputStream = socket20.getOutputStream();
FileInputStream upfileInputStream = new FileInputStream(files[i]);
FTPcommand(FTPCmdwriter, "TYPE " + "I");
FTPcommand(FTPCmdwriter, "STOR " + files[i].getName());
System.out.println("UPDATE Filename " + files[i].getName());
byte[] buff = new byte[1024 * 1024];
int len = 0;
while ( (len = upfileInputStream.read(buff) ) != -1) {
ftpOutputStream.write(buff, 0, len);
ftpOutputStream.flush();
System.out.print("*");
}
ftpOutputStream.close();
upfileInputStream.close();
System.out.println("");
Thread.sleep(5 * 1000);
}
}
}
public void close() {
try {
FTPcommand(FTPCmdwriter, "QUIT ");
String temp = null;
while ( (temp = FTPCmdreader.readLine() ) != null) {
System.out.println(temp);
}
System.out.println("");
FTPCmdwriter.close();
FTPCmdreader.close();
} catch (Exception e) {
}
}
private void FTPcommand(BufferedWriter FTPCmdwriter, String FTPcmd) throws Exception {
FTPCmdwriter.write(FTPcmd + "\r\n");
FTPCmdwriter.flush();
}
protected String[] get227(String string) {
int start = string.indexOf("(") + 1;
int end = string.indexOf(")");
String substring = string.substring(start, end);
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);
String[] res = {ip, sport};
return res;
}
}
添加对文件夹的处理。
import java.io.*;
import java.net.*;
/*
file:///E:/api/index.html
*/
class Tsocket {
public static void main(String[] args) {
try {
// File[] fs = new File[] {new File("Sublime Text Build 3114 x64.zip"), new File("Sublime Text Build 3114 x64 (2).zip"), new File("npp.6.9.2.bin.zip"), new File("Sublime Text Build 3114.zip")};
File f = new File("E:\\Android");
File[] fs = f.listFiles() ;
// UFTP u = new UFTP("xxxx.web.fc2.com", "xxxx", "xxxx");
UFTP u = new UFTP("192.168.11.7", "guest", "guest");
String code = u.FTPconnect();
if (code.equals("ConnectFTPServer")) {
u.upload(fs);
u.close();
System.out.println(code);
} else {
System.out.println(code);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class UFTP {
private String USER, PASSWORD;
private InetAddress FTPServerIP;
private BufferedReader FTPCmdreader;
private BufferedWriter FTPCmdwriter ;
public UFTP(String FURL, String USER, String PASSWORD) throws Exception {
this.FTPServerIP = InetAddress.getByName(FURL);
this.USER = USER;
this.PASSWORD = PASSWORD;
}
public String FTPconnect() {
String errorlevel = "ConnectFTPServer";
try {
Socket socket21 = new Socket (FTPServerIP, 21);
FTPCmdreader = new BufferedReader(new InputStreamReader(socket21.getInputStream()));
FTPCmdwriter = new BufferedWriter(new OutputStreamWriter(socket21.getOutputStream()));
FTPcommand(FTPCmdwriter, "USER " + USER);
FTPcommand(FTPCmdwriter, "PASS " + PASSWORD);
} catch (Exception e) {
errorlevel = "ConnectFTPerror";
}
return errorlevel;
}
public void upload(File[] files) throws Exception {
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
FTPcommand(FTPCmdwriter, "PASV ");
String[] temp = new String[] {};
String recode = new String();
while (true) {
recode = FTPCmdreader.readLine();
System.out.println(recode);
if (recode.substring(0, 3).equals("227")) {
temp = get227(recode);
break;
}
}
Socket socket20 = new Socket(temp[0], Integer.parseInt(temp[1]));
OutputStream ftpOutputStream = socket20.getOutputStream();
FileInputStream upfileInputStream = new FileInputStream(files[i]);
FTPcommand(FTPCmdwriter, "TYPE " + "I");
FTPcommand(FTPCmdwriter, "STOR " + files[i].getName());
System.out.println("UPDATE Filename " + files[i].getName());
byte[] buff = new byte[1024 * 1024];
int len = 0;
while ( (len = upfileInputStream.read(buff) ) != -1) {
ftpOutputStream.write(buff, 0, len);
ftpOutputStream.flush();
System.out.print("*");
}
ftpOutputStream.close();
upfileInputStream.close();
System.out.println("");
Thread.sleep(5 * 1000);
}
}
}
public void close() {
try {
FTPcommand(FTPCmdwriter, "QUIT ");
String temp = null;
while ( (temp = FTPCmdreader.readLine() ) != null) {
System.out.println(temp);
}
System.out.println("");
FTPCmdwriter.close();
FTPCmdreader.close();
} catch (Exception e) {
}
}
private void FTPcommand(BufferedWriter FTPCmdwriter, String FTPcmd) throws Exception {
FTPCmdwriter.write(FTPcmd + "\r\n");
FTPCmdwriter.flush();
}
protected String[] get227(String string) {
int start = string.indexOf("(") + 1;
int end = string.indexOf(")");
String substring = string.substring(start, end);
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);
String[] res = {ip, sport};
return res;
}
}
2016年12月5日月曜日
FTP命令 FTP响应码
FTP命令
命令 | 描述 |
ABOR | 中断数据连接程序 |
ACCT <account> | 系统特权帐号 |
ALLO <bytes> | 为服务器上的文件存储器分配字节 |
APPE <filename> | 添加文件到服务器同名文件 |
CDUP <dir path> | 改变服务器上的父目录 |
CWD <dir path> | 改变服务器上的工作目录 |
DELE <filename> | 删除服务器上的指定文件 |
HELP <command> | 返回指定命令信息 |
LIST <name> | 如果是文件名列出文件信息,如果是目录则列出文件列表 |
MODE <mode> | 传输模式(S=流模式,B=块模式,C=压缩模式) |
MKD <directory> | 在服务器上建立指定目录 |
NLST <directory> | 列出指定目录内容 |
NOOP | 无动作,除了来自服务器上的承认 |
PASS <password> | 系统登录密码 |
PASV | 请求服务器等待数据连接 |
PORT <address> | IP 地址和两字节的端口 ID |
PWD | 显示当前工作目录 |
QUIT | 从 FTP 服务器上退出登录 |
REIN | 重新初始化登录状态连接 |
REST <offset> | 由特定偏移量重启文件传递 |
RETR <filename> | 从服务器上找回(复制)文件 |
RMD <directory> | 在服务器上删除指定目录 |
RNFR <old path> | 对旧路径重命名 |
RNTO <new path> | 对新路径重命名 |
SITE <params> | 由服务器提供的站点特殊参数 |
SMNT <pathname> | 挂载指定文件结构 |
STAT <directory> | 在当前程序或目录上返回信息 |
STOR <filename> | 储存(复制)文件到服务器上 |
STOU <filename> | 储存文件到服务器名称上 |
STRU <type> | 数据结构(F=文件,R=记录,P=页面) |
SYST | 返回服务器使用的操作系统 |
TYPE <data type> | 数据类型(A=ASCII,E=EBCDIC,I=binary) |
USER <username>> | 系统登录的用户名 |
FTP响应码
响应代码 | 解释说明 |
110 | 新文件指示器上的重启标记 |
120 | 服务器准备就绪的时间(分钟数) |
125 | 打开数据连接,开始传输 |
150 | 打开连接 |
200 | 成功 |
202 | 命令没有执行 |
211 | 系统状态回复 |
212 | 目录状态回复 |
213 | 文件状态回复 |
214 | 帮助信息回复 |
215 | 系统类型回复 |
220 | 服务就绪 |
221 | 退出网络 |
225 | 打开数据连接 |
226 | 结束数据连接 |
227 | 进入被动模式(IP 地址、ID 端口) |
230 | 登录因特网 |
250 | 文件行为完成 |
257 | 路径名建立 |
331 | 要求密码 |
332 | 要求帐号 |
350 | 文件行为暂停 |
421 | 服务关闭 |
425 | 无法打开数据连接 |
426 | 结束连接 |
450 | 文件不可用 |
451 | 遇到本地错误 |
452 | 磁盘空间不足 |
500 | 无效命令 |
501 | 错误参数 |
502 | 命令没有执行 |
503 | 错误指令序列 |
504 | 无效命令参数 |
530 | 未登录网络 |
532 | 存储文件需要帐号 |
550 | 文件不可用 |
551 | 不知道的页类型 |
552 | 超过存储分配 |
553 | 文件名不允许 |
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;
}
}
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) {
}
}
}
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();
}
}
}
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());
}
}
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);
}
}
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();
}
}
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();
}
}
所以,在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();
}
}
2016年11月29日火曜日
Android_Layout 用代码得到对象的高宽
Android_Layout 用代码得到对象的高宽
当设定 ViewGroup.LayoutParams 的设定优先。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = new Button(getApplicationContext());
button.setText("Button");
// ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(500, 500);
ViewGroup viewGroup = (ViewGroup) findViewById(R.id.activity_main);
button.setHeight(400);
button.setWidth(400);
// viewGroup.addView(button);
viewGroup.addView(button, layoutParams);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RelativeLayout.LayoutParams rl = (RelativeLayout.LayoutParams) ((Button) v).getLayoutParams();
System.out.println(rl.height);
System.out.println(rl.width);
System.out.println(((Button) v).getHeight());
System.out.println(((Button) v).getWidth());
}
});
}
当>>>>
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(500, 500);
ViewGroup viewGroup = (ViewGroup) findViewById(R.id.activity_main);
button.setHeight(400);
button.setWidth(400);
viewGroup.addView(button, layoutParams);
结果
I/System.out: 500
I/System.out: 500
I/System.out: 500
I/System.out: 500
当>>>>
button.setText("Button");
// ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(500, 500);
ViewGroup viewGroup = (ViewGroup) findViewById(R.id.activity_main);
button.setHeight(400);
button.setWidth(400);
viewGroup.addView(button);
结果
I/System.out: -2
I/System.out: -2
I/System.out: 400
I/System.out: 400
当设定 ViewGroup.LayoutParams 的设定优先。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = new Button(getApplicationContext());
button.setText("Button");
// ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(500, 500);
ViewGroup viewGroup = (ViewGroup) findViewById(R.id.activity_main);
button.setHeight(400);
button.setWidth(400);
// viewGroup.addView(button);
viewGroup.addView(button, layoutParams);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RelativeLayout.LayoutParams rl = (RelativeLayout.LayoutParams) ((Button) v).getLayoutParams();
System.out.println(rl.height);
System.out.println(rl.width);
System.out.println(((Button) v).getHeight());
System.out.println(((Button) v).getWidth());
}
});
}
当>>>>
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(500, 500);
ViewGroup viewGroup = (ViewGroup) findViewById(R.id.activity_main);
button.setHeight(400);
button.setWidth(400);
viewGroup.addView(button, layoutParams);
结果
I/System.out: 500
I/System.out: 500
I/System.out: 500
I/System.out: 500
当>>>>
button.setText("Button");
// ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(500, 500);
ViewGroup viewGroup = (ViewGroup) findViewById(R.id.activity_main);
button.setHeight(400);
button.setWidth(400);
viewGroup.addView(button);
结果
I/System.out: -2
I/System.out: -2
I/System.out: 400
I/System.out: 400
Android_Layout 用代码添加对象
Android LayoutParams
用代码添加对象(按键),并设置LayoutParames,
当按键Click时,变更LayoutParames 的值。
public class MainActivity extends AppCompatActivity {
/**
* https://www.youtube.com/watch?v=QSsvUbPVHOU&index=3&list=PLTstZD3AK3S9sR6uiKzmNtgnY5p4nMT3Z
*
* @param savedInstanceState
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = new Button(getApplicationContext());
button.setText("Button");
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
ViewGroup viewGroup = (ViewGroup) findViewById(R.id.activity_main);
// "NG>>" ViewGroup viewGroup = (ViewGroup) findViewById(R.layout.activity_main);
viewGroup.addView(button, layoutParams);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RelativeLayout.LayoutParams layoutParams1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
((Button) v).setLayoutParams(layoutParams1);
// java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.widget.RelativeLayout$LayoutParams
// "NG>>" ViewGroup.LayoutParams layoutParams1 = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
// Button bbt = (Button) v;
// bbt.setLayoutParams(layoutParams1);
}
});
}
}
用代码添加对象(按键),并设置LayoutParames,
当按键Click时,变更LayoutParames 的值。
public class MainActivity extends AppCompatActivity {
/**
* https://www.youtube.com/watch?v=QSsvUbPVHOU&index=3&list=PLTstZD3AK3S9sR6uiKzmNtgnY5p4nMT3Z
*
* @param savedInstanceState
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = new Button(getApplicationContext());
button.setText("Button");
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
ViewGroup viewGroup = (ViewGroup) findViewById(R.id.activity_main);
// "NG>>" ViewGroup viewGroup = (ViewGroup) findViewById(R.layout.activity_main);
viewGroup.addView(button, layoutParams);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RelativeLayout.LayoutParams layoutParams1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
((Button) v).setLayoutParams(layoutParams1);
// java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.widget.RelativeLayout$LayoutParams
// "NG>>" ViewGroup.LayoutParams layoutParams1 = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
// Button bbt = (Button) v;
// bbt.setLayoutParams(layoutParams1);
}
});
}
}
2016年11月27日日曜日
Android SQL
Android SQL
package com.example.e560.m1126a.ToolsClass;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONObject;
/**
* Created by E560 on 2016/11/26.
*/
public class FlickrSQL {
/**
*
*/
private Context context;
private final String TAG = "FlickrSQL";
private final String JSON_PATH = "http://cdefgab.web.fc2.com/idolsname.json";
private final String DB_NAME = "IdolAPP.db";
private final int DB_VERSION = 1;
private mSQL mSQL_db;
/**
* @param context
*/
public FlickrSQL(Context context) {
this.context = context;
mSQL_db = new mSQL(context, DB_NAME, null, DB_VERSION);
}
/**
* 檢查Name是否存在。count = 1 存在,0 不存在。
*
* @param name
* @return
* @throws Exception
*/
public int check_name(String name) throws Exception {
int count = 0;
SQLiteDatabase db = mSQL_db.getWritableDatabase();
String sql_cmd = "select name from toplist where name = ?";
Cursor cursor = db.rawQuery(sql_cmd, new String[]{name});
count = cursor.getCount();
cursor.close();
db.close();
return count;
}
/**
* 返回Name個數。
*
* @return
*/
public int db_count() {
int count = 0;
SQLiteDatabase db = mSQL_db.getReadableDatabase();
String sql_cmd = "select count(*) from toplist";
Cursor cursor = db.rawQuery(sql_cmd, null);
while (cursor.moveToNext()) {
count = Integer.parseInt(cursor.getString(cursor.getColumnIndex("count(*)")));
}
cursor.close();
Log.i(TAG, "db_idols_count: " + count);
db.close();
return count;
}
/**
* 返回所有條目。
*
* @return
*/
public Cursor Selectall() {
Cursor cursor = null;
SQLiteDatabase db = mSQL_db.getReadableDatabase();
String sql_cmd = "select * from toplist WHERE active NOT IN(?) ORDER BY up_date DESC ";
cursor = db.rawQuery(sql_cmd, new String[]{"false"});
return cursor;
}
/**
* 從JSON_PATH 更新客戶端數據庫。
* String JSON_PATH = "http://cdefgab.web.fc2.com/idolsname.json";
*
* @throws Exception
*/
public void sysdb() throws Exception {
int insertcount = 0;
SQLiteDatabase db = mSQL_db.getWritableDatabase();
String json = FlickrHttp.GetResultstring(JSON_PATH);
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("idolnames");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
if (check_name(jsonObject1.getString("name")) == 1) {
update_active(jsonObject1.getString("name"), jsonObject1.getString("active"));
} else {
insertcount++;
insert(jsonObject1.getString("name"), jsonObject1.getString("img"));
update_active(jsonObject1.getString("name"), jsonObject1.getString("active"));
}
}
Log.i(TAG, "sysdb: new Insert " + insertcount);
db.close();
}
public void insert(String name, String img_url) {
SQLiteDatabase db = mSQL_db.getWritableDatabase();
String sql_cmd = "insert into toplist(name,img_url) values (? ,?)";
db.execSQL(sql_cmd, new String[]{name, img_url});
db.close();
}
public void update_imgurl(String name, String img_url) {
SQLiteDatabase db = mSQL_db.getWritableDatabase();
String sql_cmd = "update toplist set img_url = ? where name = ?";
db.execSQL(sql_cmd, new String[]{name, img_url});
db.close();
}
public void update_active(String name, String active) {
SQLiteDatabase db = mSQL_db.getWritableDatabase();
String sql_cmd = "update toplist set active = ? where name = ?";
db.execSQL(sql_cmd, new String[]{active, name});
db.close();
}
public class mSQL extends SQLiteOpenHelper {
/**
* mSQL_db = new mSQL(context, db_pak_name, null, db_version);
* https://farm8.staticflickr.com/7566/15949681296_b6a869bdfd_q.jpg
* https://farm8.staticflickr.com/7569/15975428145_c85aae84bd_s.jpg
*/
public mSQL(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
String topidoltable = "create table toplist (rowid INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE NOT NULL,up_date TEXT default current_timestamp,img_url TEXT NOT NULL, accc INTEGER DEFAULT 0, Active TEXT DEFAULT 'ture')";
String setimgurl = "update toplist set img_url = ?";
db.execSQL(topidoltable);
db.execSQL(setimgurl, new String[]{"https://farm8.staticflickr.com/7569/15975428145_c85aae84bd_s.jpg"});
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}
/**
* Created by E560 on 2016/11/26.
*/
public class test_FlickrSQL extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
new Th().start();
}
class Th extends Thread {
@Override
public void run() {
try {
FlickrSQL flickrSQL = new FlickrSQL(getApplicationContext());
// flickrSQL.sysdb();
// flickrSQL.db_count();
Cursor cursor = flickrSQL.Selectall();
while (cursor.moveToNext()) {
String rowid = cursor.getString(cursor.getColumnIndex("rowid"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String up_date = cursor.getString(cursor.getColumnIndex("up_date"));
String img_url = cursor.getString(cursor.getColumnIndex("img_url"));
String accc = cursor.getString(cursor.getColumnIndex("accc"));
String Active = cursor.getString(cursor.getColumnIndex("Active"));
System.out.println(rowid);
System.out.println(name);
System.out.println(up_date);
System.out.println(img_url);
System.out.println(accc);
System.out.println(Active);
}
// cursor.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
package com.example.e560.m1126a.ToolsClass;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONObject;
/**
* Created by E560 on 2016/11/26.
*/
public class FlickrSQL {
/**
*
*/
private Context context;
private final String TAG = "FlickrSQL";
private final String JSON_PATH = "http://cdefgab.web.fc2.com/idolsname.json";
private final String DB_NAME = "IdolAPP.db";
private final int DB_VERSION = 1;
private mSQL mSQL_db;
/**
* @param context
*/
public FlickrSQL(Context context) {
this.context = context;
mSQL_db = new mSQL(context, DB_NAME, null, DB_VERSION);
}
/**
* 檢查Name是否存在。count = 1 存在,0 不存在。
*
* @param name
* @return
* @throws Exception
*/
public int check_name(String name) throws Exception {
int count = 0;
SQLiteDatabase db = mSQL_db.getWritableDatabase();
String sql_cmd = "select name from toplist where name = ?";
Cursor cursor = db.rawQuery(sql_cmd, new String[]{name});
count = cursor.getCount();
cursor.close();
db.close();
return count;
}
/**
* 返回Name個數。
*
* @return
*/
public int db_count() {
int count = 0;
SQLiteDatabase db = mSQL_db.getReadableDatabase();
String sql_cmd = "select count(*) from toplist";
Cursor cursor = db.rawQuery(sql_cmd, null);
while (cursor.moveToNext()) {
count = Integer.parseInt(cursor.getString(cursor.getColumnIndex("count(*)")));
}
cursor.close();
Log.i(TAG, "db_idols_count: " + count);
db.close();
return count;
}
/**
* 返回所有條目。
*
* @return
*/
public Cursor Selectall() {
Cursor cursor = null;
SQLiteDatabase db = mSQL_db.getReadableDatabase();
String sql_cmd = "select * from toplist WHERE active NOT IN(?) ORDER BY up_date DESC ";
cursor = db.rawQuery(sql_cmd, new String[]{"false"});
return cursor;
}
/**
* 從JSON_PATH 更新客戶端數據庫。
* String JSON_PATH = "http://cdefgab.web.fc2.com/idolsname.json";
*
* @throws Exception
*/
public void sysdb() throws Exception {
int insertcount = 0;
SQLiteDatabase db = mSQL_db.getWritableDatabase();
String json = FlickrHttp.GetResultstring(JSON_PATH);
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("idolnames");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
if (check_name(jsonObject1.getString("name")) == 1) {
update_active(jsonObject1.getString("name"), jsonObject1.getString("active"));
} else {
insertcount++;
insert(jsonObject1.getString("name"), jsonObject1.getString("img"));
update_active(jsonObject1.getString("name"), jsonObject1.getString("active"));
}
}
Log.i(TAG, "sysdb: new Insert " + insertcount);
db.close();
}
public void insert(String name, String img_url) {
SQLiteDatabase db = mSQL_db.getWritableDatabase();
String sql_cmd = "insert into toplist(name,img_url) values (? ,?)";
db.execSQL(sql_cmd, new String[]{name, img_url});
db.close();
}
public void update_imgurl(String name, String img_url) {
SQLiteDatabase db = mSQL_db.getWritableDatabase();
String sql_cmd = "update toplist set img_url = ? where name = ?";
db.execSQL(sql_cmd, new String[]{name, img_url});
db.close();
}
public void update_active(String name, String active) {
SQLiteDatabase db = mSQL_db.getWritableDatabase();
String sql_cmd = "update toplist set active = ? where name = ?";
db.execSQL(sql_cmd, new String[]{active, name});
db.close();
}
public class mSQL extends SQLiteOpenHelper {
/**
* mSQL_db = new mSQL(context, db_pak_name, null, db_version);
* https://farm8.staticflickr.com/7566/15949681296_b6a869bdfd_q.jpg
* https://farm8.staticflickr.com/7569/15975428145_c85aae84bd_s.jpg
*/
public mSQL(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
String topidoltable = "create table toplist (rowid INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE NOT NULL,up_date TEXT default current_timestamp,img_url TEXT NOT NULL, accc INTEGER DEFAULT 0, Active TEXT DEFAULT 'ture')";
String setimgurl = "update toplist set img_url = ?";
db.execSQL(topidoltable);
db.execSQL(setimgurl, new String[]{"https://farm8.staticflickr.com/7569/15975428145_c85aae84bd_s.jpg"});
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}
/**
* Created by E560 on 2016/11/26.
*/
public class test_FlickrSQL extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
new Th().start();
}
class Th extends Thread {
@Override
public void run() {
try {
FlickrSQL flickrSQL = new FlickrSQL(getApplicationContext());
// flickrSQL.sysdb();
// flickrSQL.db_count();
Cursor cursor = flickrSQL.Selectall();
while (cursor.moveToNext()) {
String rowid = cursor.getString(cursor.getColumnIndex("rowid"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String up_date = cursor.getString(cursor.getColumnIndex("up_date"));
String img_url = cursor.getString(cursor.getColumnIndex("img_url"));
String accc = cursor.getString(cursor.getColumnIndex("accc"));
String Active = cursor.getString(cursor.getColumnIndex("Active"));
System.out.println(rowid);
System.out.println(name);
System.out.println(up_date);
System.out.println(img_url);
System.out.println(accc);
System.out.println(Active);
}
// cursor.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
2016年11月23日水曜日
Android Handler
Android Handler
public class MainActivity extends AppCompatActivity {
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nThread n = new nThread();
n.start();
Button bt = (Button) findViewById(R.id.Bub);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Message msg = handler.obtainMessage();
msg.obj = "SandMessage";
handler.sendMessage(msg);
}
});
}
class nThread extends Thread {
@Override
public void run() {
Looper.prepare();
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
System.out.println(msg.obj);
System.out.println(Thread.currentThread().getName());
}
};
Looper.loop();
}
}
}
public class MainActivity extends AppCompatActivity {
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nThread n = new nThread();
n.start();
Button bt = (Button) findViewById(R.id.Bub);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Message msg = handler.obtainMessage();
msg.obj = "SandMessage";
handler.sendMessage(msg);
}
});
}
class nThread extends Thread {
@Override
public void run() {
Looper.prepare();
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
System.out.println(msg.obj);
System.out.println(Thread.currentThread().getName());
}
};
Looper.loop();
}
}
}
Android Handler
Android Handler
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HttpHandelar httpHandelar = new HttpHandelar();
HttpThread h = new HttpThread(httpHandelar);
h.start();
}
class HttpThread extends Thread {
public Handler handler;
public HttpThread(Handler handler) {
this.handler = handler;
}
@Override
public void run() {
super.run();
Message m = handler.obtainMessage();
HashMap<String, String> h = new HashMap<String, String>();
h.put("a", "aa");
h.put("b", "bb");
h.put("c", "cc");
h.put("d", "dd");
m.obj = h;
handler.sendMessage(m);
}
}
class HttpHandelar extends Handler {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
HashMap<String, String> mh = (HashMap) msg.obj;
Set<String> key = mh.keySet();
for (String gk : key) {
System.out.println(mh.get(gk));
}
}
}
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HttpHandelar httpHandelar = new HttpHandelar();
HttpThread h = new HttpThread(httpHandelar);
h.start();
}
class HttpThread extends Thread {
public Handler handler;
public HttpThread(Handler handler) {
this.handler = handler;
}
@Override
public void run() {
super.run();
Message m = handler.obtainMessage();
HashMap<String, String> h = new HashMap<String, String>();
h.put("a", "aa");
h.put("b", "bb");
h.put("c", "cc");
h.put("d", "dd");
m.obj = h;
handler.sendMessage(m);
}
}
class HttpHandelar extends Handler {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
HashMap<String, String> mh = (HashMap) msg.obj;
Set<String> key = mh.keySet();
for (String gk : key) {
System.out.println(mh.get(gk));
}
}
}
}
2016年11月20日日曜日
Javascript Json
Json String
function getjson(){
var idolname = document.getElementsByClassName('idolname');
var idolnames ={};
var list = [];
for(var i = 0; i < idolname.length; i++){
var item = {};
item.name = idolname[i].innerText;
item.img = "https://farm4.staticflickr.com/3239/2897452239_d2cf730467_s.jpg";
item.count = "10";
item.active = "0";
list.push(item);
}
idolnames.total = idolname.length;
idolnames.idolnames = list;
console.log(JSON.stringify(idolnames));
}
function getjson(){
var idolname = document.getElementsByClassName('idolname');
var idolnames ={};
var list = [];
for(var i = 0; i < idolname.length; i++){
var item = {};
item.name = idolname[i].innerText;
item.img = "https://farm4.staticflickr.com/3239/2897452239_d2cf730467_s.jpg";
item.count = "10";
item.active = "0";
list.push(item);
}
idolnames.total = idolname.length;
idolnames.idolnames = list;
console.log(JSON.stringify(idolnames));
}
java 字符串分割,得到文件名
java 字符串分割
得到URL的文件名
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "https://farm8.staticflickr.com/7385/26957386592_7f0aa84802_s.jpg";
String[] sa = s.split("/");
System.out.println(sa[sa.length-1]);
}
}
得到URL的文件名
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s = "https://farm8.staticflickr.com/7385/26957386592_7f0aa84802_s.jpg";
String[] sa = s.split("/");
System.out.println(sa[sa.length-1]);
}
}
2016年11月19日土曜日
Android Flickr API 显示缩略图
两个后台任务,一个负责得到列表,另一个下载每一个图片。
保存缩略图到getApplication().getCacheDir(),如果文件存在就读Cache,
不存在时从网络下载。
/**
* Created by E560 on 2016/11/19.
*/
public class Mlistview extends AppCompatActivity {
private GridView gridView;
private final String imgsize = "s";
private final String test_url = "http://cdefgab.web.fc2.com/song.json";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mlistview);
new getlistmap().execute(test_url);
}
protected class getlistmap extends AsyncTask<String, Integer, List<String>> {
/*
* 返回所以縮圖,最長邊為 100的URL;
*/
@Override
protected List<String> doInBackground(String... params) {
GetJson getJson = new GetJson(params[0]);
List<String> listurl = new ArrayList<String>();
try {
HashMap<Integer, HashMap> items_map = getJson.jsonMap();
for (int i = 0; i < items_map.size(); i++) {
listurl.add(GetJson.img_url(items_map.get(i), imgsize));
}
} catch (Exception e) {
e.printStackTrace();
}
return listurl;
}
@Override
protected void onPostExecute(List<String> strings) {
super.onPostExecute(strings);
gridView = (GridView) findViewById(R.id.mlistview);
myAdapter my = new myAdapter(strings);
my.notifyDataSetChanged();
gridView.setAdapter(my);
}
}
protected class myAdapter extends BaseAdapter {
private List<String> list;
public myAdapter(List<String> list) {
this.list = list;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Bitmap bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
View v = new View(getApplication());
if (convertView == null) {
v = LayoutInflater.from(getApplication()).inflate(R.layout.ladapter, null);
} else {
v = convertView;
}
ImageView iv = (ImageView) v.findViewById(R.id.imageView2);
iv.setImageBitmap(bitmap);
GG gg = new GG(iv);
gg.execute(list.get(position));
return v;
}
public class GG extends AsyncTask<String, Integer, Bitmap> {
private Bitmap bitmap;
private ImageView iv;
public GG(ImageView iv) {
this.iv = iv;
}
@Override
protected Bitmap doInBackground(String... params) {
try {
// https://farm8.staticflickr.com/7385/26957386592_7f0aa84802_s.jpg
String[] sa = params[0].split("/");
File file = new File(getApplication().getCacheDir(), sa[sa.length - 1]);
if (file.isFile()) {
FileInputStream fin = new FileInputStream(file);
bitmap = BitmapFactory.decodeStream(fin);
fin.close();
} else {
bitmap = GetJson.getBitmap(params[0]);
FileOutputStream fon = new FileOutputStream(file);
ByteArrayOutputStream bas = GetJson.getBAOS(params[0]);
fon.write(bas.toByteArray());
fon.flush();
fon.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
iv.setImageBitmap(bitmap);
}
}
}
}
2016年11月17日木曜日
Android BitmapFactory 文件下载前得到文件宽高
Android BitmapFactory 文件下载前得到文件宽高
http://s.nownews.com/media_crop/119027/hash/22/c9/22c9873afe491faf76ee832b96dbfec8.JPG
com.example.java.m1117a I/System.out: 4737
com.example.java.m1117a I/System.out: 3264
com.example.java.m1117a I/System.out: image/jpeg
https://c1.staticflickr.com/9/8020/7247612044_97c88b6741_b.jpg
com.example.java.m1117a I/System.out: 1024
com.example.java.m1117a I/System.out: 682
com.example.java.m1117a I/System.out: image/jpeg
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
T1 t = new T1();
t.execute("test");
}
class T1 extends AsyncTask<String, Integer, Bitmap> {
@Override
protected Bitmap doInBackground(String... params) {
Bitmap bitmap = null;
try {
// InputStream is = HttpTool.gis("https://c1.staticflickr.com/9/8020/7247612044_97c88b6741_b.jpg");
InputStream is = HttpTool.gis("http://s.nownews.com/media_crop/119027/hash/22/c9/22c9873afe491faf76ee832b96dbfec8.JPG");
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, options);
System.out.println(options.outHeight);
System.out.println(options.outWidth);
System.out.println(options.outMimeType);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
}
}
}
http://s.nownews.com/media_crop/119027/hash/22/c9/22c9873afe491faf76ee832b96dbfec8.JPG
com.example.java.m1117a I/System.out: 4737
com.example.java.m1117a I/System.out: 3264
com.example.java.m1117a I/System.out: image/jpeg
https://c1.staticflickr.com/9/8020/7247612044_97c88b6741_b.jpg
com.example.java.m1117a I/System.out: 1024
com.example.java.m1117a I/System.out: 682
com.example.java.m1117a I/System.out: image/jpeg
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
T1 t = new T1();
t.execute("test");
}
class T1 extends AsyncTask<String, Integer, Bitmap> {
@Override
protected Bitmap doInBackground(String... params) {
Bitmap bitmap = null;
try {
// InputStream is = HttpTool.gis("https://c1.staticflickr.com/9/8020/7247612044_97c88b6741_b.jpg");
InputStream is = HttpTool.gis("http://s.nownews.com/media_crop/119027/hash/22/c9/22c9873afe491faf76ee832b96dbfec8.JPG");
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, options);
System.out.println(options.outHeight);
System.out.println(options.outWidth);
System.out.println(options.outMimeType);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
}
}
}
2016年11月16日水曜日
Android flickr 工具类
Android flickr 工具类
得到Json的 字节输入流,Byte数组输出流,JSON的字符串。
http://cdefgab.web.fc2.com/song.json JSON文件样本。
package com.example.java.m1115a.Tools;
import android.content.Context;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by java on 2016/11/15.
*/
public class HttpTools {
private String url_path;
private Context context;
public HttpTools(String url_path) {
this.url_path = url_path;
}
public HttpTools(String url_path, Context context) {
this.url_path = url_path;
this.context = context;
}
public InputStream getnetInputStream() throws Exception {
URL url = new URL(url_path);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(10000);
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("GET");
InputStream inputStream = null;
if (httpURLConnection.getResponseCode() == 200) {
inputStream = httpURLConnection.getInputStream();
}
return inputStream;
}
public ByteArrayOutputStream getbyteArrayOutputStream() throws Exception {
InputStream inputStream = getnetInputStream();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int len = 0;
while ((len = inputStream.read(buff)) != -1) {
byteArrayOutputStream.write(buff, 0, len);
}
inputStream.close();
return byteArrayOutputStream;
}
public String getjsonString() throws Exception {
ByteArrayOutputStream byteArrayOutputStream = getbyteArrayOutputStream();
return byteArrayOutputStream.toString();
}
}
得到Json的 字节输入流,Byte数组输出流,JSON的字符串。
http://cdefgab.web.fc2.com/song.json JSON文件样本。
package com.example.java.m1115a.Tools;
import android.content.Context;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by java on 2016/11/15.
*/
public class HttpTools {
private String url_path;
private Context context;
public HttpTools(String url_path) {
this.url_path = url_path;
}
public HttpTools(String url_path, Context context) {
this.url_path = url_path;
this.context = context;
}
public InputStream getnetInputStream() throws Exception {
URL url = new URL(url_path);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(10000);
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("GET");
InputStream inputStream = null;
if (httpURLConnection.getResponseCode() == 200) {
inputStream = httpURLConnection.getInputStream();
}
return inputStream;
}
public ByteArrayOutputStream getbyteArrayOutputStream() throws Exception {
InputStream inputStream = getnetInputStream();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int len = 0;
while ((len = inputStream.read(buff)) != -1) {
byteArrayOutputStream.write(buff, 0, len);
}
inputStream.close();
return byteArrayOutputStream;
}
public String getjsonString() throws Exception {
ByteArrayOutputStream byteArrayOutputStream = getbyteArrayOutputStream();
return byteArrayOutputStream.toString();
}
}
继承HttpTools类
得到JSON的数字HashMap,得到Item的图片URL,得到图片的Bitmap
package com.example.java.m1115a.Tools;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
/**
* Created by java on 2016/11/15.
*/
public class GetJson extends HttpTools {
public GetJson(String url_path) {
super(url_path);
}
public HashMap<Integer, HashMap> jsonMap() throws Exception {
String jsonString = getjsonString();
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject jsonObject1 = jsonObject.getJSONObject("photos");
JSONArray jsonArray = jsonObject1.getJSONArray("photo");
HashMap<Integer, HashMap> jMap = new HashMap<Integer, HashMap>();
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> item = new HashMap<String, String>();
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
Iterator<String> iterator = jsonObject2.keys();
while (iterator.hasNext()) {
String temp = iterator.next();
item.put(temp, jsonObject2.getString(temp));
}
jMap.put(i, item);
}
return jMap;
}
public static String img_url(HashMap<String, String> item_hashMap) throws Exception {
/*
*
* https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}.jpg
* https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}_[mstzb].jpg
* https://farm{farm-id}.staticflickr.com/{server-id}/{id}_{o-secret}_o.(jpg|gif|png)
*
* String farmid = item_hashMap.get("farm");
* String Serverid = item_hashMap.get("server");
* String id = item_hashMap.get("id");
* String secret = item_hashMap.get("secret");
* String img_url = "https://farm" + farmid + ".staticflickr.com/" + Serverid + "/" + id + "_" + secret + ".jpg";
* System.out.println(img_url);
*/
HashMap<String, String> temp_map = item_hashMap;
return "https://farm" + item_hashMap.get("farm") + ".staticflickr.com/" + item_hashMap.get("server") + "/" + item_hashMap.get("id") + "_" + item_hashMap.get("secret") + ".jpg";
}
public static Bitmap getBitmap(String img_url) throws Exception {
URL url = new URL(img_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(10000);
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("GET");
Bitmap bitmap = null;
if (httpURLConnection.getResponseCode() == httpURLConnection.HTTP_OK) {
InputStream inputStream = httpURLConnection.getInputStream();
if (inputStream != null) {
byte[] buf = new byte[1024];
int len = 0;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
while ((len = inputStream.read(buf)) != -1) {
byteArrayOutputStream.write(buf, 0, len);
byteArrayOutputStream.flush();
}
bitmap = BitmapFactory.decodeByteArray(byteArrayOutputStream.toByteArray(), 0, byteArrayOutputStream.size());
inputStream.close();
byteArrayOutputStream.close();
inputStream.close();
byteArrayOutputStream.close();
}
}
return bitmap;
}
}
完成的例子,测试
每按一次按键,更换下一张图片。
应该不需要每次后 New URL.
package com.example.java.m1115a;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.java.m1115a.Tools.GetJson;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bt = (Button) findViewById(R.id.button);
bt.setOnClickListener(new View.OnClickListener() {
private int cont;
@Override
public void onClick(View v) {
new img().execute("http://cdefgab.web.fc2.com/song.json", String.valueOf(cont));
cont++;
}
});
}
public class img extends AsyncTask<String, Integer, Bitmap> {
@Override
protected Bitmap doInBackground(String... params) {
GetJson json = new GetJson(params[0]);
int cont = Integer.parseInt(params[1]);
Bitmap bitmap = null;
try {
bitmap = GetJson.getBitmap(GetJson.img_url(json.jsonMap().get(cont)));
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if (bitmap == null) {
Toast.makeText(MainActivity.this, "noImg", Toast.LENGTH_SHORT).show();
}
ImageView iv = (ImageView) findViewById(R.id.imageView);
iv.setImageBitmap(bitmap);
}
}
}
2016/11/18
也可以直接加载InputStream的方式
bitmap = BitmapFactory.decodeStream(HttpTool.gis("http://s.nownews.com/media_crop/119027/hash/22/c9/22c9873afe491faf76ee832b96dbfec8.JPG"));
也可以直接加载InputStream的方式
bitmap = BitmapFactory.decodeStream(HttpTool.gis("http://s.nownews.com/media_crop/119027/hash/22/c9/22c9873afe491faf76ee832b96dbfec8.JPG"));
登録:
投稿 (Atom)