How to handle events in Android application - java

I am going to implement a feature , where my application has to receive events of a camera from ( Event push server).
This server will push the events and my application has to receive and show in the notification bar.
e.g like the Facebook app or WhatsApp app, where in we receive the new message on the notification bar, even though the app is not in active state.
So to implement it:
What all pre requisetes i need. e.g information about the Event server?
Information on what protocol used in the server?
what is required on the Android side to implement this feature.
Please tell me how to proceed to implement on Android application side.

The programs like facebook using service to take events in background. Use JSON files for data interchange. Im using BroadcastReceiver to keep in touch with my activity. BroadcastReceiver its a very nice tool to communicate your service with activity.
Intent in = new Intent("SOMEACTION");
sendBroadcast(in);
Sending intent to you activity after handling response.
#Override
public void onResume() {
super.onResume();
// Register mMessageReceiver to receive messages.
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("my-event"));
}
// handler for received Intents for the "my-event" event
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Extract data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
};
#Override
protected void onPause() {
// Unregister since the activity is not visible
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onPause();
}

Related

Implementing exit app button in the persistent notification

My app runs a background service indicated by the persistent notification. Users need to use the toggle button in MainActivity to turn on/off this service and thus to remove the persistent notification.
Now I want to implement a notification action that can turn this service off & as well as the toggle within MainActivity. All in all, it should be an exit button to close my app and background service directly from the notification.
How do I achieve this?
note that I have two different java files, one for NotificationService
and the other is MainActivity. The toggle belongs to MainActivity.
edit: Is this okay to call System.exit(0) if I use pending intent with
BroadCastReceiver to exit from the app completely?
You have to use PendingIntent with BroadcastReceiver or Service to perform this. Here is an example of PendingIntent with BroadcastReciever.
Build a Notification
public static void createNotif(Context context){
Intent intentAction = new Intent(context,StopServerBroadcast.class);
//This is optional if you have more than one buttons and want to differentiate between two
intentAction.putExtra("action","actionName");
pIntent = PendingIntent.getBroadcast(context,1,intentAction,PendingIntent.FLAG_UPDATE_CURRENT);
drivingNotifBldr = (NotificationCompat.Builder) new NotificationCompat.Builder(context, CHANNEL_NAME)
.setSmallIcon(R.drawable.steeringwheel)
.setContentTitle("Stop Service")
.setContentText("Example Text")
.addAction(R.drawable.smallmanwalking, "On/off", pIntent)
.setOngoing(true);
...
}
Now the receiver which will receive this Intent
public class StopServerBroadcast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//Toast.makeText(context,"recieved",Toast.LENGTH_SHORT).show();
String action=intent.getStringExtra("action");
if(action.equals("action1")){
performAction1();
/*
Code that will stop your service
*/
}
}
}
Register Receiver in Manifest
<receiver
android:name=".StopServerBroadcast"
android:enabled="true" />

AlertDialog not appearing

this is my first time posting here. I'm new to Java & using the Android SDK, and thought I'd start off by trying to write a simple app to filter text messages for "scammy" keywords, for an Innovation module in school.
The app began off by showing a small toast whenever a keyword ("FREEBIE" etc.) is flagged, but I've been trying to make a more noticeable indicator, such as through alert dialogs.
Not sure what I've been doing wrong, but the alert isn't displaying when a message containing the keyword is sent through, but toasts work fine though. I thought it might be an issue with the context, so I've tried context/this/getActivityContext etc., but I receive a "Builder cannot be applied to com.example.myapp.ReceiveSms" error.
package com.example.myapp;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
public class ReceiveSms extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
Bundle bundle = intent.getExtras();
SmsMessage[] msgs;
if (bundle != null) {
try {
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
String msgFrom = msgs[i].getOriginatingAddress();
String msgBody = msgs[i].getMessageBody();
if (msgBody.matches(".*\\bFREEBIE\\b.*")) {
AlertDialog.Builder builder = new AlertDialog.Builder(context.getApplicationContext());
builder.setTitle("Scam Message");
builder.setMessage("Scam Message");
builder.setCancelable(true);
builder.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
Basicly you can not show dialog in broadcast receiver . See this link for more details , https://stackoverflow.com/a/8766864/1079842
The problem is with the context passed to the dialog as they can only be displayed within an activity.
new AlertDialog.Builder(context.getApplicationContext());
You need to specify the activity that the AlertDialog will appear over not the application context. It would look something like this:
new AlertDialog.Builder(YourActivityClass.this);
Since the dialog is being created from a receiver (not it's designated use case), one solution, but not recommended is to create an activity for this specific dialog.
show an alert dialog in broadcast receiver after a system reboot
Showing AlertDialog in a BroadcastReceiver is not allowed, this should only happen in a context of an Activity.
Instead of showing an AlertDialog, I'd recommend using showing notifications instead.
public class ReceiveSms extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent arg1) {
// Add your desired logic here whether to show or not the notification
showNotification(context);
}
private void showNotification(Context context) {
PendingIntent pIntent = PendingIntent.getActivity(
context, 0,
new Intent(context, MyActivity.class), 0);
NotificationCompat.Builder builder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.some.icon_here)
.setContentTitle("Your Notification Title")
.setContentText("Your Message");
builder.setContentIntent(pIntent);
builder.setAutoCancel(true);
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, builder.build()); // 1 denotes your notification id
}
}
This should help you further understand the alternatives on what you are trying to do.
Further reading
https://developer.android.com/training/notify-user/build-notification
ReceiveSms extends BroadcastReceiver
This is your BroadcastReceiver. BroadcastReceiver are defined for the purpose of getting system broadcasts on the different resources.
Example :
Internet is started by user
Sms is received
Call is coming
Sms has arrived
What is the BroadcastReceivers work
Just to let developers get the access to the triggers.
Why your Dialog alert not working, even if coded correctly ?
I will not correct the mistake in your dialog alert, As your programming approach is wrong. It is not working because, when the sms receives your app might be in foreground or background or nowhere.. And Even if present in background you needs to draw over other apps, permission.
When Dialog alert are used ?
Used in only when user is actively in the app and app is open in front of him. and not in Broadcastreceivers nor in the background. Broadcastreceivers works in background and you need to show System alert or a notification or simply a toast.
Remove your alertdialog and use below :
Toast.makeText(this, " SMS ARRIVED ", Toast.LENGTH_LONG).show();
Or
A System Alet
or
A Notification
Another problem in your approach :
You are not allowed to use READ_SMS or SEND_SMS or any SMS related operations as your app will be rejected if you tried to upload it on play store.
You need to use https://developers.google.com/identity/sms-retriever/user-consent/request
SMS-RETRIEVAR api for that purpose

