Mais conteúdo relacionado
Semelhante a AndroidーiOS開発比較〜iOSエンジニアから見たAndroidのアレコレ〜 (20)
Mais de Takaaki Tanaka (7)
AndroidーiOS開発比較〜iOSエンジニアから見たAndroidのアレコレ〜
- 4. 弊社のよくある要件
• Android / iOS並行開発
• 同時リリース
• iOS先行リリースという案件もあり
• Appleの審査期間を踏まえてiOSを前倒しで開発するというこ
ともあり
4Ⓒ Classmethod, Inc.
- 13. 対応OSバージョンについて
• iOS
• Xcode のバージョンアップ対応には注意
• XcodeのバージョンによってサポートされるSwiftのバー
ジョンが違う
• Xcode 6.0 -> Swift 1.0
• Xcode 6.1 -> Swift 1.1
• Xcode 6.3 -> Swift 1.2
• Xcode 7.0 -> Swift 2.0
• Xcode 7.2 -> Swift 2.1
• Xcode 7.3 -> Swift 2.2
13Ⓒ Classmethod, Inc.
- 41. AWS側の作業
41Ⓒ Classmethod, Inc.
• Amazon Cognito で Identity pool を作成
• Amazon SNS で Google Android の Platform
を作成
• Amazon SNS で Apple iOS Dev の Platformを
作成
• Amazon SNS で Topicを作成
- 42. 開発環境
• Android
• Android Studio 2.0
• Java
• iOS
• Xcode 7.3
• CocoaPods or Carthage
• Swift 2.2
42Ⓒ Classmethod, Inc.
- 48. ライブラリのインポート
48Ⓒ Classmethod, Inc.
apply plugin: 'com.google.gms.google-services'
android {
…
}
dependencies {
…
compile "com.google.android.gms:play-services:8.3.0"
…
}
• build.gradleを編集
• GCM用のライブラリを適用する
- 50. パーミッションの設定
50Ⓒ Classmethod, Inc.
<?xml version="1.0" encoding="utf-8"?>
<manifest
package="jp.co.kongmings.android.app"
xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="com.google.android.c2dm.permission.REGISTER" />
</manifest>
• AndroidManifest.xmlを編集
• パーミッションの設定
- 52. Push受信処理の実装
52Ⓒ Classmethod, Inc.
public class MsgGcmListenerService extends GcmListenerService {
static final String TAG = MsgGcmListenerService.class.getSimpleName();
@Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
sendNotification(message);
sendBroadcast(message);
}
void sendNotification(String message) {
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);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Message received!")
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, notificationBuilder.build());
}
void sendBroadcast(String message) {
Intent broadcastIntent = new Intent();
broadcastIntent.putExtra("message", message);
broadcastIntent.setAction("MESSAGE_RECEIVED");
getBaseContext().sendBroadcast(broadcastIntent);
}
}
• GCMからメッセージが返ってきた時の処理
- 53. Push受信処理の実装
53Ⓒ Classmethod, Inc.
…
void sendNotification(String message) {
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);
Uri defaultSoundUri =
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new
NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Message received!")
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager manager =
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, notificationBuilder.build());
}
...
• 通知センターに表示させる
- 54. Push受信処理の実装
54Ⓒ Classmethod, Inc.
public class MsgGcmListenerService extends GcmListenerService {
…
void sendBroadcast(String message) {
Intent broadcastIntent = new Intent();
broadcastIntent.putExtra("message", message);
broadcastIntent.setAction("MESSAGE_RECEIVED");
getBaseContext().sendBroadcast(broadcastIntent);
}
}
• メッセージを受信したことを通知する
- 55. Push受信処理の実装
55Ⓒ Classmethod, Inc.
public class RegistrationIntentService extends IntentService {
public RegistrationIntentService() {
super("RegistrationIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
try {
InstanceID instanceID = InstanceID.getInstance(this);
String token = instanceID.getToken(
getString(R.string.gcm_defaultSenderId),
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
Prefs.put("token", token);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
• トークン取得処理にてトークンを保持しておく
- 56. Amazon Cognito IDの取得
56Ⓒ Classmethod, Inc.
void getCognitoId() {
new Thread(new Runnable() {
@Override
public void run() {
CognitoCachingCredentialsProvider provider =
new CognitoCachingCredentialsProvider(
self,
COGNITO_IDENTITY_POOL_ID,
AWS_REGION
);
final String identityId = provider.getIdentityId();
Prefs.put("cognito_id", identityId);
}
}).start();
}
• CognitoCachingCredentialsProviderに
Cognito Identity Pool IDを指定する
- 57. Amazon SNSへトークンの送信
57Ⓒ Classmethod, Inc.
void sendToken() {
AmazonSNSClient snsClient = new AmazonSNSClient(mProvider);
snsClient.setRegion(Region.getRegion(AWS_REGION));
CreatePlatformEndpointRequest createRequest = new CreatePlatformEndpointRequest();
createRequest.setPlatformApplicationArn(AWS_SNS_APPLICATION_ARN);
String token = Prefs.get("token");
createRequest.setToken(token);
CreatePlatformEndpointResult platformEndpoint =
snsClient.createPlatformEndpoint(createRequest);
String endpointArn = platformEndpoint.getEndpointArn();
snsClient.subscribe(AWS_SNS_SUBSCRIBE_TOPIC_ARN, "application", endpointArn);
}
• 指定したTopicをSuscribeする
- 58. 受信時の処理の実装
58Ⓒ Classmethod, Inc.
private MessageBroadcastReceiver mReceiver;
public class MessageBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
String message = bundle.getString("message");
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
…
mReceiver = new MessageBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("MESSAGE_RECEIVED");
registerReceiver(mReceiver, intentFilter);
}
- 68. Amazon Cognito IDの取得
68Ⓒ Classmethod, Inc.
func application(
application: UIApplication, didFinishLaunchingWithOptions
launchOptions: [NSObject: AnyObject]?) -> Bool {
let credentialsProvider = AWSCognitoCredentialsProvider(
regionType: AWSRegionType.APNortheast1,
identityPoolId: CognitoIdentityPoolId)
let defaultServiceConfiguration = AWSServiceConfiguration(
region: AWSRegionType.APNortheast1,
credentialsProvider: credentialsProvider)
AWSServiceManager.defaultServiceManager().defaultServiceConfiguration =
defaultServiceConfiguration
self.registerForRemoteNotifications()
return true
}
• AWSServiceManagerの設定を実施
• CognitoIdentityPoolIdはAWSで作成したものを指定する
- 69. Amazon SNSへトークンの送信
69Ⓒ Classmethod, Inc.
func application(
application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken
deviceToken: NSData) {
let deviceTokenString = "(deviceToken)"
.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString:"<>"))
.stringByReplacingOccurrencesOfString(" ", withString: "")
…
}
• トークン取得時に呼ばれるメソッドからトークンを取
得する
- 70. Amazon SNSへトークンの送信
70Ⓒ Classmethod, Inc.
…
let sns = AWSSNS.defaultSNS()
let request = AWSSNSCreatePlatformEndpointInput()
request.token = deviceTokenString
request.platformApplicationArn = AWSSNSApplicationArn
sns.createPlatformEndpoint(request).continueWithExecutor(
AWSExecutor.mainThreadExecutor(), withBlock: { (task: AWSTask!) -> AnyObject! in
if task.error != nil {
print("Error: (task.error)")
} else {
let createEndpointResponse = task.result as! AWSSNSCreateEndpointResponse
let subscribeRequest = AWSSNSSubscribeInput()
subscribeRequest.topicArn = self.AWSSNSSubscribeTopicArn
subscribeRequest.endpoint = createEndpointResponse.endpointArn
subscribeRequest.protocols = "Application"
sns.subscribe(subscribeRequest)
}
return nil
})
}
• 指定したTopicをSuscribeする
- 71. 受信時の処理
71Ⓒ Classmethod, Inc.
func application(
application: UIApplication,
didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
if application.applicationState == .Active {
if let aps = userInfo["aps"] {
if let alert = aps["alert"] {
let alertController = UIAlertController(
title: nil, message: alert, preferredStyle: .Alert)
alertController.addAction(
UIAlertAction(
title: "OK", style: .Default, handler: nil))
self.window?.rootViewController?.presentViewController(
alertController, animated: true, completion: nil)
}
}
}
}
• Pushを受信した時の処理を記載する
- 72. AWS側の作業
72Ⓒ Classmethod, Inc.
• Amazon Cognito で Identity pool を作成
• Amazon SNS で Google Android の Platform
を作成
• Amazon SNS で Apple iOS Dev の Platformを
作成
• Amazon SNS で Topicを作成
- 73. Amazon Cognito で Identity pool を作成
73Ⓒ Classmethod, Inc.
http://aws.amazon.com/jp/cognito/
- 75. Amazon SNS で Google Android の Platformを作成
75Ⓒ Classmethod, Inc.
https://aws.amazon.com/jp/sns/
- 76. Amazon SNS で Apple iOS Dev の Platformを作成
76Ⓒ Classmethod, Inc.
https://aws.amazon.com/jp/sns/
- 77. Amazon SNS で Topicを作成
77Ⓒ Classmethod, Inc.
https://aws.amazon.com/jp/sns/