* AndroidManifest.xml

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

* Listener 구현

final LocationListener gpsLocationListener = new LocationListener() {

    public void onLocationChanged(Location location) {
 
        String provider = location.getProvider();
        double longitude = location.getLongitude();
        double latitude = location.getLatitude();
        double altitude = location.getAltitude();
 
        txtResult.setText("위치정보 : " + provider + "\n" +
                "위도 : " + longitude + "\n" +
                "경도 : " + latitude + "\n" +
                "고도  : " + altitude);
 
    }
 
    public void onStatusChanged(String provider, int status, Bundle extras) {
    
    }
 
    public void onProviderEnabled(String provider) {
    
    }
 
    public void onProviderDisabled(String provider) {
    
    }
    
};

* LocationManager

final LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

* 위치 업데이트

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
        1000,
        1,
        gpsLocationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
        1000,
        1,
        gpsLocationListener);

* MainActivity.java

public class MainActivity extends AppCompatActivity {
 
    private Button button1;
    private TextView txtResult;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button1 = (Button)findViewById(R.id.button1);
        txtResult = (TextView)findViewById(R.id.txtResult);
 
        final LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
 
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ( Build.VERSION.SDK_INT >= 23 &&
                        ContextCompat.checkSelfPermission( getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) {
                    ActivityCompat.requestPermissions( MainActivity.this, new String[] {  android.Manifest.permission.ACCESS_FINE_LOCATION  },
                            0 );
                }
                else{
                    Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    String provider = location.getProvider();
                    double longitude = location.getLongitude();
                    double latitude = location.getLatitude();
                    double altitude = location.getAltitude();
 
                    txtResult.setText("위치정보 : " + provider + "\n" +
                            "위도 : " + longitude + "\n" +
                            "경도 : " + latitude + "\n" +
                            "고도  : " + altitude);
 
                    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                            1000,
                            1,
                            gpsLocationListener);
                    lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                            1000,
                            1,
                            gpsLocationListener);
                }
            }
        });
 
    }
    final LocationListener gpsLocationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
 
            String provider = location.getProvider();
            double longitude = location.getLongitude();
            double latitude = location.getLatitude();
            double altitude = location.getAltitude();
 
            txtResult.setText("위치정보 : " + provider + "\n" +
                    "위도 : " + longitude + "\n" +
                    "경도 : " + latitude + "\n" +
                    "고도  : " + altitude);
 
        }
 
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
 
        public void onProviderEnabled(String provider) {
        }
 
        public void onProviderDisabled(String provider) {
        }
    };
}
출처: https://bottlecok.tistory.com/54 [잡캐의 IT 꿀팁]
블로그 이미지

디츠

“말은 쉽지, 코드를 보여줘.” “Talk is cheap. Show me the code.” – 리누스 토르발스(Linus Torvalds)

,
LatLng northeastLatLng = map.getProjection().getVisibleRegion().latLngBounds.northeast; // 화면 좌측 상단 부분의 LatLng
LatLng southwestLatLng = map.getProjection().getVisibleRegion().latLngBounds.southwest; // 화면 우측 하단 부분의 LatLng
블로그 이미지

디츠

“말은 쉽지, 코드를 보여줘.” “Talk is cheap. Show me the code.” – 리누스 토르발스(Linus Torvalds)

,

* Gradle - Project

buildscript {
    repositories {
        google()   
    }
    dependencies {
        classpath 'com.google.gms:google-services:4.2.0'
    }
}

allprojects {
    repositories {
        google()       
    }
}

* Gradle - Module

dependencies {
    implementation 'com.google.firebase:firebase-core:17.0.1'
    implementation 'com.google.firebase:firebase-messaging:20.0.0'
}

apply plugin: 'com.google.gms.google-services'

* AndroidManifest.xml

<application
    <service android:name=".service.FirebaseMessaging">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
</application>

* FirebaseMessaging.java

public class FirebaseMessaging extends FirebaseMessagingService {

    @Override
    public void onNewToken(String token) {
        Log.d("@@", "Refreshed token: " + token);
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        if (remoteMessage.getNotification() != null) {
            Log.d("@@", "알림 메시지: " + remoteMessage.getNotification().getBody());
            String messageBody = remoteMessage.getNotification().getBody();
            String messageTitle = remoteMessage.getNotification().getTitle();
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
            String channelId = "Channel ID";
            Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            NotificationCompat.Builder notificationBuilder =
                    new NotificationCompat.Builder(this, channelId)
                            .setSmallIcon(R.mipmap.ic_launcher)
                            .setContentTitle(messageTitle)
                            .setContentText(messageBody)
                            .setAutoCancel(true)
                            .setSound(defaultSoundUri)
                            .setContentIntent(pendingIntent);
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                String channelName = "Channel Name";
                NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH);
                notificationManager.createNotificationChannel(channel);
            }
            notificationManager.notify(0, notificationBuilder.build());
        }
    }

}

