如果要使用Google API,一定要先到Google Developers Console中拿到API Key。
| 圖1.建立專案 |
| 圖2.啟用GCM API |
| 圖3.建立金鑰 |
| 圖4.取得API Key | 圖5.取得專案ID |
Gradle:
compile "com.google.android.gms:play-services:8.3.0"AndroidManifest.xml:
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission android:name="YOUR_PACKAGE_NAME.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="YOUR_PACKAGE_NAME.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.VIBRATE"/>
YOUR_PACKAGE_NAME:更改為您的專案名稱android.permission.VIBRATE:開起震動
<receiver
android:name="YOUR_PACKAGE_NAME.GcmBroadcastReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="YOUR_PACKAGE_NAME" />
</intent-filter>
</receiver>
<service android:name=".GcmIntentService" />
YOUR_PACKAGE_NAME:更改為您的專案名稱GcmIntentService:
public class GcmIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
public GcmIntentService() {
super("GcmIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
if (!extras.isEmpty()) {
try {
//分析GCM推送的JSON資料
JSONTokener jsonTokener = new JSONTokener(extras.toString().replaceAll("Bundle", ""));
JSONArray jsons = (JSONArray) jsonTokener.nextValue();
JSONObject jsonObject = (JSONObject)jsons.get(0);
//取得message屬性的內容
sendNotification(jsonObject.getString("message"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
private void sendNotification(String msg) {
//設定點選推播要啟動的Activity
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
//設定新通知
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
mBuilder.setSmallIcon(R.drawable.ic_launcher);
mBuilder.setTicker("new message");
mBuilder.setContentText(msg);
mBuilder.setContentTitle("Ocean's 通知");
mBuilder.setAutoCancel(true);
mBuilder.setContentIntent(contentIntent);
//顯示通知
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
GcmBroadcastReceiver:
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ComponentName comp = new ComponentName(context.getPackageName(), GcmIntentService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
MainActivity:public class MainActivity extends AppCompatActivity {
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
public static final String PROPERTY_REG_ID = "gcmtest-1152";
public static final String SENDER_ID = "219666876033";
private GoogleCloudMessaging gcm;
private String regid;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (checkPlayServices()) {
gcm = GoogleCloudMessaging.getInstance(this);
regid = getRegistrationId();
if (regid.length() == 0) {
registerInBackground();
} else {
Toast.makeText(MainActivity.this, "Already registered", Toast.LENGTH_SHORT).show();
Log.i("regid", regid);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//檢查是否支援GooglePlayServices
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
finish();
}
return false;
}
return true;
}
//取得推播的ID
private String getRegistrationId() {
final SharedPreferences prefs = getSharedPreferences(MainActivity.class.getSimpleName(), Context.MODE_PRIVATE);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
return "";
}
return registrationId;
}
//註冊推播
private void registerInBackground() {
new AsyncTask() {
@Override
protected Void doInBackground(Void... params) {
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(MainActivity.this);
}
regid = gcm.register(SENDER_ID);
storeRegistrationId(regid);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Toast.makeText(MainActivity.this, "Successful registration", Toast.LENGTH_SHORT).show();
Log.i("regid", regid);
}
}.execute(null, null, null);
}
//通知GCM推播ID使用
private void storeRegistrationId(String regId)
{
SharedPreferences prefs = getSharedPreferences(MainActivity.class.getSimpleName(), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.commit();
}
}
PROPERTY_REG_ID:儲存GCM註冊ID之Key。SENDER_ID:圖5所得到的專案ID。
※regid:接受訊息裝置的辨識Key。
測試推播server:
(來自知道原因問題就解決一半):http://emlscer.no-ip.info:8080/sample/Send.php
GOOGLE_API_KEY:你所註冊的金鑰(圖4)。
APP_REG_ID:你取得的regid。
Message:你欲傳送之訊息。
※中文無法推,PHP沒有對中文做編碼。
資料來源:
http://gnehcic.azurewebsites.net/android%E4%BD%BF%E7%94%A8google%E6%8E%A8%E6%92%AD%E6%9C%8D%E5%8B%99/ (知道原因問題就解決一半)
沒有留言:
張貼留言