I' m trying to implement push notification in my applicatio but the RegistrationIntentService.class does not get called when i use the method startService.
home activity:
public class HomeActivity extends AriesMobileActivity {
private LinearLayout itemReports;
private LinearLayout itemTickets;
private LinearLayout itemSystems;
private LinearLayout itemManuals;
private LinearLayout itemNotes;
private LinearLayout itemChecklist;
private LinearLayout itemCalendar;
private LinearLayout itemSettings;
private BroadcastReceiver mRegistrationBroadcastReceiver;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(context);
boolean sentToken = sharedPreferences
.getBoolean(Preferences.SENT_TOKEN_TO_SERVER, false);
if (sentToken) {
} else {
}
}
};
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode, 9000)
.show();
} else {
Log.i(TAG, "This device is not supported.");
finish();
}
}
Intent intent = new Intent(this,RegistrationIntentService.class);
startService(intent);
if(this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
this.setContentView(R.layout.layout_home_landscape);
else this.setContentView(R.layout.layout_home_portrait);
itemReports = (LinearLayout) this.findViewById(R.id.item_menu_reports);
itemTickets = (LinearLayout) this.findViewById(R.id.item_menu_tickets);
itemSystems = (LinearLayout) this.findViewById(R.id.item_menu_systems);
itemManuals = (LinearLayout) this.findViewById(R.id.item_menu_manuals);
itemNotes = (LinearLayout) this.findViewById(R.id.item_menu_notes);
itemChecklist = (LinearLayout) this.findViewById(R.id.item_menu_checklist);
itemCalendar = (LinearLayout) this.findViewById(R.id.item_menu_calendar);
itemSettings = (LinearLayout) this.findViewById(R.id.item_menu_settings);
itemReports.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ReportListActivity.class);
startActivity(intent);
}
});
itemTickets.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, TicketListActivity.class);
startActivity(intent);
}
});
itemSystems.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, SystemListActivity.class);
startActivity(intent);
}
});
itemSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
context.startActivity(new Intent(context, SettingsActivity.class));
}
});
itemManuals.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ManualsListActivity.class);
startActivity(intent);
}
});
itemCalendar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, CalendarActivity.class);
startActivity(intent);
}
});
}
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(Preferences.REGISTRATION_COMPLETE));
}
#Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
super.onPause();
}
}
RegistrationIntentService:
public class RegistrationIntentService extends IntentService {
private static final String[] TOPICS = {"global"};
public RegistrationIntentService() {
super("RegistrationIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
try {
// [START register_for_gcm]
// Initially this call goes out to the network to retrieve the token, subsequent calls
// are local.
// R.string.gcm_defaultSenderId (the Sender ID) is typically derived from google-services.json.
// See https://developers.google.com/cloud-messaging/android/start for details on this file.
// [START get_token]
InstanceID instanceID = InstanceID.getInstance(this);
String token = instanceID.getToken("312109676786",
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
// [END get_token]
Log.i("RegistrationIntentService", "GCM Registration Token: " + token);
// TODO: Implement this method to send any registration to your app's servers.
sendRegistrationToServer(token);
// Subscribe to topic channels
subscribeTopics(token);
// You should store a boolean that indicates whether the generated token has been
// sent to your server. If the boolean is false, send the token to your server,
// otherwise your server should have already received the token.
sharedPreferences.edit().putBoolean(Preferences.SENT_TOKEN_TO_SERVER, true).apply();
// [END register_for_gcm]
} catch (Exception e) {
Log.d("RegistrationIntentService", "Failed to complete token refresh", e);
// If an exception happens while fetching the new token or updating our registration data
// on a third-party server, this ensures that we'll attempt the update at a later time.
sharedPreferences.edit().putBoolean(Preferences.SENT_TOKEN_TO_SERVER, false).apply();
}
// Notify UI that registration has completed, so the progress indicator can be hidden.
Intent registrationComplete = new Intent(Preferences.REGISTRATION_COMPLETE);
LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
/**
* Persist registration to third-party servers.
*
* Modify this method to associate the user's GCM registration token with any server-side account
* maintained by your application.
*
* #param token The new token.
*/
private void sendRegistrationToServer(String token) {
// Add custom implementation, as needed.
}
/**
* Subscribe to any GCM topics of interest, as defined by the TOPICS constant.
*
* #param token GCM token
* #throws IOException if unable to reach the GCM PubSub service
*/
// [START subscribe_topics]
private void subscribeTopics(String token) throws IOException {
GcmPubSub pubSub = GcmPubSub.getInstance(this);
for (String topic : TOPICS) {
pubSub.subscribe(token, "/topics/" + topic, null);
}
}
// [END subscribe_topics]
manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ngs.ariesmobile"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="com.verivo.examples.pushandalerttests.permission.C2D_MESSAGE" />
<permission android:name="com.example.gcm.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.gcm.permission.C2D_MESSAGE" />
<application
android:name=".AriesMobileApplication"
android:allowBackup="true"
android:icon="#drawable/app_logo"
android:label="#string/app_name"
android:theme="#android:style/Theme.Holo.Light.NoActionBar" >
<service
android:name=".AriesMobileGcmListenerService"
android:exported="false" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
<service
android:name=".AriesMobileInstanceIDListenerService"
android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID"/>
</intent-filter>
</service>
<service android:name=".RegistrationIntentService" android:exported="false">
<intent-filter>
<action android:name="com.google.android.gms.iid.InstanceID"/>
</intent-filter>
</service>
<receiver
android:name="com.google.android.gms.gcm.GcmReceiver"
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="com.example.gcm" />
</intent-filter>
</receiver>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<receiver
android:name="com.verivo.examples.pushandalerttests.MyBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.verivo.examples.pushandalerttests" />
</intent-filter>
</receiver>
<receiver android:name=".receivers.PhoneCallReceiver" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
<activity
android:name=".view.LoginActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".view.HomeActivity"
android:label="#string/app_name" />
<activity
android:name=".view.SignatureCaptureActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name"
android:screenOrientation="sensorLandscape" />
<activity
android:name=".view.SetupHomeActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name" />
<activity
android:name=".view.SetupApiActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name" />
<activity
android:name=".view.SetupLoginActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name" />
<activity
android:name=".view.SetupTechnicianActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name" />
<activity
android:name=".view.SettingsActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name" />
<activity
android:name=".view.SettingsPasswordActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name" />
<activity
android:name=".view.SettingsApiActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name" />
<activity
android:name=".view.SynchronizationActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name" />
<activity
android:name=".view.ReportCustomerActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name"
android:screenOrientation="sensorLandscape" />
<activity
android:name=".view.ReportInternalActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name"
android:screenOrientation="sensorLandscape" />
<activity
android:name=".view.ReportListActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name" />
<activity
android:name=".view.TicketListActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name" />
<activity
android:name=".view.PhoneCallActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name"
android:theme="#android:style/Theme.Translucent" />
<activity
android:name=".view.SystemActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name"
android:screenOrientation="landscape" />
<activity
android:name=".view.SystemListActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name" />
<activity
android:name=".view.ReportSummaryActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/app_name"
android:screenOrientation="portrait" />
<activity
android:name=".view.ManualsListActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/title_activity_manuals_list" >
</activity>
<activity
android:name=".view.SystemStoricalActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/title_activity_system_storical" >
</activity>
<activity
android:name=".view.SystemTechnicalPartActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/title_activity_system_technical_part" >
</activity>
<activity
android:name=".view.SystemConsActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/title_activity_system_cons" >
</activity>
<activity
android:name=".view.SystemNoteActivity"
android:configChanges="orientation|keyboard|screenSize"
android:label="#string/title_activity_system_note" >
</activity>
<activity
android:name=".view.SystemSupervisionActivity"
android:configChanges="orientation|screenSize"
android:label="#string/title_activity_system_supervision" >
</activity>
<activity
android:name=".view.CalendarActivity"
android:configChanges="orientation|screenSize"
android:label="#string/title_activity_calendar"
android:screenOrientation="landscape" >
</activity>
<activity
android:name=".view.ReportHoursActivity"
android:label="#string/title_activity_report_hours" >
</activity>
<activity
android:name="ngs.ariesmobile.pushnotification.RegisterActivity"
android:label="#string/title_activity_register" >
</activity>
</application>
</manifest>
Thanks in advance
Related
how to launch an launch activity after phone restart or manually turn power off or on
i tried below codes but its working for only for unlocking phone but i also want to make it done for boot up manually or restart phone.
below is code
application.class
public class MyApplication extends Application {
public static SharedPreferences preferences;
public static SharedPreferences.Editor editor;
public static String PASSWORD = "password";
public static String IS_SET = "nothing";
public static String MYPREF = "mypref";
public String TAG = getClass().getName();
#Override
protected void attachBaseContext(Context context) {
super.attachBaseContext(context);
MultiDex.install(this);
}
#Override
public void onCreate() {
super.onCreate();
init();
}
public void init() {
preferences = getSharedPreferences(MYPREF, 0);
editor = preferences.edit();
startService(new Intent(getBaseContext(), ScreenReceiver.class));
}
}
ScreenReceiver.class
public class ScreenReceiver extends BroadcastReceiver {
SharedPreferences preferences;
#Override
public void onReceive(Context context, Intent intent) {
System.out.println(intent.getAction());
preferences = context.getSharedPreferences(MYPREF, 0);
if (preferences != null) {
String lock = preferences.getString(IS_SET, null);
if (lock != null) {
if (lock.equals("passcode")) {
gotopasslock(context, intent);
} else {
gotopatternlock(context, intent);
}
}
}
}
public void gotopasslock(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
Intent intent1 = new Intent(context, Main.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent1);
} else if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent myStarterIntent = new Intent(context, Main.class);
myStarterIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myStarterIntent);
}
}
public void gotopatternlock(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
Intent intent1 = new Intent(context, PatternLock.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent1);
} else if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent myStarterIntent = new Intent(context, PatternLock.class);
myStarterIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myStarterIntent);
}
}
}
Main.class
public class Main extends AppCompatActivity {
private PinLockView mPinLockView;
private IndicatorDots mIndicatorDots;
private String TAG = getClass().getName();
String oldPassword = "";
String newPassword = "";
SharedPreferences preferences;
SharedPreferences.Editor editor;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// getSupportActionBar().hide();
super.onCreate(savedInstanceState);
setContentView(R.layout.main_xml);
menifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="">
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:replace="label">
<meta-data
android:name="com.google.android.gms.vision.DEPENDENCIES"
android:value="face" />
<activity android:name=".activities.ChooseActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<!-- <category android:name="android.intent.category.HOME" />
<category android:name="android.intent.category.DEFAULT" />-->
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".activities.Home" />
<activity android:name=".activities.MainActivity" />
<activity
android:name=".activities.Main"
android:showOnLockScreen="true" />
<activity
android:name=".activities.PatternLock"
android:showOnLockScreen="true" />
<!--<receiver
android:name=".receiver.ScreenReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
</receiver>-->
<receiver
android:name=".receiver.ScreenReceiver"
android:label="ScreenReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
<intent-filter>
<category android:name="android.intent.category.HOME" />
<action android:name="android.intent.action.SCREEN_ON" />
<action android:name="android.intent.action.SCREEN_OFF" />
<action android:name="android.intent.action.USER_PRESENT" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
</application>
</manifest>
Intent Action is missing.
To make a android activity launch after reboot, add following line in
AndroidManifest.xml
STEP 1
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Step 2:
<receiver
android:name=".receiver.ScreenReceiver"
android:label="ScreenReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.USER_PRESENT"
</intent-filter>
</receiver>
NOTE:
try to do code cleanup
I'm trying to implement Facebook login button, but i'm receiving these errors when trying to run app:
Error:
FATAL EXCEPTION: AsyncTask #4
Process: , PID: 4633
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Object.hashCode()' on a null object reference
at java.util.concurrent.ConcurrentHashMap.get(ConcurrentHashMap.java:746)
at java.util.concurrent.ConcurrentHashMap.containsKey(ConcurrentHashMap.java:774)
at com.facebook.internal.Utility.queryAppSettings(Utility.java:825)
at com.facebook.login.widget.LoginButton$1.run(LoginButton.java:489)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
com.android.vlada.sportisa E/GoogleApiAvailability: Google Play services is invalid. Cannot recover.
Code:
public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {
private Button buttonRegistrujSe, buttonPrijaviSeKaoGost, buttonPrijavaRegistrovaniKorisnik;
private LoginButton loginButton;
private CallbackManager callbackManager;
private TextView info;
#Override
protected void onCreate(Bundle savedInstanceState) {
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FacebookSdk.sdkInitialize(getApplicationContext());
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
GoogleApiClient mGoogleApiClient;
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
buttonRegistrujSe = (Button) (findViewById(R.id.button_registruj_se));
buttonRegistrujSe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, RegistrationActivity.class);
startActivity(i);
}
});
buttonPrijaviSeKaoGost = (Button) (findViewById(R.id.button_prijavi_se_kao_gost));
buttonPrijaviSeKaoGost.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i2 = new Intent(MainActivity.this, LoginGostActivity.class);
startActivity(i2);
}
});
buttonPrijavaRegistrovaniKorisnik = (Button) (findViewById(R.id.button_prijava_registrovani_korisnik));
buttonPrijavaRegistrovaniKorisnik.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i3 = new Intent(MainActivity.this, LoginActivity.class);
startActivity(i3);
}
});
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_main);
info = (TextView)findViewById(R.id.info);
loginButton = (LoginButton)findViewById(R.id.connectWithFbButton);
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
info.setText(
"User ID: "
+ loginResult.getAccessToken().getUserId()
+ "\n" +
"Auth Token: "
+ loginResult.getAccessToken().getToken()
);
}
#Override
public void onCancel() {
info.setText("Login attempt canceled.");
}
#Override
public void onError(FacebookException e) {
info.setText("Login attempt failed.");
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onDestroy() {
super.onDestroy();
System.exit(0);
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
Layout Code
<com.facebook.login.widget.LoginButton
android:id="#+id/connectWithFbButton"
style="#style/com_facebook_loginview_default_style"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_above="#+id/sign_in_button"
android:layout_centerHorizontal="true"
android:layout_marginBottom="43dp" />
Update: after i deleted duplicate code in MainActivity i'm still receiving the same errors when trying to ran app. I'm attaching Manifest code also as requested so maybe that would help? Thanx
<?xml version="1.0" encoding="utf-8"?>
<!-- To auto-complete the email text field in the login form with the user's emails -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.INTERNET" />
<permission
android:name="com.android.vlada.sportisa.Entiteti.maps.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<uses-permission android:name="com.android.vlada.sportisa.Entiteti.maps.permission.MAPS_RECEIVE" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyAVb2JuN-5nbaVkGODivuXPJOF5OeRekzo" />
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_login" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity android:name=".MainActivity" />
<activity android:name=".SplashActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".RegistrationActivity" />
<activity android:name=".LoginActivity" />
<activity android:name=".BiranjeAktivnosti" />
<activity
android:name=".Trazim"
android:label="#string/title_activity_trazim"
android:theme="#style/AppTheme" />
<activity
android:name=".Organizujem"
android:label="#string/title_activity_organizujem"
android:theme="#style/AppTheme" />
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name"
android:theme="#android:style/Theme.Translucent.NoTitleBar" />
</application>
Add metadata inside application tag before activities.
What you have now is:
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyAVb2JuN-5nbaVkGODivuXPJOF5OeRekzo" />
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_login" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity android:name=".MainActivity" />
<activity android:name=".SplashActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
...
</application>
Move metadata inside application tag like this:
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyAVb2JuN-5nbaVkGODivuXPJOF5OeRekzo" />
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_login" />
<activity android:name=".MainActivity" />
<activity android:name=".SplashActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
...
</application>
Have you added this code in manifest file.
You also need to add the application id like this:
<application android:label="#string/app_name" ...>
...
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="#string/facebook_app_id"/>
...
</application>
Don't what, but there's an issue with either FacebookActivity name or the support for Gradle Version 2.3.0 is removed. I faced the same issue and with the following I got rid of this.
Replaced <activity> tag
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name"
android:theme="#android:style/Theme.Translucent.NoTitleBar" />
with the <meta> tag.
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/fb_id" />
EDIT
Also, I have placed this <meta> tag at the bottom of the file below, all the activities, above the closing tag.
i have try to implement GCM in android studio got below error in my logcat.
LogCat:
onReceive: com.google.android.c2dm.intent.REGISTRATION GCM
IntentService class: com.project.GCMIntentService Acquiring wakelock
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.project">
<permission
android:name="com.project.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" ></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.project.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.READ_SYNC_STATS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS" />
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.project.permission.C2D_MESSAGE" />
<!-- This app has permission to register and receive data message. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<!-- Creates a custom permission so only this app can receive its messages. -->
<!-- Required OpenGL ES 2.0. for Maps V2 -->
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<permission
android:name="com.project.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<application
android:name="com.project.App"
android:allowBackup="true"
android:hardwareAccelerated="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:largeHeap="true"
android:theme="#style/AppTheme">
<activity
android:name=".SplashScreenActivity"
android:screenOrientation="portrait"
android:theme="#style/FullScreenThemes">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.project.core.account.ManageAccounts" />
<activity android:name=".projectActivity"/>
<activity android:name=".projectLogin"/>
<activity android:name="fieldatom.controls.SearchableItemActivity" />
<activity android:name="com.project.SettingsActivity" />
<activity
android:name="com.project.core.account.AppIntro"
android:screenOrientation="portrait" />
<activity
android:name=".base.addons.mail.widget.MailDetailDialog"
android:theme="#style/Theme.AppCompat.Light.Dialog" />
<activity
android:name=".base.addons.mail.widget.MailChatterCompose"
android:theme="#style/Theme.AppCompat.Light.Dialog" />
<activity
android:name=".core.account.FieldAtomAccountQuickManage"
android:theme="#style/Theme.AppCompat.Light.Dialog"
android:windowSoftInputMode="adjustPan" />
<activity android:name="com.project.core.account.About" />
<activity android:name="com.project.core.account.Profile" />
<!-- Reminder Receivers// -->
<receiver android:name="com.project.core.utils.reminder.ReminderReceiver" />
<receiver android:name="com.project.core.utils.reminder.ReminderActionReceiver" />
<!--<receiver android:name=".server.notifications.OdooServerNotificationReceiver">
<intent-filter>
<action android:name="com.project.odoo.mobile.SERVER_NOTIFICATION" />
</intent-filter>
</receiver>-->
<service android:name="com.project.core.auth.OdooAuthService">
<intent-filter>
<action android:name="android.accounts.AccountAuthenticator" />
</intent-filter>
<meta-data
android:name="android.accounts.AccountAuthenticator"
android:resource="#xml/authenticator" />
</service>
<provider
android:name="com.project.core.orm.provider.BaseModelProvider"
android:authorities="com.project.core.provider.content"
android:multiprocess="true" />
<provider
android:name="com.project.base.addons.ir.providers.IrModelProvider"
android:authorities="com.project.core.provider.content.sync.ir_model"
android:multiprocess="true" />
<!-- Sync Customer Provider & Service // -->
<provider
android:name="com.project.addons.customers.providers.CustomersSyncProvider"
android:authorities="com.project.core.provider.content.sync.res_partner"
android:label="#string/sync_label_customers"
android:multiprocess="true" />
<service
android:name="com.project.addons.customers.services.CustomerSyncService"
android:exported="true"
android:process=":sync_customer">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="#xml/customer_sync_adapter" />
</service>
<!-- Sync Request Provider & Service // -->
<provider
android:name="com.project.addons.requests.providers.RequestSyncProviders"
android:authorities="com.project.core.provider.content.sync.fa_service_request"
android:label="#string/sync_label_request"
android:multiprocess="true" />
<service
android:name="com.project.addons.requests.services.RequestSyncService"
android:exported="true"
android:process=":sync_request">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="#xml/request_sync_adapter" />
</service>
<!-- Sync Stage Provider & Service // -->
<provider
android:name="com.project.addons.stages.providers.StageSyncProviders"
android:authorities="com.project.core.provider.content.sync.fa_service_stage"
android:label="#string/sync_label_stages"
android:multiprocess="true" />
<service
android:name="com.project.addons.stages.services.StageSyncService"
android:exported="true"
android:process=":sync_stage">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="#xml/stage_sync_adapter" />
</service>
<!-- Sync Account Analytic Provider & Service // -->
<provider
android:name="com.project.addons.accountanalytics.providers.AccountAnalyticSyncProviders"
android:authorities="com.project.core.provider.content.sync.account_analytic_line"
android:label="#string/sync_label_accountAnalytic"
android:multiprocess="true" />
<service
android:name="com.project.addons.accountanalytics.services.AccountAnalyticSyncService"
android:exported="true"
android:process=":sync_account_analytic">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="#xml/account_analytic_sync_adapter" />
</service>
<!-- Sync Product Provider & Service // -->
<provider
android:name=".addons.products.providers.ProductsSyncProviders"
android:authorities="com.project.core.provider.content.sync.product_product"
android:label="#string/sync_label_product"
android:multiprocess="true" />
<service
android:name=".addons.products.service.ProductsSyncService"
android:exported="true"
android:process=":sync_account_analytic">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="#xml/product_sync_adapter" />
</service>
<!-- Sync QUOTATION Provider & Service // -->
<provider
android:name=".addons.quotes.providers.QuotationSyncProviders"
android:authorities="com.project.core.provider.content.sync.sale_order"
android:label="#string/sync_label_quotation"
android:multiprocess="true" />
<service
android:name=".addons.quotes.services.QuotationSyncService"
android:exported="true"
android:process=":sync_quotation">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="#xml/quote_sync_adapter" />
</service>
<!-- Sync QUOTATIONLine Provider & Service // -->
<provider
android:name=".addons.quotes.providers.QuotationLineSyncProviders"
android:authorities="com.project.core.provider.content.sync.sale_order_line"
android:label="#string/sync_label_quotation_line"
android:multiprocess="true" />
<service
android:name=".addons.quotes.services.QuotationLineSyncService"
android:exported="true"
android:process=":sync_quotation_line">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="#xml/quote_line_sync_adapter" />
</service>
<!-- Sync Attachment Provider & Service // -->
<provider
android:name=".addons.attachment.providers.IrAttachmentSyncProviders"
android:authorities="com.project.core.provider.content.sync.ir_attachment"
android:label="#string/sync_label_attachment"
android:multiprocess="true" />
<service
android:name=".addons.attachment.service.IrAttachmentSyncService"
android:exported="true"
android:process=":sync_attachment">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="#xml/attachment_sync_adapter" />
</service>
<!-- Sync MailMessage Provider & Service // -->
<provider
android:name=".base.addons.mail.providers.MailMessageSyncProviders"
android:authorities="com.project.core.provider.content.sync.mail_message"
android:label="#string/sync_label_mail_message"
android:multiprocess="true" />
<service
android:name=".base.addons.mail.service.MailMessageSyncService"
android:exported="true"
android:process=":sync_mail_message">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="#xml/mail_message_sync_adapter" />
</service>
<!-- Sync Maps Provider & Service // -->
<provider
android:name=".addons.maps.providers.MapsSyncProviders"
android:authorities="com.project.core.provider.content.sync.fa_map"
android:label="#string/sync_label_map_message"
android:multiprocess="true" />
<service
android:name=".addons.maps.service.MapsSyncService"
android:exported="true"
android:process=":sync_map">
<intent-filter>
<action android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="#xml/maps_sync_adapter" />
</service>
<service android:name=".addons.requests.services.TimeUpdateService"></service>
<activity
android:name="com.project.addons.customers.CustomerDetailActivity"
android:configChanges="orientation|keyboardHidden|screenLayout|screenSize"
android:windowSoftInputMode="stateHidden|adjustPan" />
<activity
android:name=".addons.requests.utils.RequestTabDetailAcitivty"
android:configChanges="orientation|keyboardHidden|screenLayout|screenSize"
android:windowSoftInputMode="stateHidden|adjustPan"
/>
<activity
android:name=".addons.accountanalytics.VisitDetailActivity"
android:configChanges="orientation|keyboardHidden|screenLayout|screenSize"
android:theme="#style/CustomActionBar"
android:windowSoftInputMode="stateHidden" />
<activity
android:name=".addons.accountanalytics.CreateVisitActivity"
android:configChanges="orientation|keyboardHidden|screenLayout|screenSize"
android:windowSoftInputMode="stateHidden"></activity>
<activity
android:name=".addons.requests.AddPartActivity"
android:configChanges="orientation|keyboardHidden|screenLayout|screenSize"
android:windowSoftInputMode="stateHidden"></activity>
<activity
android:name=".addons.requests.AddNoteActivity"
android:configChanges="orientation|keyboardHidden|screenLayout|screenSize"
android:windowSoftInputMode="stateHidden"></activity>
<activity
android:name=".addons.requests.AddQuoteActivity"
android:configChanges="orientation|keyboardHidden|screenLayout|screenSize"
android:windowSoftInputMode="stateHidden"></activity>
<activity
android:name=".addons.requests.utils.CaptureSignature"
android:configChanges="orientation|keyboardHidden|screenLayout|screenSize"
android:windowSoftInputMode="stateHidden"></activity>
<activity
android:name=".addons.requests.utils.ProductRequestListActivity"
android:configChanges="orientation|keyboardHidden|screenLayout|screenSize"
android:windowSoftInputMode="stateHidden"></activity>
<activity
android:name=".addons.quotes.QuoteDetailActivity"
android:configChanges="orientation|keyboardHidden|screenLayout|screenSize"
android:windowSoftInputMode="stateHidden"></activity>
<activity
android:name=".addons.products.ProductDetails"
android:configChanges="orientation|keyboardHidden|screenLayout|screenSize"
android:windowSoftInputMode="stateHidden"></activity>
<!-- Map Related Metadata -->
<uses-library
android:name="com.google.android.maps"
android:required="false" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyCpjJtPYoeVN2dGqCVMCDEoR847OEwzgME" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<!-- Push Notification -->
<receiver
android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<!-- Receives the actual messages. -->
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<!-- Receives the registration id. -->
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.project" />
</intent-filter>
</receiver>
<service android:name=".GCMIntentService"></service>
</application>
<!--CB:A6:E7:26:97:08:37:4A:D6:60:1B:9B:2C:D0:9A:3B:9F:DF:02:D3;com.project-->
</manifest>
This is my project structure details below.
com.projcet
App.java
ProjcetLogin.java
GCMIntentService.java
This code working perfect in eclipse & android studio...finally i can do it.
MainActivity.java
public class MainActivity extends Activity implements View.OnClickListener{
//Notification Constant
Context context;
Button btn_GCMRegister, btn_Post;
GoogleCloudMessaging gcm;
public static String URL = "192.168.1.39:12069";
String regId;
public final String GOOGLE_PROJECT_ID = "your project id";
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
init();
}
private void init() {
btn_GCMRegister = (Button) findViewById(R.id.btn_gcm_register);
btn_GCMRegister.setOnClickListener(this);
btn_Post = (Button) findViewById(R.id.btn_post_on_server);
btn_Post.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn_gcm_register:
registerGCM();
break;
case R.id.btn_post_on_server:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Map<String, Object> params = new HashMap<String, Object>();
params.put("regId", regId);
params.put("user_id", 1);
String server_url = URL;
try {
post(server_url, params);
}catch (IOException e){
e.printStackTrace();
}
break;
default:
break;
}
}
/*
* Issue a POST request to the server.
*/
private static void post(String endpoint, Map<String, Object> params)
throws IOException {
URL url;
try {
url = new URL(endpoint);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("invalid url: " + endpoint);
}
StringBuilder bodyBuilder = new StringBuilder();
Iterator<Map.Entry<String, Object>> iterator = params.entrySet().iterator();
// constructs the POST body using the parameters
while (iterator.hasNext()) {
Map.Entry<String, Object> param = iterator.next();
bodyBuilder.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
bodyBuilder.append('&');
}
}
String body = bodyBuilder.toString();
//Log.v(Config.TAG, "Posting '" + body + "' to " + url);
byte[] bytes = body.getBytes();
HttpURLConnection conn = null;
try {
Log.e("URL", "> " + url);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
// post the request
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
// handle the response
int status = conn.getResponseCode();
System.out.println("Json Data--->" + status);
// If response is not success
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
private void registerGCM() {
// TODO Auto-generated method stub
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regId = gcm.register(GOOGLE_PROJECT_ID);
Log.d("Reg Id----->", "" + regId);
Toast.makeText(MainActivity.this,"Register Key from server : " +regId,Toast.LENGTH_LONG).show();
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
Log.d("MainActivity", "Error: " + msg);
}
Log.d("MainActivity", "AsyncTask completed: " + msg);
return msg;
}
#Override
protected void onPostExecute(String msg) {
Toast.makeText(getApplicationContext(),
"Registered On GCM Server." + msg, Toast.LENGTH_LONG)
.show();
}
}.execute(null, null, null);
}
}
GCMIntentService.java
public class GCMIntentService extends GCMBaseIntentService {
#Override
protected void onError(Context arg0, String arg1) {
// TODO Auto-generated method stub
Log.e("onError", "gcm...error");
}
public GCMIntentService() {
super("your project id");
}
#Override
protected String[] getSenderIds(Context context) {
return super.getSenderIds(context);
}
#Override
protected void onMessage(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.i(TAG, "Received message");
if (intent.getExtras() != null) {
String message = intent.getExtras().getString("message");
String title = intent.getExtras().getString("title");
String ticker = intent.getExtras().getString("ticker");
generateNotification(context,message,title,ticker);
}
}
#Override
protected void onRegistered(Context arg0, String arg1) {
// TODO Auto-generated method stub
Log.e("onRegistered", "gcm Registered");
}
#Override
protected void onUnregistered(Context arg0, String arg1) {
// TODO Auto-generated method stub
Log.e("onUnregistered", "gcm...Unregistered...");
}
/**
* Create a notification to inform the user that server has sent a message.
*/
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private static void generateNotification(Context context, String message,String title,String ticker) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(context);
Intent notificationIntent = new Intent(context, MainActivity.class);
PendingIntent intent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
builder.setContentTitle(title)
.setContentText(message)
.setLargeIcon(
BitmapFactory.decodeResource(context.getResources(),
icon))
.setStyle(new Notification.BigTextStyle().bigText(message))
.setContentIntent(intent).setSmallIcon(icon).setTicker(ticker)
.setLights(0xff00ff00, 300, 100)
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE).setAutoCancel(true).setWhen(when);
Notification notification = builder.build();
notificationManager.notify(0, notification);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.xxx.gcmnotification" >
<!-- GCM connects to Internet Services. -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- Creates a custom permission so only this app can receive its messages. -->
<permission
android:name="com.example.xxx.gcmnotification.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.xxx.gcmnotification.permission.C2D_MESSAGE" />
<!-- This app has permission to register and receive data message. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<!-- Receives the actual messages. -->
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<!-- Receives the registration id. -->
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.example.xxx.gcmnotification" />
</intent-filter>
</receiver>
<service android:name=".GCMIntentService" />
</application>
</manifest>
build.gradle(Module:app)
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:22.2.0'
compile 'com.google.android.gms:play-services:+'
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
android:gravity="center"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<Button
android:id="#+id/btn_gcm_register"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10dip"
android:text="Register On GCM Server" />
<Button
android:id="#+id/btn_post_on_server"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10dip"
android:text="Post On Server" />
</LinearLayout>
I am working on Parse notifications..to send notifications to all users...The below code works well on emulator but the real device cannot get notifications....
Heres my code :
MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ParseAnalytics.trackAppOpenedInBackground(getIntent());
PushService.setDefaultPushCallback(this, MainActivity.class);
ParseInstallation.getCurrentInstallation().saveInBackground();
}
}
ParseApplication.java
public class ParseApplication extends Application{
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Parse.initialize(this, "[APP ID]", "[CLIENT KEY]");
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
defaultACL.setPublicReadAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
ParseInstallation.getCurrentInstallation().saveInBackground();
}
Receiver.java
public class Receiver extends ParsePushBroadcastReceiver{
#Override
protected void onPushOpen(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
Intent i = new Intent(arg0,MainActivity.class);
i.putExtras(arg1.getExtras());
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
arg0.startActivity(i);
}
AndroidManifest.xml
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="11" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission android:protectionLevel="signature"
android:name="com.example.parse.permission.C2D_MESSAGE" />
<uses-permission android:name="com.example.parse.permission.C2D_MESSAGE" />
<application
android:allowBackup="true"
android:name="com.example.parse.ParseApplication"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
>
<activity
android:name="com.example.parse.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.parse.PushService" />
<receiver android:name="com.parse.ParseBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>
<receiver
android:name="com.example.parse.Receiver"
android:exported="false" >
<intent-filter>
<action android:name="com.parse.push.intent.RECEIVE" />
<action android:name="com.parse.push.intent.DELETE" />
<action android:name="com.parse.push.intent.OPEN" />
</intent-filter>
</receiver>
</application>
</manifest>
You do not have subscription set. If you haven't seen it already please follow the link. Parse Android Push Tutorial
In your Application onCreate:
ParsePush.subscribeInBackground("", new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Log.d("com.parse.push", "successfully subscribed to the broadcast channel.");
} else {
Log.e("com.parse.push", "failed to subscribe for push", e);
}
}
});
As you may be creating your own sample app, pay close attention to the Manifest configuration, ensure you have right package names.
As noted in the Parse docs, they use GCM when Play-Services is available, which actual Android device will have. Where as they use persistent connection on devices without play-service ie. your emulator. Hope this helps.
I do receive the push messages but whenever I click on them inside the notificationbar this logcat appears and the notification dissapears...
This is my logcat output:
05-31 16:49:47.165: D/Test - UALib(20523): No intent receiver set, not sending ACTION_NOTIFICATION_OPENED
Here is my manifest structure:
<category android:name="com.test.push" />
</intent-filter>
</receiver>
<service
android:name="com.urbanairship.push.PushService"
android:label="Push Notification Service" />
<service
android:name="com.urbanairship.push.PushWorkerService"
android:label="Push Notification Worker Service" />
<service
android:name="com.urbanairship.analytics.EventService"
android:label="Event Service" />
<provider
android:name="com.urbanairship.UrbanAirshipProvider"
android:authorities="com.test.push.urbanairship.provider"
android:exported="false"
android:multiprocess="true" />
<activity
android:name="com.test.push.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.test.push.SettingsActivity"
android:label="#string/title_activity_settings" />
<activity
android:name="com.test.push.ChooseClass"
android:label="#string/app_name" />
</application>
This here is my MyApplication.java:
public class MyApplication extends Application {
#Override
public void onCreate() {
AirshipConfigOptions options = AirshipConfigOptions
.loadDefaultOptions(this);
options.developmentAppKey = "1234567890";
options.developmentAppSecret = "1234567890";
options.productionAppKey = "";
options.productionAppSecret = "";
options.gcmSender = "1234567890";
options.transport = "gcm";
options.inProduction = false;
UAirship.takeOff(this, options);
PushManager.enablePush();
}
}
And this is my IntentReceiver.java:
public class IntentReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context aContext, Intent aIntent) {
String action = aIntent.getAction();
if (action.equals(PushManager.ACTION_PUSH_RECEIVED)) {
logPushExtras(aIntent);
} else if (action.equals(PushManager.ACTION_NOTIFICATION_OPENED)) {
logPushExtras(aIntent);
Intent launch = new Intent(Intent.ACTION_MAIN);
launch.setClass(UAirship.shared().getApplicationContext(),
MainActivity.class);
launch.putExtra("push_message",
aIntent.getStringExtra(PushManager.EXTRA_ALERT));
launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
UAirship.shared().getApplicationContext().startActivity(launch);
} else if (action.equals(PushManager.ACTION_REGISTRATION_FINISHED)) {
Logger.info("device registrated, APID="
+ aIntent.getStringExtra(PushManager.EXTRA_APID)
+ ", valid="
+ aIntent.getBooleanExtra(
PushManager.EXTRA_REGISTRATION_VALID, false));
}
}
private void logPushExtras(Intent intent) {
Set<String> keys = intent.getExtras().keySet();
for (String key : keys) {
List<String> ignoredKeys = (List<String>) Arrays.asList(
"collapse_key", "from", PushManager.EXTRA_NOTIFICATION_ID,
PushManager.EXTRA_PUSH_ID, PushManager.EXTRA_ALERT);
if (ignoredKeys.contains(key)) {
continue;
}
}
}
}
The problem was, I was missing the following line inside my MyApplication.java file:
PushManager.shared().setIntentReceiver(IntentReceiver.class);
All the rest was correct. It's now working perfectly.
And i was missing to specify Application's android:name attribute in my manifest file-
<application
android:allowBackup="true"
android:icon="#drawable/app_icon"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:allowClearUserData="true"
android:enabled="true"
android:name=".MyMainApplication">
<activity>
Some Activity
</activity>
</application>