반응형

WebView objects allow you to display web content as part of your activity layout but lack some of the features of fully-developed browsers. A WebView is useful when you need increased control over the UI and advanced configuration options that will allow you to embed web pages in a specially-designed environment for your app.

In most cases, Android recommends using a standard web browser, like Chrome, to deliver content to the user. 


크롬이나 다른 웹브라우저와 같은 다양한 기능은 없지만 WebView를 사용해 앱 안에서 간단히 인터넷 웹 페이지를 디스플레이 할 수 있다.


<AndroidManifest.xml>

1
2
3
4
5
6
7
8
9
10
    <uses-permission android:name="android.permission.INTERNET"/>
 
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true">



<MainActivity.java>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public class MainActivity extends AppCompatActivity {
 
    EditText editText;
    WebView webView;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        editText = findViewById(R.id.editText);
        webView = findViewById(R.id.webView);
 
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true); // Tells the WebView to enable JavaScript execution.
        webSettings.setBuiltInZoomControls(true);   // Sets whether the WebView should use its built-in zoom mechanisms.
        //webSettings.setDisplayZoomControls(false);
        // Sets whether the WebView should display on-screen zoom controls when using the built-in zoom mechanisms.
        // The default is true.
 
        webView.setWebViewClient(new ViewClient());
 
        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                webView.loadUrl(editText.getText().toString());
            }
        });
    }
 
    private class ViewClient extends WebViewClient {
        // This method was deprecated in API level 24. Use shouldOverrideUrlLoading(WebView, WebResourceRequest) instead.
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
 
            return true;
        }
 
//        @Override
//        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
//            view.loadUrl(request.getUrl().toString());
//
//            return true;
//        }
    }
}




Run the app and enter a URL.


Click 'OPEN' button and it shows the web site.


Use the built-in zoom controls if needed.


반응형
Posted by J-sean
:
반응형

A YouTubePlayer provides methods for loading, playing and controlling YouTube video playback.


Copy 'YouTubeAndroidPlayerApi.jar' to 'app/libs' and sync project with gradle files.


<AndroidManifest.xml>

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



<activity_main.xml>

1
2
3
4
    <com.google.android.youtube.player.YouTubePlayerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/youTubePlayerView"/>



<MainActivity.java>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
public class MainActivity extends YouTubeBaseActivity {
 
    YouTubePlayerView youTubePlayerView;
    YouTubePlayer player;
 
    private static String API_KEY = "AIyaSyDpsLddBj2ISc-NHU4sxWFh4JlcHNELir8";  // Your API Key
    private static String videoId = "Mx5GmonOiKo"// Youtube video ID from https://youtu.be/Mx5GmonOiKo
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        initPlayer();
 
        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadVideo();
            }
        });
 
        Button button2 = findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playVideo();
            }
        });
    }
 
    public void initPlayer() {
        youTubePlayerView = findViewById(R.id.youTubePlayerView);
        youTubePlayerView.initialize(API_KEY, new YouTubePlayer.OnInitializedListener() {
            @Override
            public void onInitializationSuccess(YouTubePlayer.Provider provider, final YouTubePlayer youTubePlayer, boolean b) {
 
                player = youTubePlayer;
 
                youTubePlayer.setPlayerStateChangeListener(new YouTubePlayer.PlayerStateChangeListener() {
                    @Override
                    public void onLoading() {
 
                    }
 
                    @Override
                    public void onLoaded(String s) {
                        Toast.makeText(getApplicationContext(), s + " loaded", Toast.LENGTH_SHORT).show();
                    }
 
                    @Override
                    public void onAdStarted() {
 
                    }
 
                    @Override
                    public void onVideoStarted() {
 
                    }
 
                    @Override
                    public void onVideoEnded() {
 
                    }
 
                    @Override
                    public void onError(YouTubePlayer.ErrorReason errorReason) {
 
                    }
                });
            }
 
            @Override
            public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
 
            }
        });
    }
 
    public void loadVideo() {
        if (player != null) {
            player.cueVideo(videoId);
            // Loads the specified video's thumbnail and prepares the player to play the video, but does not download any of the video stream
            // until play() is called.
        }
    }
 
    public void playVideo() {
        if (player != null) {
            if (player.isPlaying()) {
                player.pause();
            } else {
                player.play();
            }
        }
    }
}


Your activity needs to extend YouTubeBaseActivity.



Run the app and click the LOAD button.


It loads the video.


Play and enjoy the video.


반응형
Posted by J-sean
:
반응형

You can stream a video file with VideoView.


<AndroidManifest.xml>

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



