Thursday, April 11, 2013

[android help] Check if app is open during a GCM onMessage event?


I would use order broadcast to do that.


In your onMessagemethod:



Intent responseIntent = new Intent("com.yourpackage.GOT_PUSH");
sendOrderedBroadcast(responseIntent, null);


In your Activity:



public class YourActivity extends Activity {

final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {

@Override
public void onReceive(Context context, Intent intent) {
//Right here do what you want in your activity
abortBroadcast();
}
};

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

//.....
}

@Override
protected void onPause() {
unregisterReceiver(mBroadcastReceiver);
super.onPause();
}

@Override
protected void onResume() {
IntentFilter filter = new IntentFilter("com.yourpackage.GOT_PUSH");
filter.setPriority(2);
registerReceiver(mBroadcastReceiver, filter);
super.onResume();
}
}


The other BroadcastReceiver



public class SecondReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
//In this receiver just send your notification
}

}


Manifest:



android:name=".YourActivity"
android:label="@string/app_name">

android:name="android.intent.action.MAIN" />
android:name="android.intent.category.LAUNCHER" />


android:name=".SecondReceiver">
android:priority="1">
android:name="com.yourpackage.GOT_PUSH">




Basically in the onMessage method you send an Intent which is first received by the BroadcastReceiver registered inside YourActivity if it is running and in foreground, otherwise it is received by the SecondReceiver.



.

stackoverflow.comm

No comments:

Post a Comment

Google Voice on T-Mobile? [General]

Google Voice on T-Mobile? So I recently switched from a GNex on Verizon to a Moto X DE on T-Mobile. I had always used Google Voice for my v...