How to implement Push Notifications in Android - java

I am trying from more than a day to implement a simple PUSH notification using gcm, but unable to implement it.
When ever I am adding this permission
<permission android:name="Android.Test.permission.C2D_MESSAGE" android:protectionLevel="signature" />
I get this error message while debugging via mobile device
pkg: /data/local/tmp/Android.Test
Failure [INSTALL_PARSE_FAILED_MANIFEST_MALFORMED]
Can somebody suggest me what I am doing. for further help I am putting my whole manifest.xml file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="Android.Test"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="14"/>
<permission android:name="Android.Test.permission.C2D_MESSAGE" android:protectionLevel="normal" />
<uses-permission android:name="Android.Test.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<application android:label="#string/app_name" android:icon="#drawable/ic_launcher">
<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>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="Android.Test" />
</intent-filter>
</receiver>
<service android:name=".GCMIntentService" />
</application>
</manifest>
Edit 1:
This is how I am trying to send the message from C# to my android device.....I found this code from the blog.
private string SendGCMNotification(string apiKey, string postData, string postDataContentType = "application/json")
{
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateServerCertificate);
//
// MESSAGE CONTENT
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
//
// CREATE REQUEST
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
Request.Method = "POST";
Request.KeepAlive = false;
Request.ContentType = postDataContentType;
Request.Headers.Add(string.Format("Authorization: key={0}", apiKey));
Request.ContentLength = byteArray.Length;
Stream dataStream = Request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
//
// SEND MESSAGE
try
{
WebResponse Response = Request.GetResponse();
HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
{
var text = "Unauthorized - need new token";
}
else if (!ResponseCode.Equals(HttpStatusCode.OK))
{
var text = "Response from web service isn't OK";
}
StreamReader Reader = new StreamReader(Response.GetResponseStream());
string responseLine = Reader.ReadToEnd();
Reader.Close();
return responseLine;
}
catch (Exception e)
{
}
return "error";
}
This is what I am getting in the responseLine code
{"multicast_id":7357801824672,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
Thanks

try this one
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="16"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<permission
android:name="com.google.android.gcm.demo.app.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission
android:name="com.google.android.gcm.demo.app.permission.C2D_MESSAGE" />
<!-- This app has permission to register and receive data message. -->
<uses-permission
android:name="com.google.android.c2dm.permission.RECEIVE" />
<!-- Main activity. -->
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".MainActivity"
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>
<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="Android.Test" />
</intent-filter>
</receiver>
<service android:name=".GCMIntentService" />
</application>

Your response code contains the answer, you are passing invalid registration_ids
"results":[{"error":"InvalidRegistration"}]
Sample php code:
$postdata = array(
'registration_ids' => array('your_device_registration_key'),
'data' => 'message'
);
$headers = array(
'Authorization: key=' . YOUR_API_KEY,
'Content-Type: application/json'
);

Related

Download unsuccessful - Kotlin

I'm new to Kotlin and I'm creating a project. My task is to download audio (mp3 format). I'm not getting any errors in logcat but when trying to download audio getting "Download unsuccessful". Here is my AsyncTask file:
class DownloadAudioFromUrl(val context: Context, val audio: Audio) {
#RequiresApi(Build.VERSION_CODES.O)
fun download() {
try {
val audioName = audio.title + LocalDateTime.now() + ".mp3"
val downloadManager = context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val uri = Uri.parse(audio.filePath)
val request = DownloadManager.Request(uri)
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI)
.setTitle(audio.title)
.setDescription("Downloading: " + audio.title)
.setAllowedOverMetered(true)
.setAllowedOverRoaming(true)
.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, audioName)
downloadManager.enqueue(request)
} catch (e: Exception) {
println("Error downloading: $e")
}
}
}
curPlayingAudio is not null.
Here is my Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.daniil_holdings.soundy">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<application
android:usesCleartextTraffic="true"
android:name=".SoundyApplication"
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.NoActionBar">
<service android:name=".exoplayer.MusicService">
<intent-filter>
<action android:name="android.media.browse.MediaBrowserService" />
</intent-filter>
</service>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/res"/>
</provider>
<activity android:name=".ui.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Android Studio: cannot resolve getApplication() [duplicate]