<MainActivity.java>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
public class MainActivity extends AppCompatActivity {
 
    VideoView videoView;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        videoView = findViewById(R.id.videoView);
 
        MediaController mediaController = new MediaController(this);
        videoView.setMediaController(mediaController);
 
        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                videoView.setVideoURI(Uri.parse("http://nexoft.tk/data/WhileYouWereSleeping.mp4")); // or your video file url.
                videoView.requestFocus();
                videoView.start();
            }
        });
 
        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                Toast.makeText(getApplicationContext(), "Video play completed", Toast.LENGTH_SHORT).show();
            }
        });
 
        videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                String message;
 
                switch (what) {
                    case MediaPlayer.MEDIA_ERROR_UNKNOWN:
                        message = "MEDIA_ERROR_UNKNOWN";
                        break;
 
                    case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
                        message = "MEDIA_ERROR_SERVER_DIED";
                        break;
 
                    default:
                        message = "No what";
                }
 
                switch (extra) {
                    case MediaPlayer.MEDIA_ERROR_IO:
                        message += ", MEDIA_ERROR_IO";
                        break;
 
                    case MediaPlayer.MEDIA_ERROR_MALFORMED:
                        message += ", MEDIA_ERROR_MALFORMED";
                        break;
 
                    case MediaPlayer.MEDIA_ERROR_UNSUPPORTED:
                        message += ", MEDIA_ERROR_UNSUPPORTED";
                        break;
 
                    case MediaPlayer.MEDIA_ERROR_TIMED_OUT:
                        message += ", MEDIA_ERROR_TIMED_OUT";
                        break;
 
                    default:
                        message += ", No extra";
                }
                Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
 
                //    Returns true if the method handled the error, false if it didn't. Returning false, or not having an OnErrorListener
                //    at all, will cause the OnCompletionListener to be called.
                return true;
            }
        });
    }
}




Run the app and click the PLAY button.


It may not be able to stream the video and show an error message in AVD.


It can stream the video in the actual device.


반응형
Posted by J-sean
:
반응형

Explains how to take a photo and save the full-size photo in an easy way.


기기의 카메라 앱을 실행 시키고 사진을 찍어 앱 디렉토리에 저장하고 화면에 표시 한다.


<AndroidManifest.xml>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
    <!-- The write permission implicitly allows reading, so if you need to write
    to the external storage then you need to request only one permission: -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
 
    <uses-feature android:name="android.hardware.camera"
                  android:required="true"/>
 
    <application
        ...
        <provider
            android:authorities="com.example.myapplication.fileprovider"
            android:name="androidx.core.content.FileProvider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths">
            </meta-data>
        </provider>
        ...
    </application>



<res/xml/file_paths.xml>

1
2
3
4
5
6
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="my_images"
        path="Android/data/com.example.myapplication/files/Pictures"/>
</paths>



<MainActivity.java>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
public class MainActivity extends AppCompatActivity {
 
    static final int PERMISSION_REQUEST_CONTACTS = 1001;
    static final int REQUEST_TAKE_PHOTO = 2001;
 
    ImageView imageView;
    String currentPhotoPath;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        String[] permissionRequests = {
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };
 
        checkPermissions(permissionRequests);
 
