ラベル Android の投稿を表示しています。 すべての投稿を表示
ラベル Android の投稿を表示しています。 すべての投稿を表示

2018年9月12日水曜日

【Android】快速切换到主线程更新UI的几种方法

【Android】快速切换到主线程更新UI的几种方法
方法一: view.post(Runnable action)
textView.post(new Runnable() {
        @Override
        public void run() {
            textView.setText("更新textView");
            //还可以更新其他的控件
            imageView.setBackgroundResource(R.drawable.update);
        }
    });

方法二: activity.runOnUiThread(Runnable action)
public void updateUI(final Context context) {
        ((MainActivity) context).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //此时已在主线程中,可以更新UI了
            }
        });
    }

方法三: Handler机制
...

2018年7月19日木曜日

Android Handler Thread HandlerThread

Android Handler Thread HandlerThread

Handler.Callback callback = new Handler.Callback()


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView = findViewById(R.id.textView);
    button = findViewById(R.id.button);

    CC();
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            handler.sendEmptyMessage(99);
        }
    });
}

protected void CC() {
    HandlerThread handlerThread = new HandlerThread("test");
    handlerThread.start();

    Handler.Callback callback = new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            System.out.println();
            System.out.println(Thread.currentThread().getName());
            System.out.println("0000000000000000000000000000000000000");
            return false;
        }
    };
    handler = new Handler(handlerThread.getLooper(), callback);
}

Android Handler Thread HandlerThread

Android Handler Thread HandlerThread

從主線程發送消息到子線程。
子線程必須創建Looper,
handlerThread.getLooper(),
Looper.prepare(),Looper.loop()

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button = findViewById(R.id.button2);

    Tthread tthread = new Tthread();
    tthread.start();
    T3();
    T4();

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            hh.sendEmptyMessage(12);
            handler.sendEmptyMessage(12);
            handlerT4.sendEmptyMessage(12);
        }
    });
}

protected void T3() {
    HandlerThread handlerThread = new HandlerThread("name-thread");
    handlerThread.start();
    handler = new Handler(handlerThread.getLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            System.out.println(Thread.currentThread().getName());
            System.out.println("T33333333333333333");
        }
    };
}

protected void T4() {
    Thread thread = new Thread() {
        @Override
        public void run() {
            super.run();
            Looper.prepare();
            handlerT4 = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    System.out.println("T44444444444444444444");
                }
            };
            Looper.loop();
        }
    };
    thread.start();
}

class Tthread extends Thread {
    @Override
    public void run() {
        super.run();
        Looper.prepare();
        hh = new HH();
        Looper.loop();
    }
}

class HH extends Handler {
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        System.out.println("HHHHHHHHHHHHHHHHHHHHHHHH");
        System.out.println(Thread.currentThread().getName());
    }
}

2018年7月15日日曜日

StreamConfigurationMap

StreamConfigurationMap

CameraManager cameraManager = (CameraManager) getSystemService(CAMERA_SERVICE);
CameraCharacteristics cameraCharacteristics = cameraManager.getCameraCharacteristics("0");
StreamConfigurationMap streamConfigurationMap = cameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
Size[] a = streamConfigurationMap.getOutputSizes(MediaRecorder.class);
Size[] b = streamConfigurationMap.getOutputSizes(SurfaceHolder.class);




System.out.println(streamConfigurationMap);
07-15 01:25:52.463 7881-7881/? I/System.out: 
StreamConfiguration(Outputs( 
[w:4096, h:3072, format:JPEG(256), min_duration:0, stall:1093386752], 
[w:4096, h:2304, format:JPEG(256), min_duration:0, stall:870040064], 
[w:3648, h:2736, format:JPEG(256), min_duration:0, stall:908645888], 
[w:3648, h:2052, format:JPEG(256), min_duration:0, stall:731484416],
[w:3264, h:2448, format:JPEG(256), min_duration:0, stall:767309312],
[w:3264, h:1836, format:JPEG(256), min_duration:0, stall:625481984], 
[w:2592, h:1944, format:JPEG(256), min_duration:0, stall:557758208],
[w:2592, h:1458, format:JPEG(256), min_duration:0, stall:468318656],
[w:2080, h:1560, format:JPEG(256), min_duration:0, stall:430380800],
[w:2080, h:1170, format:JPEG(256), min_duration:0, stall:372785600], 
[w:2048, h:1536, format:JPEG(256), min_duration:0, stall:423346688],
[w:1920, h:1080, format:JPEG(256), min_duration:0, stall:347225600], 
[w:1600, h:1200, format:JPEG(256), min_duration:0, stall:336320000],
[w:1600, h:900, format:JPEG(256), min_duration:0, stall:302240000], 
[w:1280, h:720, format:JPEG(256), min_duration:0, stall:265433600], 
[w:800, h:600, format:JPEG(256), min_duration:0, stall:234080000],
[w:720, h:480, format:JPEG(256), min_duration:0, stall:224537600],
[w:640, h:480, format:JPEG(256), min_duration:0, stall:221811200],
[w:352, h:288, format:JPEG(256), min_duration:0, stall:207197696],
[w:320, h:240, format:JPEG(256), min_duration:0, stall:205452800],
[w:176, h:144, format:JPEG(256), min_duration:0, stall:201799424],
[w:1920, h:1080, format:PRIVATE(34), min_duration:0, stall:0],
[w:1280, h:960, format:PRIVATE(34), min_duration:0, stall:0], 
[w:1280, h:720, format:PRIVATE(34), min_duration:0, stall:0],
[w:800, h:600, format:PRIVATE(34), min_duration:0, stall:0], 
[w:720, h:480, format:PRIVATE(34), min_duration:0, stall:0], 
[w:640, h:480, format:PRIVATE(34), min_duration:0, stall:0],
[w:352, h:288, format:PRIVATE(34), min_duration:0, stall:0],
[w:320, h:240, format:PRIVATE(34), min_duration:0, stall:0], 
[w:176, h:144, format:PRIVATE(34), min_duration:0, stall:0], 
[w:1920, h:1080, format:YUV_420_888(35), min_duration:0, stall:0],
[w:1280, h:960, format:YUV_420_888(35), min_duration:0, stall:0],
[w:1280, h:720, format:YUV_420_888(35), min_duration:0, stall:0],
[w:800, h:600, format:YUV_420_888(35), min_duration:0, stall:0],
[w:720, h:480, format:YUV_420_888(35), min_duration:0, stall:0], 
[w:640, h:480, format:YUV_420_888(35), min_duration:0, stall:0], 
[w:352, h:288, format:YUV_420_888(35), min_duration:0, stall:0],
[w:320, h:240, format:YUV_420_888(35), min_duration:0, stall:0],
[w:176, h:144, format:YUV_420_888(35), min_duration:0, stall:0], 
[w:1920, h:1080, format:YV12(842094169), min_duration:0, stall:0], 
[w:1280, h:960, format:YV12(842094169), min_duration:0, stall:0],
[w:1280, h:720, format:YV12(842094169), min_duration:0, stall:0], 
[w:800, h:600, format:YV12(842094169), min_duration:0, stall:0], 
[w:720, h:480, format:YV12(842094169), min_duration:0, stall:0], 
[w:640, h:480, format:YV12(842094169), min_duration:0, stall:0],
[w:352, h:288, format:YV12(842094169), min_duration:0, stall:0],
[w:320, h:240, format:YV12(842094169), min_duration:0, stall:0],
[w:176, h:144, format:YV12(842094169), min_duration:0, stall:0]), HighResolutionOutputs(), Inputs(), ValidOutputFormatsForInput(), HighSpeedVideoConfigurations())


int[] iii = streamConfigurationMap.getOutputFormats();
256
34
35
842094169



2018年7月1日日曜日

android.hardware.camera2

android.hardware.camera2

下面的代碼可以打開相機

package com.kankanla.e560.m180701_camera;

import android.annotation.SuppressLint;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CaptureRequest;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.util.Arrays;

public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        try {
            mCamera();
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("MissingPermission")
    protected void mCamera() throws CameraAccessException {
        SurfaceView surfaceView = findViewById(R.id.surfaceView);
        final Surface surface = surfaceView.getHolder().getSurface();
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        final CameraManager cameraManager = (CameraManager) getSystemService(CAMERA_SERVICE);

        surfaceHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                try {
                    cameraManager.openCamera("0", new CameraDevice.StateCallback() {
                        @Override
                        public void onOpened(@NonNull final CameraDevice camera) {
                            try {
                                camera.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback() {
                                    @Override
                                    public void onConfigured(@NonNull CameraCaptureSession session) {
                                        try {
                                            CaptureRequest.Builder builder = camera.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
                                            builder.addTarget(surface);
                                            CaptureRequest captureRequest = builder.build();
                                            session.setRepeatingRequest(captureRequest, new CameraCaptureSession.CaptureCallback() {
                                                @Override
                                                public void onCaptureStarted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, long timestamp, long frameNumber) {
                                                    super.onCaptureStarted(session, request, timestamp, frameNumber);
                                                }
                                            }, null);
                                        } catch (CameraAccessException e) {
                                            e.printStackTrace();
                                        }
                                    }

                                    @Override
                                    public void onConfigureFailed(@NonNull CameraCaptureSession session) {

                                    }
                                }, null);
                            } catch (CameraAccessException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onDisconnected(@NonNull CameraDevice camera) {

                        }

                        @Override
                        public void onError(@NonNull CameraDevice camera, int error) {

                        }
                    }, null);
                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {

            }
        });
    }
}