Android Service to check whether the user screen on or off

Is there any way to create a service that runs forever on a background for Android user to check whether their screen on or off, etc?
I'm about to create an analytics, so I need to know when the user turn on or turn off their screen.
Thanks, I will appreciate all the input
You may use Android broadcast receiver to detect screen on and off.
Here is a good example of it
https://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/
you may also follow this thread
https://stackoverflow.com/a/9478013/2784838
You need to create broadcast receiver and manage screen on or off status.
Declare receiver in manifest:
<receiver android:name=".DeviceWakeUpReceiver" />
public class DeviceWakeUpReceiver extends BroadcastReceiver {
private static final String TAG = "DeviceWakeUpService";
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive() called");
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
//End service when user phone screen off
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
//Start service when user phone screen on
}
}
}
You cannot use a BroadcastReceiver for receiving screen off/on events.
Write a intent service which is started via boot complete listener and register for Intent.ACTION_SCREEN_OFF and Intent.ACTION_SCREEN_ON.
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
registerReceiver(new ScreenOffOnReceiver(), filter);
class ScreenOffOnReiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// Screen OFF
else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// Screen ON
}
}
}

Update textview of MainActivity from class that extends Service

I'm trying to create an android app that communicate with Bluetooth low energy module. I am able to connect to module, read data and so on. But the problem is i do not know how to update textview from class that extends Service (the one in which whole connection to BLE is going on). I know there is like BILLION or even more posts like these, but believe me i tried.
Here is MainActivity: http://pastebin.com/6yaP0dYM
and here is a class that extends Service: http://pastebin.com/cYuAUina
If someone could provide me some tips to solve my issue that would be more than great!
Create Broadcast Receiver and broadcast that in Service.
If your Activity is ope, register receiver and in onReceive() update the UI.
The receiver should be in the Activity...
Below is the working code
https://stackoverflow.com/a/14695943/1403112
You can get values through broadcast receiver......as follows, First create your own IntentFilter as,
Intent intentFilter=new IntentFilter();
intentFilter.addAction("YOUR_INTENT_FILTER");
Then create inner class BroadcastReceiver as,
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
/** Receives the broadcast that has been fired */
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction()=="YOUR_INTENT_FILTER"){
//HERE YOU WILL GET VALUES FROM BROADCAST THROUGH INTENT EDIT YOUR TEXTVIEW///////////
String receivedValue=intent.getStringExtra("KEY");
}
}
};
Now Register your Broadcast receiver in onResume() as,
registerReceiver(broadcastReceiver, intentFilter);
And finally Unregister BroadcastReceiver in onDestroy() as,
unregisterReceiver(broadcastReceiver);
Now the most important part...You need to fire the broadcast from wherever you need to send values..... so do as,
Intent i=new Intent();
i.setAction("YOUR_INTENT_FILTER");
i.putExtra("KEY", "YOUR_VALUE");
sendBroadcast(i);
....cheers :)

Broadcast Action: ACTION_CAMERA_BUTTTON

Is there any way after this action has been broadcast via a receiver to determine that the action has finished? i.e the user has exit camera mode and is doing something else?
You can register a broadcast receiver to receive this intent.
Note however that this intent will be broadcasted every time the user pushes the camera button, and is thus not directly related to any specific "action" (e.g. taking a photo).
BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// do whatever you want to do
}
};
registerReceiver(myReceiver, new IntentFilter(Intent.ACTION_CAMERA_BUTTON));
unregisterReceiver(myReceiver);
Is there any way after this action has been broadcast via a receiver to determine that the action has finished?
No. For starters, there may be no "action" to "finish", and there is no definition of "action".

Categories