        imageView = findViewById(R.id.imageView);
        Button button = findViewById(R.id.button);
 
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (intent.resolveActivity(getPackageManager()) != null) {
                    File photoFile = null;
                    try {
                        photoFile = createImageFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (photoFile != null) {
                        Uri photoURI = FileProvider.getUriForFile(getApplicationContext(),
                                "com.example.myapplication.fileprovider", photoFile);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                        startActivityForResult(intent, REQUEST_TAKE_PHOTO);
                    }
                }
            }
        });
    }
 
    public void checkPermissions(String[] permissionRequests) {
        final ArrayList<String> permissionRequestList = new ArrayList<String>();
 
        for (final String request : permissionRequests) {
            if (ContextCompat.checkSelfPermission(this, request) != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, request)) {   // Redundant in this case
                    permissionRequestList.add(request);
                } else {
                    permissionRequestList.add(request);
                }
            }
        }
 
        if (!permissionRequestList.isEmpty()) {
            final String[] results = new String[permissionRequestList.size()];
            permissionRequestList.toArray(results);
 
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("info");
 
            String msg = "This app won't work properly unless you grant below permissions.";
            for (String str : results)
                msg += ("\n- "+ str);
 
            builder.setMessage(msg);
            builder.setIcon(android.R.drawable.ic_dialog_info);
 
            builder.setNeutralButton("OK"new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    ActivityCompat.requestPermissions(MainActivity.this, results, PERMISSION_REQUEST_CONTACTS);
                }
            });
 
            AlertDialog dialog = builder.create();
            dialog.show();
        }
    }
 
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_CONTACTS: {
                for (int i = 0; i < grantResults.length; i++) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        Toast.makeText(this, permissions[i] + " permission granted.", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(this, permissions[i] + " permission denied.", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    }
 
    private File createImageFile() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyMMdd_HHmmss").format(new Date());
        String imageFileName = "IMAGE_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        // If you saved your photo to the directory provided by getExternalFilesDir(),
        // the media scanner cannot access the files because they are private to your app.
        File image = File.createTempFile(imageFileName, ".jpg", storageDir);
        currentPhotoPath = image.getAbsolutePath();
 
        return image;
    }
 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
 
        if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
            Bitmap originalBitmap = BitmapFactory.decodeFile(currentPhotoPath);
 
            int scaleFactor = Math.max(originalBitmap.getWidth()/imageView.getWidth(), originalBitmap.getHeight()/imageView.getHeight());
            if (scaleFactor < 1)
                scaleFactor = 1;
            Bitmap scaledBitmap = Bitmap.createScaledBitmap(originalBitmap, originalBitmap.getWidth()/scaleFactor,
                    originalBitmap.getHeight()/scaleFactor, true);
 
            Matrix m = new Matrix();
            m.postRotate(90);
            Bitmap rotatedBitmap = Bitmap.createBitmap(scaledBitmap, 00, scaledBitmap.getWidth(), scaledBitmap.getHeight(), m, true);
 
            imageView.setImageBitmap(rotatedBitmap);
        }
    }
}




Run the app and click CAMERA button.


Take a picture.


The displayed picture is rotated 90 degrees in AVD but is upright in the actual device.


Actual device.


※ Reference:

Android Developers


반응형
Posted by J-sean
:
반응형

Explains how to take a photo and get the thumbnail of it in an easy way.

기기의 카메라 앱을 실행 시키고 사진을 찍어 썸네일을 가져 온다.


<AndroidManifest.xml>

1
    <uses-feature android:name="android.hardware.camera" android:required="true"/>



<MainActivity.java>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class MainActivity extends AppCompatActivity {
 
    static final int REQUEST_IMAGE_CAPTURE = 1001;
 
    ImageView imageView;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        imageView = findViewById(R.id.imageView);
        Button button = findViewById(R.id.button);
 
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (intent.resolveActivity(getPackageManager()) != null) {
                    startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
                }
            }
        });
    }
 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            Bitmap bitmap = (Bitmap)extras.get("data");
            imageView.setImageBitmap(bitmap);
        }
    }
}




Run the app and click CAMERA button.


Take a picture.


Get the thumbnail.


반응형
Posted by J-sean
:
반응형

You can retrieve the contact data.

연락처 정보를 모두 받아 올 수 있다.


<AndroidManifest.xml>

1
2
    <uses-permission android:name="android.permission.READ_CONTACTS"/>
    <uses-permission android:name="android.permission.WRITE_CONTACTS"/>


<MainActivity.java>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
public class MainActivity extends AppCompatActivity {
 
    private final int MY_PERMISSION_REQUEST_CONTACTS = 1001;
    private final int MY_ACTIVITY_REQUEST_CODE = 2001;
 
    TextView textView;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        String[] permissionRequests = {
                Manifest.permission.READ_CONTACTS,
                Manifest.permission.WRITE_CONTACTS
        };
 
        checkPermissions(permissionRequests);
 
