2013-10-24 152 views
1

我在從GCM服務器獲取通知消息時遇到問題。當設備閒置或處於運行狀態但設備空閒10-15分鐘時,設備將正確獲取通知無法獲取通知,並且所有註冊的設備都無法從GCM服務器獲取通知。如何解決此問題?Android GCM不向設備發送通知消息

回答

1

通常,您的應用需要在睡眠時喚醒。

  1. 將這個到您的清單文件即可喚醒設備時收到消息

    <uses-permission android:name="android.permission.WAKE_LOCK" /> 
    
  2. 添加Java類名WakeLocker.java

    public abstract class WakeLocker { 
    private static PowerManager.WakeLock wakeLock; 
    
    public static void acquire(Context context) { 
        if (wakeLock != null) wakeLock.release(); 
    
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); 
        wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | 
         PowerManager.ACQUIRE_CAUSES_WAKEUP | 
         PowerManager.ON_AFTER_RELEASE, "WakeLock"); 
        wakeLock.acquire(); 
        } 
    
        public static void release() { 
         if (wakeLock != null) wakeLock.release(); wakeLock = null; 
        } 
    } 
    
  3. 調用上面的代碼中'private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver()'可能在你的MainActivity.java中

    private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() { 
        @Override 
        public void onReceive(Context context, Intent intent) { 
        String newMessage = intent.getExtras().getString(EXTRA_MESSAGE); 
        // Waking up mobile if it is sleeping 
        WakeLocker.acquire(getApplicationContext()); 
    
        /** 
        * Take appropriate action on this message 
        * depending upon your app requirement 
        * For now i am just displaying it on the screen 
        * */ 
    
        // Showing received message 
        lblMessage.append(newMessage + "\n");   
        Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show(); 
    
        // Releasing wake lock 
        WakeLocker.release(); 
    } 
    }; 
    

    感謝This source

    希望這有助於

相關問題