Возможный дубликат:
Зарегистрируйте приложение Android с C2DM
так что я искал все и читал все, что мог, чтобы проверить, как использовать C2DM с моим супер-крутым чат-приложением.
Я видел, что есть все, что должен знать мой серверный парень, но я ничего не понял.
В процессе регистрации должен быть включен senderId, который в основном представляет собой идентификатор Google, который передается на сервер Google в качестве приложения (или пользователя), использующего приложение, и это означает, что вы являетесь push-клиентом.
Мой вопрос: должен ли я запрашивать у пользователя диалог регистрации? это кажется ужасным, что делать с моими пользователями, поскольку приложение уже использует подключение к Facebook и вызывает слишком много из них, которые являются враждебными для пользователей и наверняка заставят их удалить приложение.
что такое процесс одного приложения, регистрирующегося для C2DM? и как я могу использовать уже существующий токен аутентификации, который использует Google Play?
public void register(View view) {
Intent intent = new Intent("com.google.android.c2dm.intent.REGISTER");
intent.putExtra("app",PendingIntent.getBroadcast(this, 0, new Intent(), 0));
intent.putExtra("sender", "[email protected]"); //WHICH EMAIL?
startService(intent);
}
является ли электронная почта, используемая в 4-й строке адресом владельца устройства или электронной почтой службы?
Если мы говорим о пользователе, есть ли способ получить это без другого диалога проверки подлинности? У меня уже есть вход в Facebook, и я не хочу причинять пользователю дискомфорт.
см. статью vogella, очень краткое руководство по внедрению для C2DM.
http://www.vogella.com/articles/AndroidCloudToDeviceMessaging/article.html
Все, что упоминается там, а также код, я лично реализую его код, и это работает нормально.
Сначала вам нужно зарегистрироваться с помощью google C2DM
Во-вторых, получите токен Auth для вашего приложения C2DM
function(){
// Create the post data
// Requires a field with the email and the password
StringBuilder builder = new StringBuilder();
builder.append("Email=").append(email);
builder.append("&Passwd=").append(password);
builder.append("&accountType=GOOGLE");
builder.append("&source=MyLittleExample");
builder.append("&service=ac2dm");
// Setup the Http Post
byte[] data = builder.toString().getBytes();
URL url = new URL("https://www.google.com/accounts/ClientLogin");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
con.setRequestProperty("Content-Length", Integer.toString(data.length));
// Issue the HTTP POST request
OutputStream output = con.getOutputStream();
output.write(data);
output.close();
// Read the response
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
String auth_key = null;
while ((line = reader.readLine()) != null) {
if (line.startsWith("Auth=")) {
auth_key = line.substring(5);
}
}
// Finally get the authentication token
// To something useful with it
return auth_key;
}
Теперь вам нужно зарегистрировать мобильное устройство клиента на C2DM, чтобы получать обновления
public void register(View view) {
Intent intent = new Intent("com.google.android.c2dm.intent.REGISTER");
intent.putExtra("app",PendingIntent.getBroadcast(this, 0, new Intent(), 0));
intent.putExtra("sender", "[email protected]");
startService(intent);
}
Служба будет асинхронно регистрироваться в Google и отправит намерение " com.google.android.c2dm.intent.REGISTRATION " при успешной регистрации. Вашему заявлению необходимо зарегистрировать широковещательный приемник для этого намерения. Это также требует использования разрешения на основе вашего пакета, поскольку система Android проверяет это внутренне.
<receiver android:name=".C2DMMessageReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE"></action>
<category android:name="de.vogella.android.c2dm.simpleclient" />
</intent-filter>
</receiver>
//
public class C2DMRegistrationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.w("C2DM", "Registration Receiver called");
if ("com.google.android.c2dm.intent.REGISTRATION".equals(action)) {
Log.w("C2DM", "Received registration ID");
final String registrationId = intent
.getStringExtra("registration_id");
String error = intent.getStringExtra("error");
Log.d("C2DM", "dmControl: registrationId = " + registrationId
+ ", error = " + error);
// Send and store this in your application server(unique for each device)
}
}
}
Теперь вы можете отправлять сообщения C2DM через свой сервер
private final static String AUTH = "authentication";
private static final String UPDATE_CLIENT_AUTH = "Update-Client-Auth";
public static final String PARAM_REGISTRATION_ID = "registration_id";
public static final String PARAM_DELAY_WHILE_IDLE = "delay_while_idle";
public static final String PARAM_COLLAPSE_KEY = "collapse_key";
private static final String UTF8 = "UTF-8";
public static int sendMessage(String auth_token, String registrationId,
String message) throws IOException {
StringBuilder postDataBuilder = new StringBuilder();
postDataBuilder.append(PARAM_REGISTRATION_ID).append("=")
.append(registrationId);
postDataBuilder.append("&").append(PARAM_COLLAPSE_KEY).append("=")
.append("0");
postDataBuilder.append("&").append("data.payload").append("=")
.append(URLEncoder.encode(message, UTF8));
byte[] postData = postDataBuilder.toString().getBytes(UTF8);
// Hit the dm URL.
URL url = new URL("https://android.clients.google.com/c2dm/send");
HttpsURLConnection
.setDefaultHostnameVerifier(new CustomizedHostnameVerifier());
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestProperty("Content-Length",
Integer.toString(postData.length));
conn.setRequestProperty("Authorization", "GoogleLogin auth="
+ auth_token);
OutputStream out = conn.getOutputStream();
out.write(postData);
out.close();
int responseCode = conn.getResponseCode();
return responseCode;
}