* MainActivity.java

public class MainActivity extends AppCompatActivity {

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

        FragmentManager fragmentManager = getFragmentManager();
        MapFragment mapFragment = (MapFragment) fragmentManager.findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        FirebaseInstanceId.getInstance().getInstanceId()
                .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                    @Override
                    public void onComplete(@NonNull Task<InstanceIdResult> task) {
                        if (!task.isSuccessful()) {
                            Log.w("@@", "getInstanceId failed", task.getException());
                            return;
                        }

                        // String token = task.getResult().getToken();
                        // Log.d("FCM Log", "FCM 토큰: " + token);
                        // Toast.makeText(MainActivity.this, token, Toast.LENGTH_SHORT).show();
                    }
                });

    }
    
}

* 메시지 보내기

1. Firebase Console(https://console.firebase.google.com)

 

로그인 - Google 계정

하나의 계정으로 모든 Google 서비스를 Google 계정으로 로그인

accounts.google.com

2. 프로젝트 선택

3. 좌측 메뉴에서 Cloud Messaging

4. 우측의 Send your first message

5. 타이틀, 제목 입력 후 전송

블로그 이미지

디츠

“말은 쉽지, 코드를 보여줘.” “Talk is cheap. Show me the code.” – 리누스 토르발스(Linus Torvalds)

,
Geocoder geocoder = new Geocoder(this);
try {
    List<Address> r = geocoder.getFromLocationName("서울시청", 1);
    double lat = r.get(0).getLatitude();
    double lng = r.get(0).getLongitude();
    Log.d("@@", "위도 : " + lat + ", 경도 : " + lng);
} catch (Exception e) {
    Log.d("@@", "주소변환 실패");
}
블로그 이미지

디츠

“말은 쉽지, 코드를 보여줘.” “Talk is cheap. Show me the code.” – 리누스 토르발스(Linus Torvalds)

,

* AndroidManifest.xml

<application android:configChanges="orientation|keyboardHidden|screenSize" />

'android' 카테고리의 다른 글

FCM(Firebase Cloud Messaging) 설정하기  (0) 2020.03.04
Geocoder 주소 > 위도, 경도 변환  (0) 2020.03.02
YouTube API 플레이어  (0) 2020.02.19
YouTube 썸네일(Thumbnail)  (0) 2020.02.19
WebView 자바스크립트 실행하기  (0) 2020.02.17
블로그 이미지

디츠

“말은 쉽지, 코드를 보여줘.” “Talk is cheap. Show me the code.” – 리누스 토르발스(Linus Torvalds)

,

YouTube API 플레이어

android 2020. 2. 19. 15:31

* lib 폴더에 라이브러리 추가

YouTubeAndroidPlayerApi-1.2.2.zip
0.63MB

* activity_myplayer.xml

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

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.google.android.youtube.player.YouTubePlayerView
            android:id="@+id/youTubePlayerView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
	
    </LinearLayout>

</LinearLayout>

* MyPlayerActivity.java

public class MyPlayerActivity extends YouTubeBaseActivity {

    public static final String API_KEY = "API_KEY";

    YouTubePlayerView youTubePlayerView;
    YouTubePlayer.OnInitializedListener listener;

    public PlayerActivity() {

    }

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

        Intent intent = getIntent();
        final ArrayList<String> idList = (ArrayList<String>) intent.getSerializableExtra("idList");

        youTubePlayerView = findViewById(R.id.youTubePlayerView);
        listener = new YouTubePlayer.OnInitializedListener() {
            @Override
            public void onInitializationSuccess(YouTubePlayer.Provider provider, final YouTubePlayer youTubePlayer, boolean b) {
                youTubePlayer.loadVideo(VIDEO_ID);
            }

            @Override
            public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {

            }
        };

        youTubePlayerView.initialize(API_KEY, listener);
    }

}

'android' 카테고리의 다른 글

Geocoder 주소 > 위도, 경도 변환  (0) 2020.03.02
가로세로 전환시 새로고침 안되게 유지  (0) 2020.02.21
YouTube 썸네일(Thumbnail)  (0) 2020.02.19
WebView 자바스크립트 실행하기  (0) 2020.02.17
WebView 사용하기  (0) 2020.02.13
블로그 이미지

디츠

“말은 쉽지, 코드를 보여줘.” “Talk is cheap. Show me the code.” – 리누스 토르발스(Linus Torvalds)

,