在看到来自谷歌的关于performance patterns video的视频后,我决定实现google Cloud Messaging。但是当我在Android上实现GCM时,我发现GCM使用了一些权限,其中之一就是"wakelock“。但正如我们所知,这个权限“等同于”电池消耗。
所以我的问题是,我们如何处理这个问题?Lib GCM为我们做这件事??使用pull通知比使用pull更好?
谢谢
发布于 2015-10-15 05:29:54
你不需要这么做。谷歌提供了一项服务,可以为你处理所有事情。如下所示:
public class GcmListenerService extends com.google.android.gms.gcm.GcmListenerService {
private static final String TAG = "GcmListenerService";
/**
* Called when message is received.
*
* @param from SenderID of the sender.
* @param data Data bundle containing message data as key/value pairs.
* For Set of keys use data.keySet().
*/
// [START receive_message]
@Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
Log.d(TAG, "From: " + from);
Log.d(TAG, "Message: " + message);
if (from.startsWith("/topics/")) {
// message received from some topic.
} else {
// normal downstream message.
}
// [START_EXCLUDE]
/**
* Production applications would usually process the message here.
* Eg: - Syncing with server.
* - Store message in local database.
* - Update UI.
*/
/**
* In some cases it may be useful to show a notification indicating to the user
* that a message was received.
*/
sendNotification(message);
// [END_EXCLUDE]
}
// [END receive_message]
/**
* Create and show a simple notification containing the received GCM message.
*
* @param message GCM message received.
*/
private void sendNotification(String message) {
Intent intent = new Intent(this, TabAllItemsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, Resources.GCM_NOTIFICATION_REQUEST_CODE, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_notification)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.icon_app))
.setContentTitle("Message from Faroque")
.setContentText(message)
.setColor(R.color.orange_dark)//setting the brand color
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);//This intent will be executed when user tap on it
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(Resources.GCM_NOTIFICATION_ID, notificationBuilder.build());
}}
Here是一个教程,如果你愿意,你可以查看。谢谢
发布于 2015-10-16 00:06:27
定义wakelock权限本身不会导致电池耗尽。误用wakelock会造成这种情况。GcmListenerService为您管理唤醒锁,这也是为什么使用GcmListenerService是一个好主意的原因之一,因为您不必自己管理唤醒锁(这不是微不足道的)。
https://stackoverflow.com/questions/33135376
复制相似问题