2018年4月21日土曜日

為Fragment添加一個接口,是能在MainActivity下找到Fragment下的子控件View

為Fragment添加一個接口,是能在MainActivity下找到Fragment下的子控件View

public class F1 extends Fragment {
    private View view;
    public Find_button find_button;

    public void getFind_button(Find_button find_button) {
        this.find_button = find_button;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        view = inflater.inflate(R.layout.f1, null);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        find_button.button(view);
    }

}

interface Find_button {
    void button(View view);
}


-----------------------------------
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        addf1();
    }

    protected void addf1() {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        F1 f1 = new F1();
        fragmentTransaction.add(R.id.f1, f1, "f1");
        fragmentTransaction.commit();
        f1.getFind_button(new Find_button() {
            @Override
            public void button(View view) {
                final Button button = view.findViewById(R.id.button);
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        button.setText("F1.Button");
                        Toast.makeText(MainActivity.this, "F1.Button", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }
}




2018年4月5日木曜日

Creating a Custom Toast View

Creating a Custom Toast View
创建自定义Toast视图

 LayoutInflater layoutInflater = getLayoutInflater();
 View view = layoutInflater.inflate(R.layout.toastlayout ,null);
 TextView textView = view.findViewById(R.id.tx);
 textView.setText("Creating a Custom Toast View");
 Toast toast = new Toast(getContext());
 toast.setView(view);
 toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
 toast.setDuration(Toast.LENGTH_LONG);
 toast.show();



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        app:srcCompat="@android:drawable/btn_dialog" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/tx"/>
</LinearLayout>





2017年11月23日木曜日

android adb 複数TCPIP链接

android adb 複数TCPIP链接


C:\> adb -s cc1394de tcpip 5555
restarting in TCP mode port: 5555

C:\> adb connect 192.168.11.111:5555
connected to 192.168.11.111:5555

C:\> adb devices
List of devices attached
192.168.11.111:5555     device
192.168.11.109:5556     device


2017年11月17日金曜日

BroadcastReceiver 监听

protected void bttest() {
    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED:
                    int x = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE, 99);
                    if (x == BluetoothAdapter.STATE_CONNECTED) {
                        System.out.println("--------------2222222222222222------4-----");
                        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                        System.out.println(device.getAddress());
                        System.out.println(device.getName());
                        System.out.println(device.getBondState());
                        System.out.println(device.getBluetoothClass());
                    }

                    break;
                case BluetoothAdapter.ACTION_STATE_CHANGED:
                    //Bluetooth has been turned on or off.
                    System.out.println("---------ACTION_STATE_CHANGED---------------------------------------------");
                    System.out.println(intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 22));
                    break;

                case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
                    System.out.println("--------本地蓝牙适配器已完成设备发现过程。----------------");
                    break;

                case BluetoothAdapter.ACTION_DISCOVERY_STARTED:
                    System.out.println("-------------本地蓝牙适配器已启动远程设备发现过程。------------");
                    break;
                   
                case BluetoothDevice.ACTION_FOUND:
                    System.out.println("---------------------发现远程设备。---------------------");
                    System.out.println(intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE));
                    BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    System.out.println(bluetoothDevice.getName());
                    System.out.println(bluetoothDevice.getAddress());
                    break;
            }
        }
    };

    IntentFilter intentFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    IntentFilter intentFilter1 = new IntentFilter(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
    IntentFilter intentFilter2 = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    IntentFilter intentFilter3 = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    IntentFilter intentFilter4 = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    registerReceiver(broadcastReceiver, intentFilter);
    registerReceiver(broadcastReceiver, intentFilter1);
    registerReceiver(broadcastReceiver, intentFilter2);
    registerReceiver(broadcastReceiver, intentFilter3);
    registerReceiver(broadcastReceiver, intentFilter4);
}

2017年11月5日日曜日

Wifi 一覧

Wifi 一覧


<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />


protected void show_wifi_ssid() {
    WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    if (wifiManager.isWifiEnabled()) {
        List<ScanResult> scanResults = wifiManager.getScanResults();
        for (ScanResult x : scanResults) {
            System.out.println("--------------------------------------------");
            System.out.println(x.toString());
            System.out.println(x.BSSID);
            System.out.println(x.SSID);
            System.out.println(x.capabilities);
        }
    } else {
        Toast.makeText(this, "WifiNull", Toast.LENGTH_SHORT).show();
    }
}



I/System.out: SSID: AirPort61998, BSSID: 34:76:c5:5e:f2:2e, capabilities: [WPA-PSK-CCMP+TKIP][WPA2-PSK-CCMP+TKIP][WPS][ESS], level: -87, frequency: 2432, timestamp: 413176363535, distance: ?(cm), distanceSd: ?(cm), wpsState :configured, wpsDeviceName :I-O DATA 802.11n AP Router
I/System.out: 34:76:c5:5e:f2:2e
I/System.out: AirPort61998
I/System.out: [WPA-PSK-CCMP+TKIP][WPA2-PSK-CCMP+TKIP][WPS][ESS]









2017年10月29日日曜日

SupportActionBar 背景色変更

SupportActionBar 背景色変更


android.support.v7.app.ActionBar actionBar = getSupportActionBar();
int color = android.R.color.black;
Drawable backgroundDrawable = getApplicationContext().getResources().getDrawable(color);
actionBar.setBackgroundDrawable(backgroundDrawable);


2017年10月16日月曜日

assets フォルダ内の画像を読み込み

assets フォルダ内の画像を読み込み


AssetManager assetManager = getAssets();
ImageView imageView = (ImageView) findViewById(R.id.imageView);
InputStream inputStream = null;
try {
     inputStream = assetManager.open("g1213.png");
} catch (IOException e) {
     e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);


2017年8月30日水曜日

多言語化

多言語化


res/values/strings.xml - 英語
res/values-ja/strings.xml - 日本語
res/values-zh/strings.xml - 中国語(簡体)
res/values-zh-rTW/strings.xml - 中国語:台湾(繁體)
res/values-zh-rHK/strings.xml - 中国語:香港(繁體)
res/values-zh-rMO/strings.xml - 中国語:マカオ(繁體)
res/values-zh-rSG/strings.xml - 中国語:シンガポール(簡体)

2017年8月28日月曜日

Android 通知音

Android 通知音

RingtoneManager



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 999) {
            Uri uri = (Uri) data.getExtras().get(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
            Ringtone ringtone = RingtoneManager.getRingtone(getActivity(), uri);
            String name = ringtone.getTitle(getActivity());
            System.out.println(name);
            System.out.println(uri);
            set_sound_url(id, uri.toString());

            TextView select_Sound = (TextView) view.findViewById(R.id.select_sound);
            select_Sound.setText(get_sound_url_title(id));
        }
    }

    protected void lin2(String id) {
        Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
        intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, getString(R.string.select_sound_title));
        intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false); 
        intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_ALARM); 
        intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, false);
        startActivityForResult(intent, 999);
    }

2017年7月31日月曜日

Android SoundPool soundPool



public class MainActivity extends AppCompatActivity {
    protected SoundPool soundPool;
    protected int id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        test();

        AssetManager am = getAssets();
        try {
            id = soundPool.load(am.openFd("PCM-M10_441kHz16bit.wav"), 1);
        } catch (IOException e) {
            e.printStackTrace();
        }

        soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                Toast.makeText(MainActivity.this, "9999999999999", Toast.LENGTH_SHORT).show();
                soundPool.play(id, 1, 1, 1, 1, 1);
            }
        });
    }

    protected void test() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            SoundPool.Builder spb = new SoundPool.Builder();
            AudioAttributes.Builder b = new AudioAttributes.Builder();
            b.setUsage(AudioAttributes.USAGE_MEDIA);
            b.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC);
            AudioAttributes a = b.build();
            spb.setAudioAttributes(a);
            spb.setMaxStreams(12);
            soundPool = spb.build();
        }
    }
}

2017年6月2日金曜日

android Bitmap to File

