I want to push data from device to device without web service, As like push notification. I want to push data which are more in size as compare to the notification and the data may be text or Json.Only that data should push from device to device with notification. When user click on the notification data gets display from device, don't want to fetch data after click on the notification with web server.Is it possible for this.I have 2 emulator.Here is my 2 Emulator Screen shot.
I have tried but the notification send my own emulator like green colour android icon on upper side on emulator, but how to send notification to second emulator.Can someone help me please.Thanks in advanced.
Here is my Activity code.
btnSubmitRequirment = (Button)findViewById(R.id.buttonSubmit_Order);
btnSubmitRequirment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String sms = "abcdefghijklmnopqrstuvwxyz this is SMS !!!!";
String phoneNo="15555215556";
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, sms, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",
Toast.LENGTH_LONG).show();
NotificationManager notifManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
long when = (long) 04.15;
Notification notif = new Notification(R.drawable.ic_launcher, sms, when );
Intent notifIntent = new Intent(context, Activity.class);
notifIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0, notifIntent, 0);
notif.setLatestEventInfo(context, "Order", sms, intent);
notif.flags |= Notification.FLAG_AUTO_CANCEL;
notifManager.notify(0, notif);
}
});
I think you want to develop a application like airdroid
https://play.google.com/store/apps/details?id=com.sand.airdroid&hl=en
As i know it set up small http server in one phone. And Send request from an another device. As you want. This sample help you to create such kind of http server. There is one restriction both device must be in same network.
https://github.com/NanoHttpd/nanohttpd.
Related
I'm sending firebase-messages using the firebase-console. The messages shall contain additional data like shown below with the purpose to open a specific URL within a webview in my app:
I set up my manifest and firebase class to get the messages. Within my firebase class I try to get the data:
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if(remoteMessage.getData().containsKey("key1")) {
intent.putExtra("destination", remoteMessage.getData().get("key1"));
}
PendingIntent pendingIntent = PendingIntent.getActivity
(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
String channelId = "default";
NotificationCompat.Builder builder;
if (remoteMessage.getNotification() != null ) {
if (remoteMessage.getNotification().getTitle() != null) {
builder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_stat_onesignal_default)
.setContentTitle(remoteMessage.getNotification().getTitle())
.setStyle(new NotificationCompat.BigTextStyle().bigText(remoteMessage.getNotification().getBody()))
.setAutoCancel(true)
.setContentIntent(pendingIntent);
} else {
builder = new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_stat_onesignal_default)
.setStyle(new NotificationCompat.BigTextStyle().bigText(remoteMessage.getNotification().getBody()))
.setAutoCancel(true)
.setContentIntent(pendingIntent);
}
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId, "default", NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(channel);
}
manager.notify(0, builder.build());
}
}
Within my MainActivity class I try to get the data. When the app is in the foreground, the following works (no matter what activity is opened, it will jump to the MainActivity and execute the following):
#Override
protected void onNewIntent(Intent intent) {
if (intent.getExtras() != null) {
Bundle extras = intent.getExtras();
if(extras.containsKey("destination")) {
Log.e("FIREBASE_CONTAINS", (String) extras.get("destination"));
}
}
}
But the event wont trigger if the app started from the background. I tried to get the intent and check for the key within the onResume() event of the activity, but it does not work (Same in inCreate() and onStart()).
Can anybody help me?
------------EDIT-----------------
As described in one of the comments, the problem seems to be that Notification-Messages won't reach the onMessageReceived() event. Apparently the firebase console can't send data-notifications (which would reach the event) so I tried using POSTMAN. I've read that I have to leave the notification tag out of the message body and put all my information in the data section. But if I do so, the messages won't reach my app (they do, when I add the notification section again, but of course they are not reaching the onMessageReceived() event in that case).
There are 3 types of push messages
notification
data
and both
A push messages is basically a json payload:
payload:{
notificacion...
data
}
Rules for each type of push messages are differente. In your case you are using the Firebase web console and adding custom data, which mean your payload will have notification and data.
For the combined type the behaviour in backgroun is to use a default notificacion (NotificationCompat, the visual kind) and open the default activity registered in the manifest. In the activity you can get the data.
Lets say your default activity is called MainActivity
public class MainActivity {
onCreate...{
//... usual stuff
Intent fcmIntent = getIntent();
if fcmIntent != null
//check the extras and forward them to the next activity if needed
}
}
There are two type of push message
(1)Notification Message (will receive when app is in foreground)
(2)Data Message (will receive when app is in background+foreground)
Reference : https://firebase.google.com/docs/cloud-messaging/android/receive
You need to set click_action in firebase notification data set to be able to receive data from background and implement onMessageReceived to handle foreground data
See updated answer here: https://stackoverflow.com/a/73724040/7904082
Here is how I am saving sms in java
private void saveSmsInInbox(Context context, SmsMessage sms) {
Intent serviceIntent = new Intent(context, SaveSmsService.class);
serviceIntent.putExtra("sender_no", sms.getDisplayOriginatingAddress());
serviceIntent.putExtra("message", sms.getDisplayMessageBody());
serviceIntent.putExtra("date", sms.getTimestampMillis());
context.startService(serviceIntent);
}
AS of KitKat, only the default SMS app can write to the SMS databsse. So unless you're the phone's SMS app chosen by the user, you cannot update the text of the SMS at a later time.
I have added two actions to the notification i.e. accept and reject.
I can see both when the app is in foreground. But I cant see the actions when app is in background.
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
private String mOrderId, mBillId;
private Boolean mUpdateNotification;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Log.d(TAG, "From: " + remoteMessage.getFrom());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.describeContents());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
//get data from server notification.
sendNotification(remoteMessage.getNotification().getBody(), remoteMessage.getNotification().getTitle());
}
//send notification
private void sendNotification(String messageBody, String title) {
Intent intent = new Intent();
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 , intent,
PendingIntent.FLAG_UPDATE_CURRENT);
long[] pattern = {500, 500, 500, 500, 500};
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.login_logo_1)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setVibrate(pattern)
.setSound(defaultSoundUri)
.addAction(R.string.accept,getString(R.string.accept), pendingIntent)
.addAction(R.string.reject,getString(R.string.reject), pendingIntent)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 , notificationBuilder.build());
}
}
Also I want to handle the intents from these actions. For this I have created a class which extends broadcast receiver,but how to call this in an activity?
public class NotificationReceiver extends BroadcastReceiver {
String ACCEPT,REJECT;
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(ACCEPT.equals(action)) {
Log.v("Delivery","Accepted");
}
else if(REJECT.equals(action)) {
Log.v("Delivery","Rejected");
}
}
}
Please help. Thank you..
In FCM there are three type of messages you can send
1. Notification message
FCM automatically displays the message to end-user devices on behalf
of the client app. Notification messages have a predefined set of
user-visible keys and an optional data payload of custom key-value
pairs.
Use notification messages when you want FCM to handle displaying a
notification on your client app's behalf.
2.Data message
Client app is responsible for processing data messages. Data messages
have only custom key-value pairs.
Use data messages when you want to process the messages on your
client app.
3. Both Notification and Data
Messages with both notification and data payload, both background and
foreground. In this case, the notification is delivered to the
device’s system tray, and the data payload is delivered in the extras
of the intent of your launcher Activity.
So if you want to handle message on client side better you go with Data Message
here you get all details
For send Data Message
For Data Message you have to call post service using following URL
https://fcm.googleapis.com/fcm/send
Headers
Authorization:key=yourserverkey
Content-Type: application/json
Payload
{"data": "extra data to be send",
"to" : "devicetoken"
}
Note: replace "to" with "registration_ids" : ["1","2","3","4","5","6"] for multiple devices
In Application onMessageReceived you can get data message using remoteMessage.getData()
For detail already mentioned this https://firebase.google.com/docs/cloud-messaging/concept-options
Here you also check to send notification to Topics using data message https://firebase.google.com/docs/cloud-messaging/android/topic-messaging
I'm writing here because I'm facing a probleme that I could not resolve even after many researches and tries.
I'm currently developing an Android Library which consists only of java classes and fragment. The problem is I need to send Local Notifications to the user, and clicking on the notifications should send the user back to the activity where he was. At this point, my library sends the notifications just fine. But the click on the notification doesn't have any action.
In my notification reciver class (which extends the BroadcastReceiver class), when the notification appears, I create a Pending Intent but I don't know what I can give as parameters to send the user to the activity. I tried using intent filters but it give me no results
So how can I have the notification sending back the user to the application ? The best would be if I was able to have the notification sending back the user to the activity where the notification is created (but it's a fragment so...)
In an usual app, I would've an intent sending back the user to an activity class but my library needs to have only fragments.
Maybe there is no problem and the solution is easy since I'm new to notifications
If someone here have an idea thanks for helping me ! :D
And if my problem isn't clear (Because of my bad english as an example) don't hesitate to ask me to add informations ^^
**Edit from 29 April : **
I managed to achieve it by giving to my broadcast pending intent the canonical name of my class using :
mContext.getClass().getCanonicalName();
Once in my broadcast receiver class I just get the class from the name of the sending class :
Class<?> activityClass = null;
try {
activityClass = Class.forName(stringSourceClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Check out below code...
public BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
try {
String title = context.getString(R.string.app_name);
Intent intent1 = new Intent(context, YourActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),1,intent1,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(title)
.setContentText("Hello")
.setAutoCancel(false)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, notificationBuilder.build());
} catch (Exception e) {
}
}
};
check the Building a notification page:
Intent resultIntent = new Intent(this, ResultActivity.class);
...
// Because clicking the notification opens a new ("special") activity, there's
// no need to create an artificial back stack.
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
just put your activity in resultIntent
how can I have the notification sending back the user to the
application ?
That's pretty simple:
1. While creating intent for pending intent call addAction ("action_name") method;
2. In activity you want to call (in manifest file) inside intent-filter tag add <action android:name="action_name>.
Now when your notification try to launch activity it would send intent message to system, which would search activity with proper action and launch it.
P.S. action name must be unique for every application
I wrote an app and I set an alarm manager which set to send a notification every 3 hours. Assume my notification has to be send at 11:10 and my phone is getting off at 11:00. So, I will not receive any notification. When my phone is turned on, I will receive the next notification at 2:10, so everything is working correctly.
Although, it was observed that I will not receive any notification after my phone is getting off for two round of notification. Do you have any suggestion?
The code is provided:
Intent intentAlarm = new Intent(this, NotifyBroadcast.class);
PendingIntent pintentAlarm = PendingIntent.getBroadcast(this, 0, intentAlarm, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
// Start every 30 seconds
mgr.setRepeating(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis(), 300, pintentAlarm);
// NotifyBroadcast:
public class NotifyBroadcast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent resultIntent = new Intent(context, MainActivity.class);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
context,
0,
resultIntent,
0
);
Notification notification = new Notification(R.drawable.ic_launcher, "Let me know what is your emotion buddy!", System.currentTimeMillis());
notification.defaults |= Notification.DEFAULT_SOUND;
notification.sound = Uri.parse("file:///sdcard/notification/notification.mp3");
//notification.flags = Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(context, "emotion interface", "Let me know what is your emotion buddy!", resultPendingIntent);
int mId = 001;
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, notification);
// mNotificationManager.notify(mId,mBuilder.build());
// mNotificationManager.cancel(mId);
}
}
I didn't understand following part very well :
I will not receive any notification after my phone is getting off for two round of notification .
Just check that you are relaunching your service after reboot. For that you need to add a receiver that launches your Service again after the reboot. You need to handle that on android.intent.action.BOOT_COMPLETED intent broadcast. Some of the questions that might help you are:
Android: make notification persist across phone reboot
android notification after reboot
Android: why did the Alarm notification stop after system reboot
Hope this helps in some way.