This question already has answers here:
How to get application object into fragment class
(6 answers)
Closed 5 years ago.
I am trying to access the global variable declared in AndroidManifest.xml in UARTlogfragment.java but there is an error in the use of getApplication() i.e. "cannot resolve".
I am posting my Androidmanifest.xml and the UARTlogfragment.java here.
The AndroidManifest.xml is:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.NFC" />
<uses-permission android:name="no.nordicsemi.android.LOG" />
<uses-feature
android:name="android.hardware.bluetooth_le"
android:required="true" />
<!-- 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" />
<application
android:name=".ToolboxApplication"
android:allowBackup="true"
android:fullBackupContent="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:theme="#style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name=".SplashscreenActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.Fullscreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.shortcuts"
android:resource="#xml/shortcuts" />
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="application/vnd.no.nordicsemi.type.app" />
<data android:mimeType="application/vnd.no.nordicsemi.type.address" />
</intent-filter>
</activity>
<!-- Template plugin activities -->
<!-- Remember to add your plug-in Activities to the Android Manifest file. -->
<!-- Plug-in activities -->
<activity
android:name=".FeaturesActivity"
android:label="#string/app_name"
android:launchMode="singleTask"
android:theme="#style/AppTheme.TranslucentStatusBar" />
<activity
android:name=".uart.UARTActivity"
android:icon="#drawable/ic_uart_feature"
android:label="#string/uart_feature_title"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="no.nordicsemi.android.nrftoolbox.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".proximity.ProximityService"
android:label="#string/proximity_feature_title" />
<service
android:name=".dfu.DfuService"
android:exported="true"
android:label="#string/dfu_service_title">
<intent-filter>
<action android:name="no.nordicsemi.android.action.DFU_UPLOAD" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</service>
<activity
android:name=".dfu.DfuInitiatorActivity"
android:label="#string/dfu_service_title"
android:noHistory="true"
android:theme="#style/AppTheme.Translucent">
<intent-filter>
<action android:name="no.nordicsemi.android.action.DFU_UPLOAD" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<service
android:name=".cgms.CGMService"
android:label="#string/cgms_feature_title" />
<service
android:name=".rsc.RSCService"
android:label="#string/rsc_feature_title" />
<service
android:name=".csc.CSCService"
android:label="#string/csc_feature_title" />
<service
android:name=".hts.HTSService"
android:label="#string/hts_feature_title" />
<service
android:name=".uart.UARTService"
android:label="#string/uart_feature_title" />
<service android:name=".wearable.MainWearableListenerService">
<intent-filter>
<action android:name="com.google.android.gms.wearable.DATA_CHANGED" />
<action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />
<data
android:host="*"
android:pathPrefix="/nrftoolbox"
android:scheme="wear" />
</intent-filter>
</service>
<provider
android:name=".uart.UARTLocalLogContentProvider"
android:authorities="no.nordicsemi.android.nrftoolbox.uart.log"
android:exported="true" />
<activity
android:name=".Register_Page"
android:label="#string/title_activity_register__page" />
<activity android:name=".View_Profile" />
<activity android:name=".Profile" />
<activity android:name=".Wallet_Page" />
<activity android:name=".confirm_booking" />
<activity android:name=".LoginActivity" />
<activity android:name=".Add_Amount" />
<activity android:name=".last_step_book"></activity>
</application>
The UARTlogfragment.java(where I am trying to access the global variable) is :
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_feature_uart_log, container, false);
mydb = new no.nordicsemi.android.nrftoolbox.myDbAdapter(getContext());
String s = ((ToolboxApplication) this.getApplication()).getSomeVariable();
Cursor rs = mydb.getData(1);
rs.moveToFirst();
String nam = rs.getString(rs.getColumnIndex(no.nordicsemi.android.nrftoolbox.myDbAdapter.CONTACTS_COLUMN_NAME));
String phon = rs.getString(rs.getColumnIndex(no.nordicsemi.android.nrftoolbox.myDbAdapter.CONTACTS_COLUMN_PHONE));
String emai = rs.getString(rs.getColumnIndex(no.nordicsemi.android.nrftoolbox.myDbAdapter.CONTACTS_COLUMN_EMAIL));
String cit = rs.getString(rs.getColumnIndex(no.nordicsemi.android.nrftoolbox.myDbAdapter.CONTACTS_COLUMN_CITY));
String gend = rs.getString(rs.getColumnIndex(no.nordicsemi.android.nrftoolbox.myDbAdapter.CONTACTS_COLUMN_GENDER));
String pas = rs.getString(rs.getColumnIndex(no.nordicsemi.android.nrftoolbox.myDbAdapter.CONTACTS_COLUMN_PASS));
String dobb = rs.getString(rs.getColumnIndex(no.nordicsemi.android.nrftoolbox.myDbAdapter.CONTACTS_COLUMN_DOB));
if (!rs.isClosed()) {
rs.close();
}
final EditText field = mField = view.findViewById(R.id.field);
mField.setText(nam+" "+emai+" "+phon+" "+gend+" "+cit);
field.setOnEditorActionListener((v, actionId, event) -> {
if (actionId == EditorInfo.IME_ACTION_SEND) {
onSendClicked();
return true;
}
return false;
});
final Button sendButton = mSendButton = view.findViewById(R.id.action_send);
sendButton.setOnClickListener(v -> onSendClicked());
return view;
}
What is the error ?? And why cannot it resolve getApplication()??
Change
String s = ((ToolboxApplication) this.getApplication()).getSomeVariable();
to
String s = ((ToolboxApplication) getActivity().getApplication()).getSomeVariable();
As you are trying yo use application context from fragment you can not use getApplication() because isn't method of Fragment class
So you first have to use the getActivity() which will return a Fragment Activity to which the fragment is currently associated with.
to sumup in your code,
instead of this.getApplication() you have to use getActivity.getApplication()

Android BroadcastReceiver not detecting SMS

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>

android Implement chatting through push notification using parse.com api

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);

GCM no receive messages in 2.3.6 but it's ok in 4.1.2

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/

Categories