        textView = findViewById(R.id.textView);
 
        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseContacts();
            }
        });
    }
 
    public void checkPermissions(String[] permissionRequests) {
        final ArrayList<String> permissionRequestList = new ArrayList<String>();
 
        for (final String request : permissionRequests) {
            if (ContextCompat.checkSelfPermission(this, request) != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, request)) {   // Redundant in this case
                    permissionRequestList.add(request);
                } else {
                    permissionRequestList.add(request);
                }
            }
        }
 
        if (!permissionRequestList.isEmpty()) {
            final String[] results = new String[permissionRequestList.size()];
            permissionRequestList.toArray(results);
 
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("info");
 
            String msg = "This app won't work properly unless you grant below permissions.";
            for (String str : results)
                msg += ("\n- "+ str);
 
            builder.setMessage(msg);
            builder.setIcon(android.R.drawable.ic_dialog_info);
 
            builder.setNeutralButton("OK"new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    ActivityCompat.requestPermissions(MainActivity.this, results, MY_PERMISSION_REQUEST_CONTACTS);
                }
            });
 
            AlertDialog dialog = builder.create();
            dialog.show();
        }
    }
 
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSION_REQUEST_CONTACTS: {
                for (int i = 0; i < grantResults.length; i++) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        Toast.makeText(this, permissions[i] + " permission granted.", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(this, permissions[i] + " permission denied.", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    }
 
    public void chooseContacts() {
        Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
        startActivityForResult(contactPickerIntent, MY_ACTIVITY_REQUEST_CODE);
    }
 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == MY_ACTIVITY_REQUEST_CODE) {
                try {
                    Uri contactsUri = data.getData();
                    String id = contactsUri.getLastPathSegment();
 
                    getContacts(id);
                } catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
 
    public void getContacts(String id) {
        Cursor cursor;
        String name;
        String phone;
 
        try {
            cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?",
                    new String[] {id},
                    null);
 
            if (cursor.moveToFirst()) {
                name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                textView.setText("Name: " + name + '\n' + "Phone: " + phone + '\n');
 
                String columns[] = cursor.getColumnNames();
                for (String column : columns) {
                    int index = cursor.getColumnIndex(column);
                    String columnOutput = ("#" + index + " -> [" + column + "] = " + cursor.getString(index));
                    textView.append('\n' + columnOutput);
                }
                cursor.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}




Run the app.


Choose contact.


Display contact data.


반응형
Posted by J-sean
:
반응형

You can retrieve multiple sensor data at the same time. Say you need ACCELEROMETER and AMBIENT_TEMPERATURE data.

동시에 여러가지 센서 데이터를 받아 올 수 있다. 예를 들어 ACCELEROMETER 와 AMBIENT_TEMPERATURE 센서의 데이터를 받아 오자.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
public class MainActivity extends AppCompatActivity {
 
    TextView textView;
    TextView textView2;
 
    SensorManager manager;
    List<Sensor> sensors;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        textView = findViewById(R.id.textView);
        textView2 = findViewById(R.id.textView2);
 
        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                manager = (SensorManager)getSystemService(SENSOR_SERVICE);
                sensors = manager.getSensorList(Sensor.TYPE_ALL);
 
                int index = 0;
                for (Sensor sensor : sensors) {
                    textView.append("#" + index++ + ": " + sensor.getName() + '\n');
                }
            }
        });
 
        final SensorEventListener sensorEventListener = new SensorEventListener() {
            @Override
            public void onSensorChanged(SensorEvent event) {
                if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
                    String str = "Sensor Timestamp: " + event.timestamp + "\n\n";
                    str = str + "Sensor Accuracy: " + event.accuracy + '\n';
 
                    for (int index = 0; index < event.values.length; index++) {
                        str += ("Sensor Value #" + index + ": " + event.values[index] + '\n');
                    }
 
                    textView.setText(str);
                }
 
                if (event.sensor.getType() == Sensor.TYPE_AMBIENT_TEMPERATURE) {
                    String str = "Sensor Timestamp: " + event.timestamp + "\n\n";
                    str = str + "Sensor Accuracy: " + event.accuracy + '\n';
 
                    for (int index = 0; index < event.values.length; index++) {
                        str += ("Sensor Value #" + index + ": " + event.values[index] + '\n');
                    }
 
                    textView2.setText(str);
                }
            }
 
            /*
            SENSOR_STATUS_ACCURACY_HIGH
            This sensor is reporting data with maximum accuracy
            Constant Value: 3 (0x00000003)
            SENSOR_STATUS_ACCURACY_LOW
            This sensor is reporting data with low accuracy, calibration with the environment is needed
            Constant Value: 1 (0x00000001)
            SENSOR_STATUS_ACCURACY_MEDIUM
            This sensor is reporting data with an average level of accuracy, calibration with the environment may improve the readings
            Constant Value: 2 (0x00000002)
            SENSOR_STATUS_NO_CONTACT
            The values returned by this sensor cannot be trusted because the sensor had no contact with what it was measuring
            (for example, the heart rate monitor is not in contact with the user).
            Constant Value: -1 (0xffffffff)
            SENSOR_STATUS_UNRELIABLE
            The values returned by this sensor cannot be trusted, calibration is needed or the environment doesn't allow readings
            Constant Value: 0 (0x00000000)
            */
 
            @Override
            public void onAccuracyChanged(Sensor sensor, int accuracy) {
 
            }
        };
 
        Button button2 = findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                manager.registerListener(sensorEventListener, manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_UI);
                // If sensors.get(0) == manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)...
                //manager.registerListener(sensorEventListener, sensors.get(0), SensorManager.SENSOR_DELAY_UI);
                manager.registerListener(sensorEventListener, manager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE), SensorManager.SENSOR_DELAY_UI);
            }
        });
 
        Button button3 = findViewById(R.id.button3);
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                manager.unregisterListener(sensorEventListener, manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER));
                // If sensors.get(0) == manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)...
                //manager.unregisterListener(sensorEventListener, sensors.get(0));
                manager.unregisterListener(sensorEventListener, manager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE));
            }
        });
    }
}



