반응형

Handling multiple buttons with one listener.

한 개의 리스너로 여러개의 버튼을 처리할 수 있다.


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
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        findViewById(R.id.button1).setOnClickListener(myClick);
        findViewById(R.id.button2).setOnClickListener(myClick);
        findViewById(R.id.button3).setOnClickListener(myClick);
    }
 
    View.OnClickListener myClick = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.button1:
                    Toast.makeText(getApplicationContext(), "Button 1", Toast.LENGTH_SHORT).show();
                    break;
 
                case R.id.button2:
                    Toast.makeText(getApplicationContext(), "Button 2", Toast.LENGTH_SHORT).show();
                    break;
 
                case R.id.button3:
                    Toast.makeText(getApplicationContext(), "Button 3", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
}



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

A notification is a message that Android displays outside your app's UI to provide the user with reminders, communication from other people, or other timely information from your app. Users can tap the notification to open your app or take an action directly from the notification.


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
public class MainActivity extends AppCompatActivity {
 
    NotificationManager notificationManager;
 
    private static String CHANNEL1_ID = "Channel1_ID";
    private static String CHANNEL1_NAME = "Channel1_NAME";
 
    private static String CHANNEL2_ID = "Channel2_ID";
    private static String CHANNEL2_NAME = "Channel2_NAME";
 
    private final int RequestCode = 101;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShowNotification1();
            }
        });
 
        Button button2 = findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShowNotification2();
            }
        });
    }
 
    public void ShowNotification1() {
        notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = null;
 
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (notificationManager.getNotificationChannel(CHANNEL1_ID) == null) {
                notificationManager.createNotificationChannel(new NotificationChannel(CHANNEL1_ID, CHANNEL1_NAME, NotificationManager.IMPORTANCE_DEFAULT));
                builder = new NotificationCompat.Builder(this, CHANNEL1_ID);
            } else {
                builder = new NotificationCompat.Builder(this, CHANNEL1_ID);
            }
        } else {
            builder = new NotificationCompat.Builder(this);
            // This package is part of the Android support library which is no longer maintained.
        }
 
        builder.setContentTitle("Simple notification");
        builder.setContentText("Message for simple notification");
        builder.setSmallIcon(android.R.drawable.ic_menu_view);
 
        Notification notification = builder.build();
 
        notificationManager.notify(1, notification);
        // Post a notification to be shown in the status bar. If a notification with the same id has already been posted by your application and has not yet
        // been canceled, it will be replaced by the updated information.
        // - Parameters
        // id: An identifier for this notification unique within your application.
        // notification: A Notification object describing what to show the user. Must not be null.
    }
 
    public void ShowNotification2() {
        notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = null;
 
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (notificationManager.getNotificationChannel(CHANNEL2_ID) == null) {
                notificationManager.createNotificationChannel(new NotificationChannel(CHANNEL2_ID, CHANNEL2_NAME, NotificationManager.IMPORTANCE_DEFAULT));
                builder = new NotificationCompat.Builder(this, CHANNEL2_ID);
            } else {
                builder = new NotificationCompat.Builder(this, CHANNEL2_ID);
            }
        } else {
            builder = new NotificationCompat.Builder(this);
        }
 
        Uri uri = Uri.parse("https://s-engineer.tistory.com");
        Intent intent = new Intent(ACTION_VIEW, uri);
        // ACTION_VIEW: Display the data to the user. This is the most common action performed on data -- it is the generic action you can use on a piece of
        // data to get the most reasonable thing to occur. For example, when used on a contacts entry it will view the entry; when used on a mailto: URI it
        // will bring up a compose window filled with the information supplied by the URI; when used with a tel: URI it will invoke the dialer.
        PendingIntent pendingIntent = PendingIntent.getActivity(this, RequestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
 
        builder.setContentTitle("Notification with PendingIntent");
        builder.setContentText("Message for notification with PendingIntent");
        builder.setSmallIcon(android.R.drawable.ic_menu_view);
        builder.setAutoCancel(true);
        // Setting this flag will make it so the notification is automatically canceled when the user clicks it in the panel.
        builder.setContentIntent(pendingIntent);
        // Supply a PendingIntent to send when the notification is clicked.
 
        Notification notification = builder.build();
 
        notificationManager.notify(2, notification);
    }
}




Run the app and click "SIMPLE NOTIFICATION" button.


A simple notification appears as an icon in the status bar. Users can swipe down on the status bar to open the notification drawer, where they can view more details and take actions with the notification.


