I'm building an app that would read incoming SMS. But, my BroadcastReceiver class can't detect/read incoming SMS. I think my code is correct but still it's not working.
Here's my code:
[XML]
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.crashlocator.carlax.crashlocator">
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.VIBRATE" />
<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"
android:theme="#android:style/Theme.NoTitleBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.default" />
</intent-filter>
</activity>
<activity android:name=".MainActivity2" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.default" />
</intent-filter>
</activity>
<receiver
android:name=".SmsReceiver"
android:exported="true" >
<intent-filter android:priority="2147483647" >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
[JAVA CLASS]
public class SmsReceiver extends BroadcastReceiver {
private static final String SMS_BUNDLE = "pdus";
private String smsBody, address;
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"Test",Toast.LENGTH_LONG);
}
public void showNotification(Context context) {
Vibrator v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MapsActivity.class), 0);
v.vibrate(500);
Intent in = new Intent("SmsMessage.intent.MAIN").
putExtra("get_msg", address + ":" + smsBody);
context.sendBroadcast(in);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
//.setSmallIcon(R.drawable.notif1)
.setContentTitle("Attention!")
.setContentText("Car crash occure.");
mBuilder.setContentIntent(contentIntent);
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
}
I think you forgot to put .show() at the end of Toast.
Toast.makeText(context, "Test" ,Toast.LENGTH_LONG).show();
Related
This is my GPS service that I'm using to obtain GPS coordinates in the background. I have logged at various areas of the code to see which bits are being called and which aren't. This service is called from a button being clicked. Nothing seems to be logged for the location and the main issue is regarding the location updates which is not returning anything.
public class SetGPS extends Service {
private LocationListener listener;
private LocationManager locationManager;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
//this is logged successfully
Log.i("LocationListener","is called");
listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Intent i = new Intent("location_update");
i.putExtra("coordinates", location.getLongitude() + " " + location.getLatitude());
sendBroadcast(i);
String latitude = String.valueOf(location.getLatitude());
//this is NOT logged successfully
Log.i("coordinates SetGPS",latitude);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
//this is NOT logged successfully
Log.i("onProviderDisabled","is logged");
}
};
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
try {
//does NOT successfully log
Log.i("testing","testing");
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 0, listener);
}
catch (SecurityException e){
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
if(locationManager != null){
locationManager.removeUpdates(listener);
}
}
}
And here is my manifest file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.a_phi.nowswap">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.NFC" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.WRITE_CONTACTS"
android:required="true" />
<uses-permission
android:name="android.permission.READ_CONTACTS"
android:required="true" />
<meta-data
android:name="firebase_crash_collection_enabled"
android:value="false" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- 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" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<service
android:name=".HceService"
android:exported="true"
android:permission="android.permission.BIND_NFC_SERVICE">
<intent-filter>
<action android:name="android.nfc.cardemulation.action.HOST_APDU_SERVICE" />
</intent-filter>
<meta-data
android:name="android.nfc.cardemulation.host_apdu_service"
android:resource="#xml/apduservice" />
</service>
<service android:name=".SetGPS"
android:permission="android.permission.ACCESS_FINE_LOCATION"/>
<activity
android:name=".LoginActivity"
android:windowSoftInputMode="adjustPan">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
<data android:scheme="file" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.CATEGORY_DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".Pilot"
android:theme="#style/AppTheme.NoActionBar"
android:windowSoftInputMode="adjustPan">
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
<data android:scheme="file" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.CATEGORY_DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".personalHome"
android:label="#string/title_activity_personal_home"
android:theme="#style/AppTheme.NoActionBar"></activity>
<activity
android:name=".ProfessionalHome"
android:label="professionalHome"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.CATEGORY_DEFAULT" />
<data android:mimeType="text/plain`" />
<data android:scheme="file" />
</intent-filter>
</activity>
<activity
android:name=".EditDetailsPersonal"
android:label="editDetails"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".EditDetailsProfessional"
android:label="editDetailsProfessional"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".receivedContact"
android:label="#string/title_activity_received_contact"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".RegisterActivity"
android:label="RegisterActivity"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".AddContact"
android:label="#string/add_contact_button"
android:theme="#style/Theme.AppCompat.Light" />
<activity
android:name=".DrawerActivity"
android:label="#string/title_activity_drawer"
android:theme="#style/Theme.AppCompat.DayNight.DarkActionBar"></activity>
</application>
</manifest>
It returns the following stacktrace.
08-31 11:44:47.710 1399-1411/? W/System.err: java.lang.SecurityException: "gps" location provider requires ACCESS_FINE_LOCATION permission.
at com.android.server.LocationManagerService.checkResolutionLevelIsSufficientForProviderUse(LocationManagerService.java:1321)
at com.android.server.LocationManagerService.getProviderProperties(LocationManagerService.java:2334)
at android.location.ILocationManager$Stub.onTransact(ILocationManager.java:378)
at com.android.server.HwLocationManagerService.onTransact(HwLocationManagerService.java:379)
08-31 11:44:47.711 1399-1411/? W/System.err: at android.os.Binder.execTransact(Binder.java:565)
08-31 11:44:47.712 1399-2192/? W/System.err: java.lang.SecurityException: "network" location provider requires ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission.
at com.android.server.LocationManagerService.checkResolutionLevelIsSufficientForProviderUse(LocationManagerService.java:1324)
at com.android.server.LocationManagerService.getProviderProperties(LocationManagerService.java:2334)
at android.location.ILocationManager$Stub.onTransact(ILocationManager.java:378)
at com.android.server.HwLocationManagerService.onTransact(HwLocationManagerService.java:379)
at android.os.Binder.execTransact(Binder.java:565)
08-31 11:45:06.132 17192-17192/com.example.a_phi.nowswap W/System.err: java.lang.SecurityException: "gps" location provider requires ACCESS_FINE_LOCATION permission.
at android.os.Parcel.readException(Parcel.java:1665)
at android.os.Parcel.readException(Parcel.java:1618)
at android.location.ILocationManager$Stub$Proxy.requestLocationUpdates(ILocationManager.java:614)
at android.location.LocationManager.requestLocationUpdates(LocationManager.java:952)
at android.location.LocationManager.requestLocationUpdates(LocationManager.java:536)
at com.example.a_phi.nowswap.SetGPS.onCreate(SetGPS.java:72)
at android.app.ActivityThread.handleCreateService(ActivityThread.java:3350)
at android.app.ActivityThread.-wrap5(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1670)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6623)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
which indicates there is an issue with
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 0, listener);
I built a chat application using firebase cloud messaging and firebase functions. But I have two problems currently.
1. When the app is in open and a new message comes in, the app will automatically move to the main activity of the application.
2. And secondly, I want notifications to be received only when it is in the background.
How do I achieve this?
Below is my onMessageReceived
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
showNotification(remoteMessage.getData().get("name"), (remoteMessage.getData().get("click_action")), remoteMessage.getData().get("title"));
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
}
}
private void showNotification(String name, String click_action, String title) {
Intent intent;
if (click_action.equals("Download")) {
intent = new Intent(this, Download.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
} else if (click_action.equals("Student_SystemsDevt")) {
intent = new Intent(this, Student_SystemsDevt.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
else {
intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setContentTitle(title)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText(name)
.setAutoCancel(true)
.setStyle(new NotificationCompat.BigTextStyle())
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
My Manifest File
<application
android:name=".GTUCONLINE"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".LoginActivity"
android:screenOrientation="portrait"
android:theme="#style/MyTheme" />
<activity android:name=".MainActivity">
</activity>
<activity
android:name=".ChoiceActivity"
android:screenOrientation="portrait"
android:theme="#style/MyTheme" />
<activity
android:name=".WelcomeActivity"
android:screenOrientation="portrait"
android:theme="#style/MyTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
android:theme="#style/Base.Theme.AppCompat" />
<activity
android:name=".StudentSignUp"
android:screenOrientation="portrait"
android:theme="#style/MyTheme" />
<activity
android:name=".LecturerSignUp"
android:screenOrientation="portrait" />
<activity android:name=".ProgrammeActivity" />
<service android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<activity
android:name=".TopicActivity"
android:theme="#style/MyTheme" />
<activity android:name=".MIS" />
<activity android:name=".GB" />
<activity android:name=".FIN" />
<activity android:name=".ENGINEERINGM" />
<activity android:name=".BDM" />
<activity android:name=".SCM" />
<activity android:name=".TE" />
<activity android:name=".TM" />
<activity android:name=".BET" />
<activity android:name=".ICT" />
<activity android:name=".T" />
<activity android:name=".IT" />
<activity android:name=".AM" />
<activity android:name=".OGM" />
<activity android:name=".I" />
<activity android:name=".PEF" />
<activity android:name=".QM" />
<activity android:name=".EPM" />
<activity android:name=".PM" />
<activity android:name=".HM" />
<activity android:name=".StudentsList">
<intent-filter>
<action android:name="StudentsList" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".LecturersList" />
<activity android:name=".AdminActivity" />
<activity
android:name=".ChatActivity"
android:parentActivityName=".StudentsList" />
<activity android:name=".LecturerMainActivity" />
<activity
android:name=".Download"
android:parentActivityName=".MIS">
<intent-filter>
<action android:name="Download" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".MIS_Information"
android:parentActivityName=".MIS" />
<activity android:name=".Terms" />
<activity
android:name=".Admin_Login"
android:parentActivityName=".LoginActivity" />
<activity
android:name=".Manipulation"
android:parentActivityName=".Admin_Login" />
<activity android:name=".Admins" />
<activity
android:name=".SystemsDevt"
android:parentActivityName=".MIS" />
<activity
android:name=".SysGroupChat"
android:parentActivityName=".SystemsDevt" />
<activity
android:name=".EntSystems"
android:parentActivityName=".MIS" />
<activity android:name=".DownloadEnt">
<intent-filter>
<action android:name="DownloadEnt" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".student_mis" />
<activity
android:name=".Student_SystemsDevt"
android:parentActivityName=".student_mis">
<intent-filter>
<action android:name="Student_SystemsDevt" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".Student_EntSys"
android:parentActivityName=".student_mis" />
<activity
android:name=".SystemsDevt_Add"
android:parentActivityName=".SystemsDevt" />
<activity android:name=".EntSystemsAdd" />
<activity android:name=".EntSystemsInfo" />
<activity
android:name=".DatabaseSystems"
android:parentActivityName=".MIS" />
<activity android:name=".DownloadDatabaseSys" />
<activity
android:name=".Student_DatabaseSystems"
android:parentActivityName=".student_mis" />
<activity android:name=".DatabaseInfo" />
<activity
android:name=".DatabaseAdd"
android:parentActivityName=".DatabaseSystems" />
<activity
android:name=".IntroToOil"
android:parentActivityName=".GB" />
<activity
android:name=".DownloadIntro"
android:parentActivityName=".IntroToOil" />
<activity
android:name=".IntroToOilInfo"
android:parentActivityName=".IntroToOil" />
<activity
android:name=".IntroToOilAdd"
android:parentActivityName=".IntroToOil" />
<activity android:name=".student_gb" />
<activity android:name=".StudentIntro" />
<activity android:name=".MIS_students_new"
android:parentActivityName=".SystemsDevt">
</activity>
</application>
1- Actually onMessageReceived is only triggered when your application is in foreground as described enter link description here. So if you don't override onMessageReceived, you will not receive push when your app is in foreground
2- According to fcm docs, when your app is in background, onMessageReceived is not triggered but
the data payload is delivered in the extras of the intent of your launcher Activity.
It explains why your push redirects to your main activity (your launcher).
So far, you can handle the redirection from the intent.
You can also specify the activity where it sould be redirected like enter link description here:
{
"to":"some_device_token",
"content_available": true,
"notification": {
"title": "hello",
"body": "test message",
"click_action": "OPEN_ACTIVITY_1"
},
"data": {
"extra":"juice"
}
}
don't forget intent filter for the desired activity:
<intent-filter>
<action android:name="OPEN_ACTIVITY_1" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
Also add Tasks permission in manifest.
private boolean isAppForeground() {
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses == null) {
return false;
}
final String packageName = getPackageName();
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
return true;
}
}
return false;
}
if(isAppForeground()){
// Handle notification silently without displaying in notification tray
}else{
// Do your regular stuff
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
showNotification(remoteMessage.getData().get("name"), (remoteMessage.getData().get("click_action")), remoteMessage.getData().get("title"));
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
}
}
I don't know what has gone wrong, but I'm having a difficult time with this one. The program is supposed to show a toast once a message is received. I have tried adding the priority in the manifest file, but it doesn't work.
The manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.comfy.textforwarder">
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="24" />
<uses-permission-sdk-23 android:name="android.permission.SEND_SMS" />
<uses-permission-sdk-23 android:name="android.permission.READ_SMS" />
<uses-permission-sdk-23 android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<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">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Settings" />
<receiver
android:name=".MyReceiver"
android:enabled="false"
android:exported="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
Broadcast Receiver
public void onReceive(Context context, Intent intent) {
Log.d("RECEIVE", "Receiving SMS");
Bundle intentExtras = intent.getExtras();
if(intentExtras != null){
Object[] sms = (Object[]) intentExtras.get("pdus");
String msgStr = "";
for(int i = 0; i < sms.length; ++i){
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);
String smsBoddeh = smsMessage.getMessageBody().toString();
String addr = smsMessage.getOriginatingAddress();
msgStr += "SMS From " + addr + "\n";
msgStr += smsBoddeh + "\n";
}
Toast.makeText(context.getApplicationContext(), msgStr, Toast.LENGTH_SHORT).show();
Log.d("RECEIVE", msgStr);
}
}
Try enabling the same..
<receiver
android:name="com.smsforwarder.smsforwarder.SMSReceiver"
**android:enabled="true">**
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
I am doing a chat application . In the app i have to do chatting with help of push notifications using parse andorid sdk. I am successfull to generate push notications between different users . But not able to recieve push and add their data in list view . Here is code of maifest file
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:name="example.chat.ChatApplication"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.facebook.LoginActivity"
android:label="#string/app_name" />
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/app_id" />
<activity
android:name="example.chat.LoginActivity"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="example.chat.FriendslIst"
android:label="Friend list"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="example.chat.RegisterActivity"
android:label="#string/title_activity_register"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="example.chat.FriendListActivity"
android:label="#string/title_activity_friend_list"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="example.chat.ChatActivity"
android:label="#string/title_activity_chat"
android:screenOrientation="portrait" >
</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.RECEIVE_BOOT_COMPLETED" />
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>
<receiver android:name="example.chat.MyCustomReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.USER_PRESENT" />
<action android:name="example.chat.UPDATE_STATUS" />
</intent-filter>
</receiver>
</application>
and code for my custom reciever
public class MyCustomReceiver extends BroadcastReceiver {
private static final String TAG = "MyCustomReceiver";
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, ""+intent, Toast.LENGTH_LONG).show();
}
}
and from java code I am sending push like this :
ParseQuery<ParseInstallation> query = ParseInstallation.getQuery();
query.whereEqualTo("device_id", target);
ParsePush push = new ParsePush();
push.setQuery(query);
push.setMessage(message);
push.setExpirationTimeInterval(86400);
push.sendInBackground();
Please tell me where I am wrong for recieving data using reciever and what to do when i recive push means any logic or idea to move further . Thanks in advance
here is the manifiest file.....
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="your package name"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="16" />
<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" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="your package name.YourActivity"
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.RECEIVE_BOOT_COMPLETED" />
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>
<receiver android:name="your package name.YourCustomReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.USER_PRESENT" />
<action android:name="your package name.UPDATE_STATUS" />
</intent-filter>
</receiver>
</application>
</manifest>
use this code to receive the push...
public class MyCustomReceiver extends BroadcastReceiver {
String title, from, msg;
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
String message = extras != null ? extras.getString("com.parse.Data")
: "";
Log.e("message ", " " + message);
JSONObject jObject;
try {
if (message != null && !message.equals("")) {
jObject = new JSONObject(message);
from = jObject.getString("from");
msg = jObject.getString("title");
title = jObject.getString("msg");
GCMMessage gcmMessage = new GCMMessage();
gcmMessage.setMsg_body(msg);
gcmMessage.setMsg_title(title);
gcmMessage.setType(0);
gcmMessage.setDateTime(time);
DatabaseUtil.insertMessage(context, gcmMessage);
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}
and here is the code to send push...
JSONObject obj;
try {
obj =new JSONObject();
obj.put("alert","oman expert ");
obj.put("action","Your Package name.UPDATE_STATUS");
data.put("from", ParseUser.getCurrentUser().getUsername());
obj.put("msg","hi");
obj.put("title","msg");
ParsePush push = new ParsePush();
ParseQuery query = ParseInstallation.getQuery();
push.setQuery(query);
push.setData(obj);
push.sendInBackground();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for any further query please let me know....
In the above code example, you have missed out few things,
Check your AndroidManifest.xml file, and add c2dm permissions,
permission android:name="your package.permission.C2D_MESSAGE" android:protectionLevel="signature"
uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"
uses-permission android:name="your package.permission.C2D_MESSAGE"
While sending the data, set the action in your data,
JSONObject data = new JSONObject();
try {
data.put("action", "your package.GOT_MESSAGE");
data.put("ya", ya);
data.put("from", ParseUser.getCurrentUser().getUsername());
}catch (Exception e){
e.printStackTrace();
return;
}
ParsePush parsePush = new ParsePush();
parsePush.setData(data);
The problem is only with android 2.3.6 .
With 4.x, there isn't any problem, the receiver it's ok.
I have received the registration ID with 2.3.6 but the messages are never received.
My Manifest is:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.arte.bilunaā€¯
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE" />
<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" />
<permission
android:name="net.arte.biluna.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="net.arte.biluna.permission.C2D_MESSAGE" />
<application
android:name="net.arte.biluna.businesslogic.CosmoApplication"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/Theme.Sherlock.Light" >
<!-- android:theme="#style/Theme.Sherlock" > -->
<activity
android:name="net.arte.biluna.SplashScreen"
android:label="#string/app_name"
android:launchMode="singleTask"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="net.arte.biluna.GreatestActivity"
android:screenOrientation="portrait" />
<activity
android:name="net.arte.biluna.LogInActivity"
android:screenOrientation="portrait" />
<activity
android:name="net.arte.biluna.HomePage"
android:screenOrientation="portrait" />
<activity
android:name="net.arte.biluna.LiveTourActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateHidden" />
<activity
android:name="net.arte.biluna.ChatActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateHidden" />
<activity
android:name="net.arte.biluna.ForYouActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateHidden" />
<activity
android:name="net.arte.biluna.StoreActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateHidden" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<service android:name="net.arte.biluna.GcmIntentService" />
<receiver
android:name="net.arte.biluna.GcmBroadcastReceiver"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="net.arte.biluna" />
</intent-filter>
</receiver>
</application>
My receiver:
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
GcmIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
my activity:
...
if (checkPlayServices()) {
gcm = GoogleCloudMessaging.getInstance(this);
regid = getRegistrationId(context);
if (regid.equals("")) {
registerInBackground();
}
}
...
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
finish();
}
return false;
}
return true;
}
Check the Google play services version number and there is a pretty defined method to check Google play services a availability
Latest release of gcm using google play is very easy to implement and can be used for longer time.
See this tutorial. Hope it might help.
http://techlovejump.in/2013/11/android-push-notification-using-google-cloud-messaging-gcm-php-google-play-service-library/