Sensor List


Sensor data


반응형
Posted by J-sean
:
반응형

서버에서 데이터를 받아 오는 경우 모든 문자가 알파벳이나 숫자라면 상관 없지만 한글이 섞여 있다면 글자가 깨지는 문제가 발생하고 어떤 인코딩이 사용되었는지 확인하기 어려운 경우가 있다. 아래와 같이 단순한 방법으로 간단히 확인 할 수 있다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
try {
    Log.d("Encoding Check""utf-8 -> euc-kr: " + new String(str.getBytes("utf-8"), "euc-kr"));
    Log.d("Encoding Check""utf-8 -> ksc5601: " + new String(str.getBytes("utf-8"), "ksc5601"));
    Log.d("Encoding Check""utf-8 -> x-windows-949: " + new String(str.getBytes("utf-8"), "x-windows-949"));
    Log.d("Encoding Check""utf-8 -> iso-8859-1: " + new String(str.getBytes("utf-8"), "iso-8859-1"));
 
    Log.d("Encoding Check""iso-8859-1 -> euc-kr: " + new String(str.getBytes("iso-8859-1"), "euc-kr"));
    Log.d("Encoding Check""iso-8859-1 -> ksc5601: " + new String(str.getBytes("iso-8859-1"), "ksc5601"));
    Log.d("Encoding Check""iso-8859-1 -> x-windows-949: " + new String(str.getBytes("iso-8859-1"), "x-windows-949"));
    Log.d("Encoding Check""iso-8859-1 -> utf-8: " + new String(str.getBytes("iso-8859-1"), "utf-8"));
 
    Log.d("Encoding Check""euc-kr -> utf-8: " + new String(str.getBytes("euc-kr"), "utf-8"));
    Log.d("Encoding Check""euc-kr -> ksc5601: " + new String(str.getBytes("euc-kr"), "ksc5601"));
    Log.d("Encoding Check""euc-kr -> x-windows-949: " + new String(str.getBytes("euc-kr"), "x-windows-949"));
    Log.d("Encoding Check""euc-kr -> iso-8859-1: " + new String(str.getBytes("euc-kr"), "iso-8859-1"));
 
    Log.d("Encoding Check""ksc5601 -> euc-kr: " + new String(str.getBytes("ksc5601"), "euc-kr"));
    Log.d("Encoding Check""ksc5601 -> utf-8: " + new String(str.getBytes("ksc5601"), "utf-8"));
    Log.d("Encoding Check""ksc5601 -> x-windows-949: " + new String(str.getBytes("ksc5601"), "x-windows-949"));
    Log.d("Encoding Check""ksc5601 -> iso-8859-1: " + new String(str.getBytes("ksc5601"), "iso-8859-1"));
 
    Log.d("Encoding Check""x-windows-949 -> euc-kr: " + new String(str.getBytes("x-windows-949"), "euc-kr"));
    Log.d("Encoding Check""x-windows-949 -> utf-8: " + new String(str.getBytes("x-windows-949"), "utf-8"));
    Log.d("Encoding Check""x-windows-949 -> ksc5601: " + new String(str.getBytes("x-windows-949"), "ksc5601"));
    Log.d("Encoding Check""x-windows-949 -> iso-8859-1: " + new String(str.getBytes("x-windows-949"), "iso-8859-1"));
catch(Exception e) {
    e.printStackTrace();
}



Logcat을 확인해 보면 'iso-8859-1 -> utf-8'이 정상적으로 한글을 표시했다.


그런데 위 코드 중 'utf-8 -> iso-8859-1'은 Logcat에 출력 되지 않는다. System.out.println()으로 해도 출력되지 않지만, 이 문자열을 기기에서 출력해 보면 깨진 한글로 표시는 된다. 이유는 알 수 없다.

1
    Log.d("Encoding Check""utf-8 -> iso-8859-1: " + new String(str.getBytes("utf-8"), "iso-8859-1"));



반응형
Posted by J-sean
: