2014-01-21 57 views
0

我只是想實現GCM在Android中,我geting推通知很好,但是,當我點擊通知區域上的通知問題時,它不會在TextView或Toast中顯示消息。點擊通知區域沒有顯示消息在活動

我的活動課是這樣的。

package com.androidhive.pushnotifications;

import static com.androidhive.pushnotifications.CommonUtilities.DISPLAY_MESSAGE_ACTION; 
import static com.androidhive.pushnotifications.CommonUtilities.EXTRA_MESSAGE; 
import static com.androidhive.pushnotifications.CommonUtilities.SENDER_ID; 
import android.app.Activity; 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.widget.TextView; 
import android.widget.Toast; 

import com.google.android.gcm.GCMRegistrar; 

public class MainActivity extends Activity { 
// label to display gcm messages 
TextView lblMessage; 

// Asyntask 
AsyncTask<Void, Void, Void> mRegisterTask; 

// Alert dialog manager 
AlertDialogManager alert = new AlertDialogManager(); 

// Connection detector 
ConnectionDetector cd; 

public static String name; 
public static String email; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.xyz); 

    cd = new ConnectionDetector(getApplicationContext()); 

    // Check if Internet present 
    if (!cd.isConnectingToInternet()) { 
     // Internet Connection is not present 
     alert.showAlertDialog(MainActivity.this, 
       "Internet Connection Error", 
       "Please connect to working Internet connection", false); 
     // stop executing code by return 
     return; 
    } 

    // Getting name, email from intent 

    Intent i = getIntent(); 
    /*Bundle b = getIntent().getExtras(); 
    String message = b.getString("message"); 
    if(message != null) 
    { 
     Log.d(message, "Message Value"); 
     Toast.makeText(this, "Message is " + message, Toast.LENGTH_LONG); 
    }*/ 
    name = i.getStringExtra("name"); 
    email = i.getStringExtra("email");  
    //email = " "; 
    // Make sure the device has the proper dependencies. 
    GCMRegistrar.checkDevice(this); 

    // Make sure the manifest was properly set - comment out this line 
    // while developing the app, then uncomment it when it's ready. 
    GCMRegistrar.checkManifest(this); 

    lblMessage = (TextView) findViewById(R.id.lblMessage); 

    registerReceiver(mHandleMessageReceiver, new IntentFilter(
      DISPLAY_MESSAGE_ACTION)); 

    // Get GCM registration id 
    final String regId = GCMRegistrar.getRegistrationId(this); 

    // Check if regid already presents 
    if (regId.equals("")) { 
     // Registration is not present, register now with GCM   
     GCMRegistrar.register(this, SENDER_ID); 
    } else { 
     // Device is already registered on GCM 
     if (GCMRegistrar.isRegisteredOnServer(this)) { 
      // Skips registration.    
      Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG).show(); 
     } else { 
      // Try to register again, but not in the UI thread. 
      // It's also necessary to cancel the thread onDestroy(), 
      // hence the use of AsyncTask instead of a raw thread. 
      final Context context = this; 
      mRegisterTask = new AsyncTask<Void, Void, Void>() { 

       @Override 
       protected Void doInBackground(Void... params) { 
        // Register on our server 
        // On server creates a new user 
        ServerUtilities.register(context, name, email, regId); 
        return null; 
       } 

       @Override 
       protected void onPostExecute(Void result) { 
        mRegisterTask = null; 
       } 

      }; 
      mRegisterTask.execute(null, null, null); 
     } 
    } 
}  

/** 
* Receiving push messages 
* */ 
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(); 
    } 
}; 

@Override 
protected void onDestroy() { 
    if (mRegisterTask != null) { 
     mRegisterTask.cancel(true); 
    } 
    try { 
     unregisterReceiver(mHandleMessageReceiver); 
     GCMRegistrar.onDestroy(this); 
    } catch (Exception e) { 
     Log.e("UnRegister Receiver Error", "> " + e.getMessage()); 
    } 
    super.onDestroy(); 
} 

}

我GCMIntentService類是

package com.androidhive.pushnotifications; 

import android.app.Notification; 
import android.app.NotificationManager; 
import android.app.PendingIntent; 
import android.content.Context; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.os.Bundle; 
import android.support.v4.app.NotificationCompat; 
import android.support.v4.app.TaskStackBuilder; 
import android.util.Log; 

import com.google.android.gcm.GCMBaseIntentService; 

import static com.androidhive.pushnotifications.CommonUtilities.SENDER_ID; 
import static com.androidhive.pushnotifications.CommonUtilities.displayMessage; 

public class GCMIntentService extends GCMBaseIntentService { 

private static final String TAG = "GCMIntentService"; 

public GCMIntentService() { 
    super(SENDER_ID); 
} 

/** 
* Method called on device registered 
**/ 
@Override 
protected void onRegistered(Context context, String registrationId) { 
    Log.i(TAG, "Device registered: regId = " + registrationId); 
    displayMessage(context, "Your device registred with GCM"); 
    Log.d("NAME", MainActivity.name); 
    ServerUtilities.register(context, MainActivity.name, MainActivity.email, registrationId); 
} 

/** 
* Method called on device un registred 
* */ 
@Override 
protected void onUnregistered(Context context, String registrationId) { 
    Log.i(TAG, "Device unregistered"); 
    displayMessage(context, getString(R.string.gcm_unregistered)); 
    ServerUtilities.unregister(context, registrationId); 
} 

/** 
* Method called on Receiving a new message 
* */ 


@Override 
protected void onMessage(Context context, Intent intent) { 
    Log.i(TAG, "Received message"); 
    String message = intent.getExtras().getString("price"); 
    Log.d("GCMIntentService", "here"); 
    displayMessage(context, message); 
    // notifies user 
    generateNotification(context, message); 
} 

/** 
* Method called on receiving a deleted message 
* */ 
@Override 
protected void onDeletedMessages(Context context, int total) { 
    Log.i(TAG, "Received deleted messages notification"); 
    String message = getString(R.string.gcm_deleted, total); 
    displayMessage(context, message); 
    // notifies user 
    generateNotification(context, message); 
} 

/** 
* Method called on Error 
* */ 
@Override 
public void onError(Context context, String errorId) { 
    Log.i(TAG, "Received error: " + errorId); 
    displayMessage(context, getString(R.string.gcm_error, errorId)); 
} 

@Override 
protected boolean onRecoverableError(Context context, String errorId) { 
    // log message 
    Log.i(TAG, "Received recoverable error: " + errorId); 
    displayMessage(context, getString(R.string.gcm_recoverable_error, 
      errorId)); 
    return super.onRecoverableError(context, errorId); 
} 

/** 
* Issues a notification to inform the user that server has sent a message. 
*/ 
private static void generateNotification(Context context, String message) { 

    int icon = R.drawable.ic_launcher; 
    long when = System.currentTimeMillis(); 
    NotificationManager notificationManager = (NotificationManager) 
      context.getSystemService(Context.NOTIFICATION_SERVICE); 
    Notification notification = new Notification(icon, message, when); 

    String title = context.getString(R.string.app_name); 

    Intent notificationIntent = new Intent(context, MainActivity.class); 
    // set intent so it does not start a new activity 
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | 
      Intent.FLAG_ACTIVITY_SINGLE_TOP); 
    PendingIntent intent = 
      PendingIntent.getActivity(context, 0, notificationIntent, 0); 
    notification.setLatestEventInfo(context, title, message, intent); 
    notification.flags |= Notification.FLAG_AUTO_CANCEL; 

    // Play default notification sound 
    notification.defaults |= Notification.DEFAULT_SOUND; 

    // Vibrate if vibrate is enabled 
    notification.defaults |= Notification.DEFAULT_VIBRATE; 
    notificationManager.notify(0, notification);  

} 

}

+0

爲什麼不創建一小段代碼來嘗試使其工作。如果那小部分代碼不起作用,那麼發佈一小段代碼,就可以完成整個項目。 –

+0

我該怎麼辦?請建議我嘗試了來自http://stackoverflow.com/questions/20743998/clicking-on-notification-is-not-starting-intended-activity?rq=1的user818455的建議,但無法使其工作。請幫幫我。 – Saty

回答

0

爲什麼不將數據存儲在數據庫中,並在以後檢索它,當你打開你的mainActivity或傳遞數據使用Intent來執行mainActivity。

//編輯這是當您收到消息而不是當你點擊它,點擊東西generateNotification功能工作,通過「信息」與你的意圖,並與意圖

@Override 
    protected void onMessage(Context context, Intent intent) { 
     String message = getString(R.string.gcm_message); 
     displayMessage(context, message); 
     DatabaseHelper db = new DatabaseHelper(context); 
     db.insertMsg(message); 
     // notifies user 
     generateNotification(context, message); 
    } 
接收數據會發生什麼
+0

我正在做同樣的,如果你看看我調用的代碼generateNotification(context,message);從onMessage,但是當它創建並打開MainActivity它顯示空消息。 – Saty

+0

請檢查編輯 –

+0

當我點擊它時,哪個類被調用的方法?我怎麼能夠得到這個消息。 – Saty