Skip to content

Instantly share code, notes, and snippets.

@vvakame
Created July 1, 2012 23:11
Show Gist options
  • Save vvakame/3029979 to your computer and use it in GitHub Desktop.
Save vvakame/3029979 to your computer and use it in GitHub Desktop.
Google Cloud Messaging for Android で、サーバ側をAndroidにしてみた
// 参考 http://d.hatena.ne.jp/azukinohiroki/20120628/1340868610
package net.vvakame.gcmsample;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import com.google.android.gcm.GCMRegistrar;
public class MainActivity extends Activity {
static final String TAG = MainActivity.class.getSimpleName();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
GCMRegistrar.register(this, "335588306847");
} else {
Log.v(TAG, "Already registered");
}
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.permitAll().build());
findViewById(R.id.gcm).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
sendGCM("hoge");
} catch (ClientProtocolException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
}
private void sendGCM(final String message) throws ClientProtocolException,
IOException {
final String url = "https://android.googleapis.com/gcm/send";
final String registrationId = "ここに端末のregistrationID入れる";
final String apiKey = "こっちにAPI Key入れる";
HttpPost req = new HttpPost(url);
req.addHeader("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
req.addHeader("Authorization", "key=" + apiKey);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("registration_id", registrationId));
params.add(new BasicNameValuePair("collapse_key", "update"));
params.add(new BasicNameValuePair("data.message", message));
req.setEntity(new UrlEncodedFormEntity(params));
new DefaultHttpClient().execute(req);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment