Intent 文件存储 找到文件
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
protected void t1() {
int cc = 100;
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("audio/*");
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, cc);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == RESULT_OK) {
Uri uri = data.getData();
System.out.println(uri);
Fpath(uri);
}
}
protected void Fpath(Uri uri) {
ContentResolver contentResolver = getContentResolver();
long id = ContentUris.parseId(uri);
// 1. select _id,_data from uri while _id = id;
String[] select = new String[]{"_id","_data"};
Cursor cursor = contentResolver.query(uri, select, "_id = " + id, null, null);
// 2. select * from uri while _id = id;
// Cursor cursor = contentResolver.query(uri, null, "_id = " + id, null, null);
// 3. select * from uri;
// Cursor cursor = contentResolver.query(uri, null, null, null, null);
while (cursor.moveToNext()) {
int cont = cursor.getColumnCount();
for (int i = 0; i < cont; i++) {
System.out.print(cursor.getColumnName(i) + ">> ");
System.out.println(cursor.getString(i));
}
}
}
2017年4月6日木曜日
2017年4月5日水曜日
Android MediaPlayer 播放指定文件夾
Android MediaPlayer 播放指定文件夾
public void PlayList(File file) {
if (file.isFile()) {
if (file.isFile()) {
fileDir = file.getParentFile();
fileName = file.getName();
} else {
fileDir = file;
fileName = null;
}
fileArray = new ArrayList<String>();
fileDir.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
if (name.endsWith(".mp3") || name.endsWith(".mp4") || name.endsWith(".wav")) {
if ((new File(dir, name)).isFile()) {
fileArray.add(name);
return true;
} else {
return false;
}
} else {
return false;
}
}
});
PlayFile(fileName);
} else {
Log.i(TAG, "nofindthefile...................................................");
}
}
public void PlayFile(final String fileName) {
Log.i(TAG, "FileName" + fileName);
intNum = fileArray.indexOf(fileName);
if (intNum == -1) {
intNum = 0;
}
Uri uri = Uri.fromFile(new File(fileDir, fileArray.get(intNum)));
if (intNum < fileArray.size() - 1) {
intNum++;
} else {
intNum = 0;
}
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.reset();
try {
mediaPlayer.setDataSource(context, uri);
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
PlayFile(fileArray.get(intNum));
}
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
PlayFile(fileArray.get(intNum));
}
});
}
public void PlayList(File file) {
if (file.isFile()) {
if (file.isFile()) {
fileDir = file.getParentFile();
fileName = file.getName();
} else {
fileDir = file;
fileName = null;
}
fileArray = new ArrayList<String>();
fileDir.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
if (name.endsWith(".mp3") || name.endsWith(".mp4") || name.endsWith(".wav")) {
if ((new File(dir, name)).isFile()) {
fileArray.add(name);
return true;
} else {
return false;
}
} else {
return false;
}
}
});
PlayFile(fileName);
} else {
Log.i(TAG, "nofindthefile...................................................");
}
}
public void PlayFile(final String fileName) {
Log.i(TAG, "FileName" + fileName);
intNum = fileArray.indexOf(fileName);
if (intNum == -1) {
intNum = 0;
}
Uri uri = Uri.fromFile(new File(fileDir, fileArray.get(intNum)));
if (intNum < fileArray.size() - 1) {
intNum++;
} else {
intNum = 0;
}
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.reset();
try {
mediaPlayer.setDataSource(context, uri);
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
PlayFile(fileArray.get(intNum));
}
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
PlayFile(fileArray.get(intNum));
}
});
}
ラベル:
Android
2017年3月31日金曜日
Android 卡拉OK
Android 卡拉OK
protected void arp() {
int sampleRateInHz = 44100;
int rec_bufsize = AudioRecord.getMinBufferSize(sampleRateInHz, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
int play_bufsize = AudioTrack.getMinBufferSize(sampleRateInHz, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
// MediaRecorder.AudioSource.MIC
AudioRecord audioRecord = new AudioRecord(
MediaRecorder.AudioSource.MIC,
sampleRateInHz,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
rec_bufsize);
AudioTrack audioTrack = new AudioTrack(
AudioManager.STREAM_MUSIC,
sampleRateInHz,
AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT,
play_bufsize,
AudioTrack.MODE_STREAM);
byte[] temp = new byte[16];
audioRecord.startRecording();
audioTrack.play();
while (!stop) {
audioRecord.read(temp, 0, temp.length);
audioTrack.write(temp, 0, temp.length);
}
audioTrack.stop();
audioRecord.stop();
audioRecord.release();
}
protected void arp() {
int sampleRateInHz = 44100;
int rec_bufsize = AudioRecord.getMinBufferSize(sampleRateInHz, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
int play_bufsize = AudioTrack.getMinBufferSize(sampleRateInHz, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
// MediaRecorder.AudioSource.MIC
AudioRecord audioRecord = new AudioRecord(
MediaRecorder.AudioSource.MIC,
sampleRateInHz,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT,
rec_bufsize);
AudioTrack audioTrack = new AudioTrack(
AudioManager.STREAM_MUSIC,
sampleRateInHz,
AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT,
play_bufsize,
AudioTrack.MODE_STREAM);
byte[] temp = new byte[16];
audioRecord.startRecording();
audioTrack.play();
while (!stop) {
audioRecord.read(temp, 0, temp.length);
audioTrack.write(temp, 0, temp.length);
}
audioTrack.stop();
audioRecord.stop();
audioRecord.release();
}
ラベル:
Android
2017年3月30日木曜日
Android AoundTrack
Android AoundTrack
package com.example.kankanla.start;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(this, "AudioTrack.demo", Toast.LENGTH_LONG).show();
new Thread(new Runnable() {
@Override
public void run() {
try {
AP();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
protected void AP() throws IOException {
int sampleRateInHz = 44100;
int buferSize = AudioTrack.getMinBufferSize(
sampleRateInHz,
AudioFormat.CHANNEL_IN_STEREO,
AudioFormat.ENCODING_PCM_16BIT);
AudioTrack audioTrack = new AudioTrack(
AudioManager.STREAM_MUSIC,
sampleRateInHz,
AudioFormat.CHANNEL_IN_STEREO,
AudioFormat.ENCODING_PCM_16BIT,
buferSize, AudioTrack.MODE_STREAM);
FileInputStream fileInputStream = new FileInputStream(new File(Environment.getExternalStorageDirectory().toString(), "PCM-D50_441kHz16bit.wav"));
byte[] buffer = new byte[buferSize];
int lens = 0;
audioTrack.play();
while ((lens = fileInputStream.read(buffer)) != -1) {
audioTrack.write(buffer, 0, lens);
}
System.out.println(audioTrack.getPlayState());
audioTrack.stop();
System.out.println(audioTrack.getPlayState());
System.out.println(Thread.currentThread().getName());
// public static final int PLAYSTATE_STOPPED = 1; // matches SL_PLAYSTATE_STOPPED
// /** indicates AudioTrack state is paused */
// public static final int PLAYSTATE_PAUSED = 2; // matches SL_PLAYSTATE_PAUSED
// /** indicates AudioTrack state is playing */
// public static final int PLAYSTATE_PLAYING = 3; // matches SL_PLAYSTATE_PLAYING
}
}
package com.example.kankanla.start;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(this, "AudioTrack.demo", Toast.LENGTH_LONG).show();
new Thread(new Runnable() {
@Override
public void run() {
try {
AP();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
protected void AP() throws IOException {
int sampleRateInHz = 44100;
int buferSize = AudioTrack.getMinBufferSize(
sampleRateInHz,
AudioFormat.CHANNEL_IN_STEREO,
AudioFormat.ENCODING_PCM_16BIT);
AudioTrack audioTrack = new AudioTrack(
AudioManager.STREAM_MUSIC,
sampleRateInHz,
AudioFormat.CHANNEL_IN_STEREO,
AudioFormat.ENCODING_PCM_16BIT,
buferSize, AudioTrack.MODE_STREAM);
FileInputStream fileInputStream = new FileInputStream(new File(Environment.getExternalStorageDirectory().toString(), "PCM-D50_441kHz16bit.wav"));
byte[] buffer = new byte[buferSize];
int lens = 0;
audioTrack.play();
while ((lens = fileInputStream.read(buffer)) != -1) {
audioTrack.write(buffer, 0, lens);
}
System.out.println(audioTrack.getPlayState());
audioTrack.stop();
System.out.println(audioTrack.getPlayState());
System.out.println(Thread.currentThread().getName());
// public static final int PLAYSTATE_STOPPED = 1; // matches SL_PLAYSTATE_STOPPED
// /** indicates AudioTrack state is paused */
// public static final int PLAYSTATE_PAUSED = 2; // matches SL_PLAYSTATE_PAUSED
// /** indicates AudioTrack state is playing */
// public static final int PLAYSTATE_PLAYING = 3; // matches SL_PLAYSTATE_PLAYING
}
}
2017年3月26日日曜日
Android ContentProvider 内容提供程序單元測試
ContentProvider 内容提供程序單元測試
public class youContentProviderTest {
@Test
public void delete() throws Exception {
Context context = InstrumentationRegistry.getContext();
ContentResolver contentResolver = context.getContentResolver();
Uri uri = Uri.parse("content://com.kankanla.e560.m0325a.youContentProvider/categoly/delete/");
int i = contentResolver.delete(uri, "rowid > ?", new String[]{"10"});
System.out.println("77777777777777777777777777777777");
System.out.println(i);
}
@Test
public void insert() throws Exception {
Context context = InstrumentationRegistry.getContext();
ContentResolver contentResolver = context.getContentResolver();
Uri uri = Uri.parse("content://com.kankanla.e560.m0325a.youContentProvider/category/insert/1");
System.out.println("11111111111111111111111111111111111111111");
System.out.println(uri.getAuthority());
System.out.println(uri.getPath());
System.out.println(uri.getPathSegments());
System.out.println("2222222222222222222222222222222222222222222");
ContentValues contentValues = new ContentValues();
contentValues.put("category_name", "日本語");
for (int i = 0; i < 10; i++) {
Uri uri1 = contentResolver.insert(uri, contentValues);
System.out.println(uri1.toString());
}
}
}
package com.kankanla.e560.m0325a;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
/**
* Created by E560 on 2017/03/25.
*/
public class youContentProvider extends ContentProvider {
private static final String TAG = "youContentProvider";
private static YouDB youDB;
private static UriMatcher uriMatcher;
private static final String AUTHORITY = "com.kankanla.e560.m0325a.youContentProvider";
private static final int insert_category = 1;
private static final int select_category = 2;
private static final int insert_list = 3;
private static final int select_list = 4;
private static final int matcher_all = 5;
private static final int del_category = 6;
private static final int error = 9;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(AUTHORITY, "list/insert", insert_list);
uriMatcher.addURI(AUTHORITY, "category/insert", insert_category);
uriMatcher.addURI(AUTHORITY, "category/insert/#", insert_category);
uriMatcher.addURI(AUTHORITY, "category/delete/", del_category);
uriMatcher.addURI(AUTHORITY, "*/*/*", error);
}
@Override
public boolean onCreate() {
youDB = new YouDB(getContext());
SQLiteDatabase sqLiteDatabase = youDB.getReadableDatabase();
sqLiteDatabase.isReadOnly();
System.out.println("888888888888888888888888888888888888888888");
Log.i(TAG, String.valueOf(sqLiteDatabase.isOpen()));
return sqLiteDatabase.isOpen();
}
@Nullable
@Override
public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
return null;
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
return null;
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
Uri uri1 = Uri.parse(uri.getAuthority() + uri.getPath());
int i = uriMatcher.match(uri);
System.out.println(i);
long cont = 0;
System.out.println("000000000000000000000000000000000000000000000000");
SQLiteDatabase sqLiteDatabase = youDB.getWritableDatabase();
switch (i) {
case insert_category:
cont = sqLiteDatabase.insert("category", null, values);
uri1 = ContentUris.withAppendedId(Uri.parse(uri.getAuthority() + uri.getPath()), cont);
break;
case insert_list:
cont = sqLiteDatabase.insert("list", null, values);
uri1 = ContentUris.withAppendedId(Uri.parse(uri.getAuthority() + uri.getPath()), cont);
break;
}
System.out.println(uri1.toString());
sqLiteDatabase.close();
return uri1;
}
@Override
public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
int flag = uriMatcher.match(uri);
int con = 0;
SQLiteDatabase sqLiteDatabase = youDB.getWritableDatabase();
switch (flag) {
case del_category:
con = sqLiteDatabase.delete("category", selection, selectionArgs);
break;
}
sqLiteDatabase.close();
return con;
}
@Override
public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
return 0;
}
private class YouDB extends SQLiteOpenHelper {
private static final String name = "m0325.db";
private static final int version = 1;
public YouDB(Context context) {
super(context, name, null, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql_category = "create table category(rowid INTEGER PRIMARY KEY AUTOINCREMENT, category_name TEXT NOT NULL)";
String sql_index = "create table list (rowid INTEGER PRIMARY KEY AUTOINCREMENT, category_id INTEGER NOT NULL,comment TEXT)";
db.execSQL(sql_category);
db.execSQL(sql_index);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}
public class youContentProviderTest {
@Test
public void delete() throws Exception {
Context context = InstrumentationRegistry.getContext();
ContentResolver contentResolver = context.getContentResolver();
Uri uri = Uri.parse("content://com.kankanla.e560.m0325a.youContentProvider/categoly/delete/");
int i = contentResolver.delete(uri, "rowid > ?", new String[]{"10"});
System.out.println("77777777777777777777777777777777");
System.out.println(i);
}
@Test
public void insert() throws Exception {
Context context = InstrumentationRegistry.getContext();
ContentResolver contentResolver = context.getContentResolver();
Uri uri = Uri.parse("content://com.kankanla.e560.m0325a.youContentProvider/category/insert/1");
System.out.println("11111111111111111111111111111111111111111");
System.out.println(uri.getAuthority());
System.out.println(uri.getPath());
System.out.println(uri.getPathSegments());
System.out.println("2222222222222222222222222222222222222222222");
ContentValues contentValues = new ContentValues();
contentValues.put("category_name", "日本語");
for (int i = 0; i < 10; i++) {
Uri uri1 = contentResolver.insert(uri, contentValues);
System.out.println(uri1.toString());
}
}
}
package com.kankanla.e560.m0325a;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
/**
* Created by E560 on 2017/03/25.
*/
public class youContentProvider extends ContentProvider {
private static final String TAG = "youContentProvider";
private static YouDB youDB;
private static UriMatcher uriMatcher;
private static final String AUTHORITY = "com.kankanla.e560.m0325a.youContentProvider";
private static final int insert_category = 1;
private static final int select_category = 2;
private static final int insert_list = 3;
private static final int select_list = 4;
private static final int matcher_all = 5;
private static final int del_category = 6;
private static final int error = 9;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(AUTHORITY, "list/insert", insert_list);
uriMatcher.addURI(AUTHORITY, "category/insert", insert_category);
uriMatcher.addURI(AUTHORITY, "category/insert/#", insert_category);
uriMatcher.addURI(AUTHORITY, "category/delete/", del_category);
uriMatcher.addURI(AUTHORITY, "*/*/*", error);
}
@Override
public boolean onCreate() {
youDB = new YouDB(getContext());
SQLiteDatabase sqLiteDatabase = youDB.getReadableDatabase();
sqLiteDatabase.isReadOnly();
System.out.println("888888888888888888888888888888888888888888");
Log.i(TAG, String.valueOf(sqLiteDatabase.isOpen()));
return sqLiteDatabase.isOpen();
}
@Nullable
@Override
public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
return null;
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
return null;
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
Uri uri1 = Uri.parse(uri.getAuthority() + uri.getPath());
int i = uriMatcher.match(uri);
System.out.println(i);
long cont = 0;
System.out.println("000000000000000000000000000000000000000000000000");
SQLiteDatabase sqLiteDatabase = youDB.getWritableDatabase();
switch (i) {
case insert_category:
cont = sqLiteDatabase.insert("category", null, values);
uri1 = ContentUris.withAppendedId(Uri.parse(uri.getAuthority() + uri.getPath()), cont);
break;
case insert_list:
cont = sqLiteDatabase.insert("list", null, values);
uri1 = ContentUris.withAppendedId(Uri.parse(uri.getAuthority() + uri.getPath()), cont);
break;
}
System.out.println(uri1.toString());
sqLiteDatabase.close();
return uri1;
}
@Override
public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
int flag = uriMatcher.match(uri);
int con = 0;
SQLiteDatabase sqLiteDatabase = youDB.getWritableDatabase();
switch (flag) {
case del_category:
con = sqLiteDatabase.delete("category", selection, selectionArgs);
break;
}
sqLiteDatabase.close();
return con;
}
@Override
public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
return 0;
}
private class YouDB extends SQLiteOpenHelper {
private static final String name = "m0325.db";
private static final int version = 1;
public YouDB(Context context) {
super(context, name, null, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql_category = "create table category(rowid INTEGER PRIMARY KEY AUTOINCREMENT, category_name TEXT NOT NULL)";
String sql_index = "create table list (rowid INTEGER PRIMARY KEY AUTOINCREMENT, category_id INTEGER NOT NULL,comment TEXT)";
db.execSQL(sql_category);
db.execSQL(sql_index);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}
ラベル:
Android
2017年3月19日日曜日
android adb error (10061)
解決步驟
C:\Users>adb devices
List of devices attached
cc13094de device
C:\Users>adb connect 192.168.11.100
unable to connect to 192.168.11.100:5555: cannot connect to 192.168.11.100:5555: 対象のコンピューターによって拒否された ため、接続できませんでした。 (10061)
C:\Users>adb kill-server
C:\Users>adb usb
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
restarting in USB mode
C:\Users>adb tcpip 5555
restarting in TCP mode port: 5555
C:\Users>adb connect 192.168.11.100
connected to 192.168.11.100:5555
C:\Users>adb devices
List of devices attached
192.168.11.100:5555 device
cc13094de device
C:\Users>adb devices
List of devices attached
cc13094de device
C:\Users>adb connect 192.168.11.100
unable to connect to 192.168.11.100:5555: cannot connect to 192.168.11.100:5555: 対象のコンピューターによって拒否された ため、接続できませんでした。 (10061)
C:\Users>adb kill-server
C:\Users>adb usb
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
restarting in USB mode
C:\Users>adb tcpip 5555
restarting in TCP mode port: 5555
C:\Users>adb connect 192.168.11.100
connected to 192.168.11.100:5555
C:\Users>adb devices
List of devices attached
192.168.11.100:5555 device
cc13094de device
ラベル:
Android
2017年3月17日金曜日
Andriod Intent Camera
Andriod Intent Camera
public class MainActivity extends AppCompatActivity {
protected File file;
protected Uri uri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1();
}
protected void t1() {
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "00000aaaa.jpg");
uri = Uri.fromFile(file);
Intent intent = new Intent();
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, 99);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 99 && resultCode == RESULT_OK) {
view2();
}
}
protected void view2() {
Display display = getWindowManager().getDefaultDisplay();
Point p = new Point();
display.getSize(p);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file.getAbsolutePath(), options);
int samsize = Math.max(options.outHeight / p.y, options.outWidth / p.x);
options.inJustDecodeBounds = false;
options.inSampleSize = samsize;
ImageView imageView = (ImageView) findViewById(R.id.vvvv);
Bitmap bt = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
imageView.setImageBitmap(bt);
}
}
public class MainActivity extends AppCompatActivity {
protected File file;
protected Uri uri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1();
}
protected void t1() {
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "00000aaaa.jpg");
uri = Uri.fromFile(file);
Intent intent = new Intent();
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, 99);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 99 && resultCode == RESULT_OK) {
view2();
}
}
protected void view2() {
Display display = getWindowManager().getDefaultDisplay();
Point p = new Point();
display.getSize(p);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(file.getAbsolutePath(), options);
int samsize = Math.max(options.outHeight / p.y, options.outWidth / p.x);
options.inJustDecodeBounds = false;
options.inSampleSize = samsize;
ImageView imageView = (ImageView) findViewById(R.id.vvvv);
Bitmap bt = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
imageView.setImageBitmap(bt);
}
}
ラベル:
Android
2017年3月13日月曜日
2017年3月12日日曜日
intent Camera
intent Camera
protected void t1() {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
ImageView imageView = (ImageView) findViewById(R.id.imageView);
Bundle bu = data.getExtras();
Bitmap bt = (Bitmap) bu.get("data");
imageView.setImageBitmap(bt);
}
https://developer.android.com/training/camera/photobasics.html
static final int REQUEST_IMAGE_CAPTURE = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
}
}
protected void t1() {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
ImageView imageView = (ImageView) findViewById(R.id.imageView);
Bundle bu = data.getExtras();
Bitmap bt = (Bitmap) bu.get("data");
imageView.setImageBitmap(bt);
}
https://developer.android.com/training/camera/photobasics.html
static final int REQUEST_IMAGE_CAPTURE = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
}
}
ラベル:
Android
2017年3月6日月曜日
Android 的第一款軟體誕生
Android 的第一款軟體誕生。利用了Flickr提供的圖片查詢API按照名稱
查詢圖片,並顯示在手機上。
2016年5月開始接觸JAVA, 本軟體是邊學邊用的結果。
下一款軟體爭取能夠公開在GooglePlay上。
下載地址
app-free-release.apk
https://www.asuswebstorage.com/navigate/s/181301E935CB4FD480EB2D54B763A9A9Y
查詢圖片,並顯示在手機上。
2016年5月開始接觸JAVA, 本軟體是邊學邊用的結果。
下一款軟體爭取能夠公開在GooglePlay上。
下載地址
app-free-release.apk
https://www.asuswebstorage.com/navigate/s/181301E935CB4FD480EB2D54B763A9A9Y
2017年2月24日金曜日
Android MediaPlayer
Android MediaPlayer
protected void t1() {
try {
String url = "http://www.ne.jp/asahi/music/myuu/wave/menuettm.mp3";
// Uri mu = Uri.parse("http://www.ne.jp/asahi/music/myuu/wave/menuettm.mp3");
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
// mediaPlayer.setDataSource(getApplicationContext(), mu);
mediaPlayer.prepare();
mediaPlayer.start();
mediaPlayer.setDataSource(url);
} catch (IOException e) {
e.printStackTrace();
}
}
protected void t1() {
try {
String url = "http://www.ne.jp/asahi/music/myuu/wave/menuettm.mp3";
// Uri mu = Uri.parse("http://www.ne.jp/asahi/music/myuu/wave/menuettm.mp3");
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
// mediaPlayer.setDataSource(getApplicationContext(), mu);
mediaPlayer.prepare();
mediaPlayer.start();
mediaPlayer.setDataSource(url);
} catch (IOException e) {
e.printStackTrace();
}
}
2017年2月7日火曜日
2016年12月25日日曜日
Android 外部存储
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());
}
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月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月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;
}
}
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月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);
}
}
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();
}
}
}
登録:
投稿 (Atom)