Hello community I have the following problem.
My manifest file looks like the following.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.someCo.test"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.location.network" />
<uses-feature android:name="android.hardware.location.gps" />
<uses-feature android:name="android.hardware.wifi" />
<uses-sdk android:minSdkVersion="8" />
<application android:icon="#drawable/ic_launcher" android:label="#string/app_name" >
<service android:name = ".BackgroundService" android:exported="true" />
</application>
</manifest>
my Activity's onCreate has the following line of code.
this.context.startService(new Intent(this.context, com.someCo.test.BackgroundService.class));
this.context.bindService(new Intent(this.context, com.someCo.test.BackgroundService.class), serviceConnection, Context.BIND_AUTO_CREATE);
my Activity also has the following private class.
private ServiceConnection serviceConnection = new ServiceConnection() {
public static final String TAG = "Service Connection Class";
public void onServiceConnected(ComponentName className, IBinder service) {
try {
com.someCo.test.BackgroundService.MyBinder binder = (com.someCo.test.BackgroundService.MyBinder)service;
backgroundService = binder.getService();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//backgroundService = ((BackgroundService.MyBinder) service).getService();
//Toast.makeText(context,"service connected", Toast.LENGTH_LONG);
Log.i(TAG, "onServiceConnected");
}
//#Override
public void onServiceDisconnected(ComponentName className) {
backgroundService = null;
}
};
my Service has the following.
private final IBinder binder = new MyBinder();
public class MyBinder extends Binder{
private static final String TAG = "MyBinder";
BackgroundService getService(){
Log.i(TAG, "get service");
return BackgroundService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Log.i(TAG, "onBind destroyed");
return binder;
}
#Override
public boolean onUnbind(Intent intent) {
Log.i(TAG, "onUnbind destroyed");
return super.onUnbind(intent);
}
At this line I get the exception below the code.
(com.someCo.test.BackgroundService.MyBinder)service;
backgroundService = binder.getService();
java.lang.classCastException: android.os.BinderProxy.
Could someone kindly point me to my mistake, I can't seem to figure it out. Please forgive the very verbose code, as I was trying to be as explicit as possible in debugging this problem.
Thanks,
I don't know why you have written the code for start Service using both way(StartService and BindService)?
Here is the example for the Bind Service. you can refer this blog.
I have tried this thing my self several times. But from my experience, if you just need to bind the service to get some data from the service, there is no need to do so.
Just use localbroadcastmanager. It is sufficient to send the data from the service to application. It is quite easy, safe, less prone to memory leaks.
Related
I am trying to record the audio via Accessibility as In Android developer Documentation mentioned
"The app can capture audio if it is an accessibility service."
Below is my code For Accessibility Service :
public class MyAccessibilityService extends AccessibilityService {
private static final String TAG="MyAccessibilityService";
public static final String START_RECORDING="START_RECORDING";
public static final String STOP_RECORDING="STOP_RECORDING";
private Context context;
MediaRecorder recorder;
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG,"MyAccessibilityService Salesken Started ...");
context=this;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
String action = intent.getAction();
switch (action) {
case START_RECORDING:
Log.d(TAG,"Start Recording");
String contact = intent.getStringExtra("contact");
startRecorder(contact);
break;
case STOP_RECORDING:
Log.d(TAG,"Stop Recording");
stopRecorder();
break;
}
}
return super.onStartCommand(intent, flags, startId);
}
private void stopRecorder() {
if(recorder != null){
recorder.stop();
recorder.release();
}
}
private void startRecorder(String contact) {
String timestamp = new SimpleDateFormat("dd-MM-yyyy-hh-mm-ss", Locale.US).format(new Date());
String fileName =contact +"-"+timestamp+".pcm";
MediaSaver mediaSaver = new MediaSaver(context).setParentDirectoryName("AudioRecording").
setFileNameKeepOriginalExtension(fileName).
setExternal(MediaSaver.isExternalStorageReadable());
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(mediaSaver.pathFile().getAbsolutePath());
try {
recorder.prepare();
} catch (IOException e) {
e.printStackTrace();
}
recorder.start();
}
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
}
#Override
public void onInterrupt() {
}
#Override
public void onDestroy() {
super.onDestroy();
stopRecorder();
}
}
Every time when i call START_RECORDING to my Accessibility Service i am getting below exception in the service
java.lang.RuntimeException: start failed.
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4222)
at android.app.ActivityThread.access$2100(ActivityThread.java:231)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1984)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Caused by: java.lang.RuntimeException: start failed.
at android.media.MediaRecorder.native_start(Native Method)
I have below mention permission in my Manifest :
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.MANAGE_OWN_CALLS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
I am not sure how to use AudioManager.AudioRecordingCallback on the AudioRecord or MediaRecorder so that it can capture Voice Call Audio.
MediaRecorder.AudioSource.VOICE_CALL for system apps.
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
Capturing from VOICE_CALL source requires the Manifest.permission.CAPTURE_AUDIO_OUTPUT permission. This permission is reserved for use by system components and is not available to third-party applications.
VOICE_CALL Documentation
You can use VOICE_RECOGNITION source after activate Accesibility Service.
However, it will still not work in some countries or some physical devices. There are legal issues, so Samsung, Huawei, Xiaomi will act differently.
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_RECOGNITION);
I have a project that was working in API 14. Now I am moving to API 21 so I am making the changes I need to.
It is an app that uses location to track a route. I have a service that takes care of the location stuff. But when I try to bind to that service it keeps coming back false and I cant figure out why.
Below is my code. I dont even know how to start looking at this really. What reasons could there be for the Service not binding?
Below is my code:
Service Connection class
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the object we can use to
// interact with the service. We are communicating with the
// service using a Messenger, so here we get a client-side
// representation of that from the raw IBinder object.
mServiceMessenger = new Messenger(service);
// Now that we have the service messenger, lets send our messenger
Message msg = Message.obtain(null, LOCATION_CHANGED, 0, 0);
msg.replyTo = mClientMessenger;
/*
* In case we would want to send extra data, we could use Bundles:
* Bundle b = new Bundle(); b.putString("key", "hello world");
* msg.setData(b);
*/
try {
mServiceMessenger.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
mBound = true;
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
mServiceMessenger = null;
mBound = false;
}
};
bindService method call - val is always false
public boolean bindService() {
/*
* Note that this is an implicit Intent that must be defined in the
* Android Manifest.
*/
Intent i = new Intent();
i.setPackage("com.example.conor.routetracker.ACTION_BIND");
boolean val = getBaseContext().getApplicationContext().bindService(i, mConnection,
Context.BIND_AUTO_CREATE);
return val;
}
Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<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>
<service
android:name="com.example.conor.routetracker.GPSService"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="com.example.conor.routetracker.ACTION_BIND" />
</intent-filter>
</service>
<activity
android:name="com.example.conor.routetracker.ListFiles"
android:label="#string/title_activity_list_files" >
</activity>
</application>
One line change saves the day.
When I create my Intent it should be
Intent i = new Intent(getApplicationContext(), GPSService.class);
public boolean bindService() {
Intent i = new Intent("com.example.conor.routetracker.ACTION_BIND");
i.setPackage("com.example.conor.routetracker")
return getBaseContext().getApplicationContext().bindService(i, mConnection, Context.BIND_AUTO_CREATE);
}
I am following the tutorial from Bound service : http://developer.android.com/guide/components/bound-services.html and use it in my code. But when I use the code from the tutorial I get an error at this line : service = binder.getService(); cannot convert from localService to IBinder. So as a solution I cast it to IBinder. But I get a classCastException then when I start running the app.
This is the code from the MainActivity :
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
LocalBinder binder = (LocalBinder) service;
service = (IBinder) binder.getService();
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
#Override
protected void onStart() {
super.onStart();
// Bind to LocalService
Intent intent = new Intent(this, LocalService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onStop() {
super.onStop();
// Unbind from the service
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
The code in my service looks like this :
public class LocalService extends Service implements LocationListener,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener, SensorEventListener {
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
LocalService getService() {
// Return this instance of LocalService so clients can call public methods
return LocalService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
}
And my manifest file looks like this :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.geotodo"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!-- Required for accessing our current location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="#drawable/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>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="KEY"/>
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<service android:enabled="true" android:name=".LocalService" />
</application>
Please help someone.
Use:
service = (LocalService) binder.getService();
... instead of:
service = (IBinder) binder.getService();
You are calling a Service object and trying to type cast it to a IBinder object it is giving to a ClassCastException.
I have to schedule invoking of an already install test project on the device after 10 sec once the button is click. For that I have created an AlarmReceiver and my TaskService which actually is invoking the test project.
After running the app, nothing happens after the button is clicked. I don't know what is wrong but service doesn't performs the job even after 10 sec.
Below is my code which I am trying. The Activity class:
// Create an anonymous implementation of OnClickListener
private OnClickListener HTListener = new OnClickListener() {
public void onClick(View v) {
btnStartSchedule(v);
}
};
public void btnStartSchedule(View v) {
try {
AlarmManager alarms = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), AlarmReceiver.class);
intent.putExtra(AlarmReceiver.ACTION_ALARM, AlarmReceiver.ACTION_ALARM);
final PendingIntent pIntent = PendingIntent.getBroadcast(this, 1234567, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarms.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 10000, pIntent);
Toast.makeText(ScrapeActivity.this, "Alarm Started", Toast.LENGTH_LONG).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The AlarmReceiver class :
public class AlarmReceiver extends BroadcastReceiver {
public static String ACTION_ALARM = "com.alarmmanager.alarm";
#Override
public void onReceive(Context context, Intent intent) {
Log.i("Alarm Receiver", "Entered");
Toast.makeText(context, "Entered", Toast.LENGTH_SHORT).show();
Bundle bundle = intent.getExtras();
String action = bundle.getString(ACTION_ALARM);
if (action.equals(ACTION_ALARM)) {
Log.i("Alarm Receiver", "If loop");
Intent inService = new Intent(context, LaunchService.class);
context.startService(inService);
} else {
Log.i("Alarm Receiver", "Else loop");
Toast.makeText(context, "Else loop", Toast.LENGTH_SHORT).show();
}
}
}
And finally the LaunchService class:
public class LaunchService extends IntentService {
public LaunchService(String name) {
super(name);
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent intent) {
Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.my.testproject");
startActivity(LaunchIntent);
}
}
I have also mention the receiver and service inside the manifest file :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.my.pb.activity"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/PB_APP"
android:theme="#style/AppTheme" >
<activity
android:name="com.my.pb.activity.ScrapeActivity"
android:label="#string/PB_APP" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".AlarmReceiver"
android:process=":remote" >
</receiver>
<service android:name=".LaunchService" >
</service>
</application>
I don't understand whats the issue coz there's no exception in the Logcat. As I click the button, i just see the toast message saying Alarm Started. Please help.
You have a typo at the Manifest, you declared AlaramReceiver instead of .AlarmReceiver there.
I am new to Android. I am trying to send message (GCM) from my server (Java) to android phone. On debugging the server code, I found that the messages are successfully sent to android phones. But I was not able to receive any messages in phone. I tried to have a break-point in onMessage(), but there was no use.
Once after the every message from server, my phone is only getting an alert box something like: "PROJECT is not responding. Would you like to close it?" It has 2 buttons in the alert box: wait and OK.
Can anyone please help me on this. Even though, my server sent messages successfully, Why I was not receiving any messages in phone. My client and server code are as follows:
Server:
public void sendPushNotification(String theRegistrationId, String thePushMsg)
{
//Used to transmit messages to the Google Cloud Messaging service.
Sender aGcmSender = new Sender(API_KEY);
//Constructing message which need to be transmitted to android device.
Message aMessage = new Message.Builder().addData("message", thePushMsg).build();
try
{
Result result = aGcmSender.send(aMessage, theRegistrationId, 1);
}
catch (Exception theException)
{
}
}
Client:
AndroidManifest.xml:
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<permission android:name="com.test.app.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="com.test.app.permission.C2D_MESSAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<!-- App receives GCM messages. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.READ_OWNER_DATA" />
<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- Permission to vibrate -->
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.SET_DEBUG_APP"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<application
android:icon="#drawable/icon"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:name="MyApplication">
<uses-library android:name="com.google.android.maps" />
<activity
android:name=".view.welcome.WelcomeView"
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>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.test.app" />
</intent-filter>
</receiver>
<service android:name="com.test.app.GCMIntentService" />
</application>
GCMIntentService:
package com.test.app;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.google.android.gcm.GCMBaseIntentService;
public class GCMIntentService extends GCMBaseIntentService
{
private static final String TAG = "===GCMIntentService===";
private static String GCM_SENDER_ID = "697532398835"; //Project id in Google API Console
public GCMIntentService()
{
super(GCM_SENDER_ID);
Log.d(TAG, "GCMIntentService init");
}
#Override
protected void onRegistered(Context theContext, String theRegistrationId)
{
Log.i(TAG, "Device registered: regId = " + theRegistrationId);
}
#Override
protected void onUnregistered(Context theContext, String theArg)
{
Log.i(TAG, "unregistered = "+theArg);
}
#Override
protected void onMessage(Context theContext, Intent theIntent)
{
Log.i(TAG, "new message= ");
String aMessage = theIntent.getStringExtra("message");
sendGCMIntent(theContext, aMessage);
}
private void sendGCMIntent(Context theContext, String theMessage)
{
Intent aBroadcastIntent = new Intent();
aBroadcastIntent.setAction("GCM_RECEIVED_ACTION");
aBroadcastIntent.putExtra("gcm", theMessage);
theContext.sendBroadcast(aBroadcastIntent);
}
#Override
protected void onError(Context theContext, String theErrorId)
{
Log.i(TAG, "Received error: " + theErrorId);
}
#Override
protected boolean onRecoverableError(Context theContext, String theErrorId)
{
return super.onRecoverableError(theContext, theErrorId);
}
}
My activity:
package com.test.app.view.welcome;
import java.net.MalformedURLException;
import java.net.URL;
import com.google.android.gcm.GCMRegistrar;
public class LoginView extends Activity implements Runnable {
Typeface itsTypeFace;
IntentFilter gcmFilter;
String broadcastMessage = "No broadcast message";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.login);
gcmFilter = new IntentFilter();
gcmFilter.addAction("GCM_RECEIVED_ACTION");
}
private BroadcastReceiver gcmReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
broadcastMessage = intent.getExtras().getString("gcm");
if (broadcastMessage != null)
{
System.out.println(broadcastMessage);
}
}
};
/**
* Method to avoid back key press for a higher api level 2.0 and above
*/
#Override
public void onBackPressed() {}
/** If the user changes the orientation of his phone, the current activity
is destroyed, and then re-created. This means that our broadcast message
will get wiped out during re-orientation.
So, we save the broad cast message during an onSaveInstanceState()
event, which is called prior to the destruction of the activity.
*/
#Override
public void onSaveInstanceState(Bundle savedInstanceState)
{
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("BroadcastMessage", broadcastMessage);
}
/** When an activity is re-created, the os generates an onRestoreInstanceState()
event, passing it a bundle that contains any values that you may have put
in during onSaveInstanceState()
We can use this mechanism to re-display our last broadcast message.
*/
#Override
public void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
broadcastMessage = savedInstanceState.getString("BroadcastMessage");
}
/** If our activity is paused, it is important to UN-register any
broadcast receivers.
*/
#Override
protected void onPause()
{
unregisterReceiver(gcmReceiver);
super.onPause();
}
/** When an activity is resumed, be sure to register any
broadcast receivers with the appropriate intent
*/
#Override
protected void onResume()
{
super.onResume();
registerReceiver(gcmReceiver, gcmFilter);
}
/**
* The call to GCMRegistrar.onDestroy()
*/
#Override
public void onDestroy()
{
GCMRegistrar.onDestroy(this);
super.onDestroy();
}
}
Can anyone please help me on this issue. Even though, my server sent messages successfully, Why I was not receiving any messages in phone.
I found a solution for this problem. On deploying my application (server side), I found there was some problem with json-simple.jar.
I have upgraded the jar to json-simple-1.1.1.jar and it worked!
And also as NickT suggested, I have updated my canonicalid as follows:
Sender aGcmSender = new Sender(API_KEY);
//Constructing message which need to be transmitted to android device.
Message aMessage = new Message.Builder().addData("message", thePushMsg).build();
Result result = aGcmSender.send(aMessage, REG_ID, 1); //Transmitting message to android device
if(result != null)
{
if(result.getMessageId() != null)
{
String aCanonicalRegistrationId = result.getCanonicalRegistrationId();
if(aCanonicalRegistrationId != null)
{
//Updated my database with aCanonicalRegistrationId (replaced REG_ID)
}
}
else
{
String error = result.getErrorCodeName();
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister database
}
}
}
}
Thank You.