android Bitmap to File


    case REQUEST_IMAGE_CAPTURE:
        File f = getFilesDir();
        Bitmap bit = data.getExtras().getParcelable("data");
        ImageView imageView = (ImageView) findViewById(R.id.bit);
        imageView.setImageBitmap(bit);

        try {
            FileOutputStream fileOutputStream = new FileOutputStream(f.getPath() + "/xxx.jpg");
            bit.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        break;

2017年5月31日水曜日

android 裁剪图片库图片

android 裁剪图片库图片





package com.kankanla.m0531a;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_IMAGE_SELECT = 1;
    private static final int REQUEST_IMAGE_CAPTURE = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setCutimg();
    }

    protected void setCutimg() {
        Intent intent = new Intent();
        intent.setAction(intent.ACTION_OPEN_DOCUMENT);
        intent.setType("image/*");
        startActivityForResult(intent, REQUEST_IMAGE_SELECT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_IMAGE_SELECT:
                    Intent intent = new Intent("com.android.camera.action.CROP");
                    Uri uri = data.getData();
                    intent.setData(uri);
                    intent.putExtra("outputX", 200);
                    intent.putExtra("outputY", 200);
                    intent.putExtra("aspectX", 1);
                    intent.putExtra("aspectY", 1);
                    intent.putExtra("scale", true);
                    intent.putExtra("return-data", true);
                    startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
                    break;
                case REQUEST_IMAGE_CAPTURE:
                    Bitmap bit = data.getExtras().getParcelable("data");
                    ImageView imageView = (ImageView) findViewById(R.id.bit);
                    imageView.setImageBitmap(bit);
                    break;
            }
        }
    }
}



2017年5月9日火曜日

Android 片段的生命周期(其 Activity 运行时)

片段的生命周期(其 Activity 运行时)

https://developer.android.com/guide/components/fragments.html


第一次启动
....m.out: Item_list--------------onAttach----------------
....m.out: Item_list--------------onCreate----------------
....m.out: Item_list--------------onCreateView----------------
....m.out: Item_list--------------onActivityCreated----------------
....m.out: Item_list--------------onStart----------------
....m.out: Item_list--------------onResume----------------


关闭屏幕
....nla.m0417b I/System.out: Item_list--------------onPause----------------
....nla.m0417b I/System.out: Item_list--------------onStop----------------

从新开屏幕
....nla.m0417b I/System.out: Item_list--------------onStart----------------
....nla.m0417b I/System.out: Item_list--------------onResume----------------



反转屏幕
....nla.m0417b I/System.out: Item_list--------------onPause----------------
....nla.m0417b I/System.out: Item_list--------------onStop----------------
....nla.m0417b I/System.out: Item_list--------------onDestroyView----------------
....nla.m0417b I/System.out: Item_list--------------onDetach----------------
....nla.m0417b I/System.out: Item_list--------------onAttach----------------
....nla.m0417b I/System.out: Item_list--------------onCreateView----------------
....nla.m0417b I/System.out: Item_list--------------onActivityCreated----------------
....nla.m0417b I/System.out: Item_list--------------onStart----------------
....nla.m0417b I/System.out: Item_list--------------onResume----------------


退回到上一Activety
....nla.m0417b I/System.out: Item_list--------------onPause----------------
....nla.m0417b I/System.out: Item_list--------------onStop----------------
....nla.m0417b I/System.out: Item_list--------------onDestroyView----------------
....nla.m0417b I/System.out: Item_list--------------onDestroy----------------
....nla.m0417b I/System.out: Item_list--------------onDetach----------------


从概览屏幕中返回
....nla.m0417b I/System.out: Item_list--------------onAttach----------------
....nla.m0417b I/System.out: Item_list--------------onCreate----------------
....nla.m0417b I/System.out: Item_list--------------onCreateView----------------
....nla.m0417b I/System.out: Item_list--------------onActivityCreated----------------
....nla.m0417b I/System.out: Item_list--------------onStart----------------
....nla.m0417b I/System.out: Item_list--------------onResume----------------

打开概览屏幕
....nla.m0417b I/System.out: Item_list--------------onPause----------------
....nla.m0417b I/System.out: Item_list--------------onStop----------------

打开其他Activety

在概览屏幕中删除
....m.out: Item_list--------------onDestroyView----------------
....m.out: Item_list--------------onDestroy----------------
....m.out: Item_list--------------onDetach----------------


按图标重新启动
....nla.m0417b I/System.out: Item_list--------------onAttach----------------
....nla.m0417b I/System.out: Item_list--------------onCreate----------------
....nla.m0417b I/System.out: Item_list--------------onCreateView----------------
....nla.m0417b I/System.out: Item_list--------------onActivityCreated----------------
....nla.m0417b I/System.out: Item_list--------------onStart----------------
....nla.m0417b I/System.out: Item_list--------------onResume----------------

2017年4月6日木曜日

Android Intent 文件存储 找到文件

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月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));
            }
        });
    }