Go back to the app and click "NOTIFICATION WITH PENDINGINTENT" button. Then click the notification again.


It will take you to a great blog.


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

Add a vibration and a ringtone notification to your android application.


<AndroidManifest.xml>

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



<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
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Vibrator vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
 
                if (Build.VERSION.SDK_INT >= 26) {
                    vibrator.vibrate(VibrationEffect.createOneShot(100010));
                    // - public static VibrationEffect createOneShot (long milliseconds, int amplitude)
                    // Create a one shot vibration. One shot vibrations will vibrate constantly for the specified period of time at the specified amplitude, and then stop.
                    // milliseconds long: The number of milliseconds to vibrate. This must be a positive number.
                    // amplitude int: The strength of the vibration. This must be a value between 1 and 255, or DEFAULT_AMPLITUDE.
                } else {
                    vibrator.vibrate(1000);
                    // Vibrate constantly for the specified period of time.
                    // This method was deprecated in API level 26. Use vibrate(android.os.VibrationEffect) instead.
                }
            }
        });
 
        Button button2 = findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                // - public static Uri getDefaultUri (int type)
                // Returns the Uri for the default ringtone of a particular type. Rather than returning the actual ringtone's sound Uri, this will return the symbolic Uri
                // which will resolved to the actual sound when played.
                // - public static final int TYPE_NOTIFICATION
                // Type that refers to sounds that are used for notifications.
                // Constant Value: 2 (0x00000002)
 
                Ringtone ringtone = RingtoneManager.getRingtone(getApplicationContext(), uri);
                // Returns a Ringtone for a given sound URI.
                // If the given URI cannot be opened for any reason, this method will attempt to fallback on another sound. If it cannot find any, it will return null.
 
                ringtone.play();
                // Plays the ringtone.
            }
        });
 
        Button button3 = findViewById(R.id.button3);
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.media);
                // Convenience method to create a MediaPlayer for a given resource id. On success, prepare() will already have been called and must not be called again.
                // When done with the MediaPlayer, you should call release(), to free the resources. If not released, too many MediaPlayer instances will result in an exception.
 
                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        mp.release();
                        // Releases resources associated with this MediaPlayer object. It is considered good practice to call this method when you're done using the MediaPlayer.
                    }
                });
                // Interface definition for a callback to be invoked when playback of a media source has completed.
 
                mediaPlayer.start();
                // Starts or resumes playback. If playback had previously been paused, playback will continue from where it was paused. If playback had been stopped, or never
                // started before, playback will start at the beginning.
            }
        });
    }
}




Add a media file for MediaPlayer.


Run the app and click the buttons.


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

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
:
반응형

You can stream an audio file with MediaPlayer.


<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
79
80
81
82
83
public class MainActivity extends AppCompatActivity {
 
    MediaPlayer mediaPlayer;
    int position = 0;
    boolean isPaused = false;   // To prevent false resume.
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // Play
        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                if (mediaPlayer != null) {
                    mediaPlayer.release();
                }
                try {
                    mediaPlayer = new MediaPlayer();
                    mediaPlayer.setDataSource("http://nexoft.tk/download/Davich.mp3");  // or your audio file url.
                    mediaPlayer.prepare();
                    mediaPlayer.start();
                    isPaused = false;
                } catch (Exception e)
                {
                    e.printStackTrace();
                }
                Toast.makeText(getApplicationContext(), "Media player started", Toast.LENGTH_SHORT).show();
            }
        });
 
        // Stop
        Button button2 = findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayer != null) {
                    mediaPlayer.stop();
                    isPaused = false;
                    Toast.makeText(getApplicationContext(), "Media player stopped", Toast.LENGTH_SHORT).show();
                }
            }
        });
 
        // Pause
        Button button3 = findViewById(R.id.button3);
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    position = mediaPlayer.getCurrentPosition();
                    mediaPlayer.pause();
                    isPaused = true;
                    Toast.makeText(getApplicationContext(), "Media player paused at " + position / 1000 + " sec", Toast.LENGTH_SHORT).show();
                }
            }
        });
 
        // Resume
        Button button4 = findViewById(R.id.button4);
        button4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayer != null && !mediaPlayer.isPlaying() && isPaused == true) {
                    mediaPlayer.start();
                    mediaPlayer.seekTo(position);
                    isPaused = false;
                    Toast.makeText(getApplicationContext(), "Media player resumed at " + position / 1000 + " sec", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
 
        if (mediaPlayer != null) {
            mediaPlayer.release();
        }
    }
}




Run the app and start the audio file.


반응형
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
: