Android Push Notifications with GCM - java

I'm Developing a simple app that receives the GCM push messages from the PHP server. The App and Server works fine, even with multiple push messages. The only thing I want to add in the app is, If a push message is not received within few seconds, lets say 5seconds, i want my app to Toast a message saying "Network error". I'm using "WakefulBrodcastReceiver" for receiving the push messages. except for this, all code is working fine, as I expect it to.
Working:
Pressing a button notifies the server, that App is ready for receiving the notifications.
Now, i'm having two scenarios,
App haven't received any push message, 5 seconds are passed by since the button press event, SHOW THE TOAST.
I've already received few push messages, 5 seconds are passed by since i've received the last message, SHOW THE TOAST.
following code snippet is written in GCM Handler class, which handles the push messages.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Log.e("HANDLER", "inside run()");
Toast.makeText(mContext, "Network Error", 1000).show();
}
}, Constants.TIME_OUT);
The value of Constants.TIME_OUT is 5000,
the Toast or the Log never displayed.

All I wanted to do was, to show a "Check network connection" message if the app don't receive a Push notification from PHP server in 5 seconds.
as Udi I and Zharf stated, When onHandleIntent returns, the service Shuts down, and so does the delayed runnings. So, I tried the other way.
I used Timer Task.
The code is,
Timer timer;
TimerTask timerTask;
public static void startTimer(Context context) {
timer = new Timer();
initializeTimerTask(context);
timer.schedule(timerTask, 5000); //Time in miliSeconds
}
public static void stopTimer(){
if(timer != null)
timer.cancel();
timer = null;
}
public static void initializeTimerTask(final Context context){
timerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
Toast.makeText(context, "Check Network connection...", Toast.LENGTH_SHORT).show();
}
}
}
}
}

Related

I need to close a notification when the application is closed

I have this Runnable method which send a notification once it is called and every minute sends a JSON Post on an HTTP Server. So i coded the method "sendNotification" to keep informed the user regards the "service" is running but when I close the app, the method to send the JSON stops and the notification stays active on the notification bar. I would like to close the notification as well.
//Runnable methods for frequency position
private final Runnable oneMinuteRunnable = new Runnable() {
#Override
public void run() {
sendNotification();
getTimestamp();
new Thread(new Runnable() {
#Override
public void run() {
getLocation();
doPostRequest();
}
}).start();
handler.postDelayed(this, 60 * 1000);
}
};
This is the notification method
//Make notification when the frequency service is running
public void sendNotification() {
Notification notification = new NotificationCompat.Builder(this, com.example.httptracker.Services.Notification.NOTIFICATION_ID)
.setSmallIcon(R.drawable.ic_baseline_run_circle_24)
.setContentTitle("AMP Tracker")
.setContentText("Tracker is running")
.build();
compat.notify(1, notification);
}
I looked up online and I saw only solutions with a Service class but I would need to develop a "stop service" button to cancel the notification. But it is not what I need. The notification should disappear once the app is closed or the method killed.
Thanks in advance
try to cancel your notification with:
compat.cancel(1); // assuming compat is NotificationManager instance, 1 is your id
in e.g. onDestroy of Activity or any place when your app is stopping oneMinuteRunnable looped execution

I want to record a sound in android phone for 6 seconds with sampling rate of 8000hz in .wav

if(checkSelfPermissionFromDevice() )
{
btnRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pathSave= Environment.getExternalStorageDirectory()
.getAbsolutePath()+"/"
+ UUID.randomUUID().toString()+"_audio_record.wav";
mediaRecorder.setAudioChannels(1);
mediaRecorder.setAudioSamplingRate(8000);
mediaRecorder.setAudioEncodingBitRate(44100);
setupMediaRecorder();
try
{
mediaRecorder.prepare();
mediaRecorder.start();
}
catch (IOException e)
{
e.printStackTrace();
}
btnPlay.setEnabled(false);
btnStop.setEnabled(false);
Toast.makeText(MainActivity.this, "Recording...", Toast.LENGTH_SHORT).show();
//add delay of 6 seconds+then stop recording
//Toast.makeText(MainActivity.this, "Stopped Recording", Toast.LENGTH_SHORT).show();
//then enable play button()
btnPlay.setEnabled(true);
btnStop.setEnabled(false);
I want to add 6 seconds delay so that I can stop recording after that or only to record for 6 seconds using builtin function by passing parameters please guide...
You could use a android.os.Handler to run a some code with 6 seconds delay using the postDelayed function. Handler Documentation
Example code:
Handler h = new Handler();
h.postDelayed(() -> {
// stop the recording here
}, 6 * 1000);
A crucial point is, that you shouldn't pause the main thread for 6 seconds with something like Thread.sleep() because then the user experience would suffer and the android system will show a dialog that the app is unresponsive. Therefore you should schedule the stopping time (i.e. with a Handler) and let the main thread run in the mean time, such that the UI is updated and responsive.

How to trigger or send intent continously (without on button click)

I am tryiny to update my edittext in UI. I have a service from where I send a intent by clicking a button and update in the UI. Everything works fine. But I would like to send intent without button click.
What I tried was to put my Intent in a method and call it oncreate in service but even then it been just called once.
public class myService extends service {
onCreate{
sendMessage();
}
private void sendMessage(){
Intent intent = new Intent("com.example.app.SEND");
intent.putExtra("KEY", (String) Number);
sendBroadcast(intent);
}
When I do like this, I just send empty string which is not useful. And even then just once.
Can I send intent continously ? So that It updates my UI once it receives input ? Any possible way to do it ?
I would like to send intent every 5 seconds.
You can use TimerTask with IntentService for scheduled jobs.
ex:
Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
//some execution
}
};
timer.schedule(timerTask, 5000, 5000);

Is there a way to make my app activity go back to foreground after users inactivity?

As a Unity3D developer, I've created an application and exported it to Android Studio. My client is asking me to make this app go back to foreground after 10 seconds of user's inactivity (in case the user opens another app). I've tried to create a service that is started on the OnPause function of my UnityPlayerActivity. Then the service would detect the user's inactivity and launch my app again (putting it back to foreground). First I've only tried to use Time.Schedule to launch my app after 10 seconds no matter what, but everytime the application is paused (goes to background), it starts the service and then it crashes. The question is: is there a simple way to do this? I'm not an Android Java Developer (only know the basics) and I'm struggling with this part .
I'm trying to create this Service and then I try to start it from the onPause() function in my activity. When I pause the app on my phone the app crashes. Can anyone tell me if I'm on the right way and, please, help me?
public class ReturnToForeground extends Service {
public ReturnToForeground() {
}
// constant
public static final long NOTIFY_INTERVAL = 10 * 1000; // 10 seconds
// run on another Thread to avoid crash
private Handler mHandler = new Handler();
// timer handling
private Timer mTimer = null;
Intent intent = new Intent(this, UnityPlayerActivity.class);
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// cancel if already existed
if (mTimer != null) {
mTimer.cancel();
} else {
// recreate new
mTimer = new Timer();
}
// schedule task
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
return super.onStartCommand(intent, flags, startId);
}
class TimeDisplayTimerTask extends TimerTask {
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
// do action
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
startActivity(intent);
}
});
}
}
}
Make a timer for when the app is in the onPause(), when the timer reaches 10 seconds you should pass an intent which will make your app active again (let's say taking the user back to the main view). You can save the current data of your app in something like shared preffs, so that information wont be lost in most situations.
In many cases this problem appears when a resource which you are trying to reload is not active anymore inside the application.
From the info you have shared it seems like you are not starting the service correctly. It would be nice if you can add a crash log so that we can debug it and see where is the problem.

My app freezes after fullscreen application on front

I am struggling with persistent problem with Android app that has MQTT ServiceConnection running on background. When ever I switch to an other application that has fullscreen surface (game, youtube on fullscreen, etc) the application completely freezes when trying to bring it on front again. It even refuses to relaunch if closed from drawer. The app won't reopen unless completely killed. The weird thing is that if I run the application via debugger it works perfectly. It makes the problem difficult to get handle on. I have put on prints on beginning of each life cycle method, even before call to super class method. None of them get printed when the app hangs, which hints that it hangs some where on the system level.
Now if I call stopService at onStop method, it works fine but defeats the purpose of having persistent service on the background. I have called unbindService also on onStop, but it does not help. With all the other application everything works fine, even you tube as long as it is not used in fullscreen.
The dependency to the MQTT library is
compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.0.2'
and this is my onStop() method
#Override
protected void onStop() {
FirebaseUserActions.getInstance().end(getIndexApiAction0());
if(mBoundToService) {
try {
unbindService(serviceConnection);
mBoundToService = false;
}
catch (Exception e)
{
e.printStackTrace();
}
}
super.onStop();
}
And the onStart() method would be this:
#Override
protected void onStart() {
Log.d(TAG, "onStart has been called");
super.onStart();
if(!mBoundToService) {
bindService(mqttIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
FirebaseUserActions.getInstance().start(getIndexApiAction());
}
But this never gets called. From the logs I can see that MQTT service is receiving messages and produces no errors. Messages continue to be received even as the application is hanged so the background service is alive and running.
The inlined Service connection class is like this:
private ServiceConnection serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder binder)
{
mqttService = ((MQTTService.MyBinder) binder).getService();
mBoundToService = true;
Log.d(TAG,"MQTT service has been bound");
Handler handler = getHandler();
//NOTIFY THE LOGIN ACTIVITY THAT THE DATA HAS BEEN ACQUIRED
Message msg = handler.obtainMessage(Utils.HANDLE_MQTT_SERVICE_CONNECTED);
Bundle bundle = new Bundle();
bundle.putString(Utils.KEY_MQTT_SERVICE_BOUND,"Everything is complete");
msg.setData(bundle);
handler.sendMessage(msg);
}
#Override
public void onServiceDisconnected(ComponentName name) {
mBoundToService = false;
Log.d(TAG, "MQTT service has been UNbound");
}
};
The MQTT service is started like this from onCreate():
mqttIntent = new Intent(getApplicationContext(), MQTTService.class);
if(!mBoundToService){
Log.d(TAG,"Starting MQTT Intent");
startService(mqttIntent);
Log.d(TAG,"Binding MQTT Service");
bindService(mqttIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
Am I missing something that I should be doing at the onStop() to be able to resume the application after having fullscreen application on front?

Categories

Resources