반응형

Create a simple drawing app for Android.


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
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MyView(this));
    }
 
    public class MyView extends View {
        Paint paint = new Paint();
        boolean isDrawing = false;
        ArrayList<Float> coordinateList = new ArrayList<>(100);
        // Each ArrayList instance has a capacity. The capacity is the size of the array used to store
        // the elements in the list. It is always at least as large as the list size. As elements are
        //  added to an ArrayList, its capacity grows automatically. The details of the growth policy
        //  are not specified beyond the fact that adding an element has constant amortized time cost.
 
        MyView(Context context)
        {
            super(context);
            paint.setColor(Color.BLUE); // 0xff0000ff
            paint.setStrokeWidth(8);
        }
 
        @Override
        public void onDraw(Canvas canvas)
        {
            // ArrayList, Float[], float[]은 서로 직접 호환되지 않음.
            Float[] coordinateFloat = coordinateList.toArray(new Float[coordinateList.size()]);
            float[] coordinate = new float[coordinateFloat.length];
 
            for (int i = 0; i < coordinateFloat.length; i++)
            {
                coordinate[i] = coordinateFloat[i].floatValue();
            }
 
            // 특정 색으로 화면을 채우는 메서드
            // void drawRGB(int r, int g, int b)
            // void drawARGB(int a, int r, int g, int b)
            // void drawColor(int color)
            // void drawPaint(Paint paint)
            canvas.drawARGB(2552552550); // Yellow
            canvas.drawLines(coordinate, paint);
            // Draw a series of lines. Each line is taken from 4 consecutive values in the pts array.
            // Thus to draw 1 line, the array must contain at least 4 values. This is logically the
            // same as drawing the array as follows: drawLine(pts[0], pts[1], pts[2], pts[3]) followed
            // by drawLine(pts[4], pts[5], pts[6], pts[7]) and so on.
        }
 
        // drawLines()는 4개의 좌표를 이용해 1개의 직선을 그린다(x1, y1, x2, y2)
        // 1개의 직선을 그리고 다음 직선의 시작 좌표(x1, y1)에 이전 끝 좌표(x2, y2)가
        // 없다면 끊어진 선으로 그려지게 된다. 마우스를 뗄때는 다음 직선의 시작 좌표로
        // 넣어준 값 두 개(x1, y1)를 삭제 해야 한다.
        @Override
        public boolean onTouchEvent(MotionEvent event)
        {
            switch (event.getAction())
            {
                case MotionEvent.ACTION_DOWN:
                    coordinateList.add(event.getX());
                    coordinateList.add(event.getY());
                    isDrawing = true;
                    break;
 
                case MotionEvent.ACTION_MOVE:
                    if (isDrawing)  // 이 코드에서는 별 의미는 없는 if
                    {
                        coordinateList.add(event.getX());
                        coordinateList.add(event.getY());
 
                        coordinateList.add(event.getX());
                        coordinateList.add(event.getY());
                    }
 
                    invalidate();
                    break;
 
                case MotionEvent.ACTION_UP:
                    coordinateList.remove(coordinateList.size() -1);
                    coordinateList.remove(coordinateList.size() -1);
                    isDrawing = false;
                    break;
 
                default:
                    break;
            }
 
            return true;
        }
    }



Run the app and draw.



To simplify the code, you can also use Path. The result is the same.

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
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MyView(this));
    }
 
    public class MyView extends View {
        Paint paint = new Paint();
        boolean isDrawing = false;
        Path path = new Path();
 
        MyView(Context context)
        {
            super(context);
            paint.setColor(Color.BLUE); // 0xff0000ff
            paint.setStyle(Paint.Style.STROKE); // Paint.Style.FILL(기본값)로 하면 채워진 도형이 그려진다
            paint.setStrokeWidth(8);
        }
 
        @Override
        public void onDraw(Canvas canvas)
        {
            canvas.drawARGB(2552552550);
            canvas.drawPath(path, paint);
        }
 
        @Override
        public boolean onTouchEvent(MotionEvent event)
        {
            switch (event.getAction())
            {
                case MotionEvent.ACTION_DOWN:
                    path.moveTo(event.getX(), event.getY());
                    isDrawing = true;
                    break;
 
                case MotionEvent.ACTION_MOVE:
                    if (isDrawing)
                    {
                        path.lineTo(event.getX(), event.getY());
                        invalidate();
                    }
                    break;
 
                case MotionEvent.ACTION_UP:
                    isDrawing = false;
                    break;
 
                default:
                    break;
            }
 
            return true;
        }
    }



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

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
: