I want to send notifications to the user, even if my app is closed. I heard about GCM but I don't think it's the best solution for me. I also tried to use Service, but it doesn't seem to work either. Does somebody have a idea on how can I perform that?
public class notificationService extends Service {
Timer timer;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
timer = new Timer();
timer.schedule(new RemindTask(), 10*1000);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startId) {
super.onCreate();
}
}
class RemindTask extends TimerTask {
public void run() {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.icone)
.setContentTitle("My notification")
.setContentText("Hello World!");
Intent resultIntent = new Intent(this, Acceuil.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(Acceuil.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, mBuilder.build());
}
}
Edit: i'm talking about this kind of notifications
GCM can be tricky, but it is the Google recommended way of doing things. What I did was to follow these pages step by step and it worked for me, pretty quick to get up and running:
Getting Started
Implementing GCM Client ("Running The Sample" below the page is great to start quickly)
Implementing GCM Server
Send via C++ Server
As mentioned, you have a C++ server, that you want to send notifications on. That is a little trickier, but doable. Here's what you need:
OpenSSL BIO (So you can connect to the GCM HTTP Server via HTTPS)
Secure programming with the OpenSSL API - Great guide by IBM
Understanding how to "speak" HTTP via sockets (You need to POST)
http://coding.debuntu.org/c-linux-socket-programming-tcp-simple-http-client
Sample code below:
POSTing via OpenSSL BIO
// Request
stringstream ss;
string endline = "\r\n";
ss << "POST /gcm/send HTTP/1.0" << endline;
ss << "Host: android.googleapis.com" << endline;
ss << "Accept: */*" << endline;
ss << "Authorization: key=" << mKey << endline;
ss << "Content-Type: application/json" << endline;
ss << "Content-Length: " << ssbody.str().size() << endline;
ss << endline;
ss << ssbody.str();
syslog(LOG_DEBUG, "%s", ss.str().c_str());
int bioResult = 0;
do {
bioResult = BIO_write(mBio, ss.str().c_str(), ss.str().length());
if (bioResult <= 0) {
this->restart();
}
} while (bioResult <= 0);
You can send a message using the onStop() or onPause() methods, depending on what you want to do.
For example, you can verify if you want to send a notification only if your app is running in background, or really when the user closes the app. To understand better about these two methods, I recommend you to see the specifications here:
http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
if u used GCM registarar for register device. U have an device id. If your app still installed on the phone. U can send notification when app is closed
If you want a push style of notification, I would recommend using Amazon's push notification service. It also includes sample code to get you started .
If you don't want a push style and rather just have a polling type (clients periodically check a server for messages ) you can use a service that periodically sends communication to a server, and if a certain response is received you can create a local notification. To do this the service should start on boot to ensure if a user restarts their phone , and hasn't opened your app, notifications can still come in.
notifications send by my c++ server
Use GCM to deliver the messages to the particular devices that need them. Your code on the device can then do what it wants.
or daily notifications
Use AlarmManager to schedule points in time when your code should get control, and then do whatever is needed at those points.
Related
i have been working on an APP where people registers and then subscribes for some kind of specific notifications i have created the APP already (pretty much done)
i am new to the APP develelopment and have less knowledge about JAVA so if i am wrong anytime please do let me know thankx
What i have now
user can login or signup etc and when signup i create a notification chanel with his/her phone number
NOTIFICATION CODE
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = channel_name;
String description = channel_description;
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("124t", name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
now i have no idea what to do after this how do i check the notification channels created and send test notification using some kind of API etc.
any reference or answer is appreciated.
Thankx
I am trying to make an android chat application. I am thinking about making it with aws. But the problem is that I am unable to find any good tutorial for doing this and I have no idea how to do it.
So could anyone please suggest some tutorial for sending push notification or on how to make a chat application?
Firebase is well suited to this due to its "realtime database" feature. Here's a few tutorials I found by Googling
https://code.tutsplus.com/tutorials/how-to-create-an-android-chat-app-using-firebase--cms-27397
http://myapptemplates.com/simple-android-chat-app-tutorial-firebase-integration/
https://codelabs.developers.google.com/codelabs/firebase-android/#0
Check Socket.IO for android. ( https://github.com/socketio/socket.io-client-java )
Its really easy to write a chat application. But you need a server side.
Easy to write a simple server for this chat app.
Server reveice the all message from clients and broadcast the message, to all.
Gradle:
compile 'com.github.nkzawa:socket.io-client:0.5.1'
Android manifest:
<uses-permission android:name="android.permission.INTERNET" />
Java
public static Socket mSocket;
try {
mSocket = IO.socket("http://192.168.1.104:4444");
mSocket.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
}
Send messsage to server:
MainActivity.mSocket.emit("message","Text here...");
Create a listener for another message:
MainActivity.mSocket.on("newMessage", onMessageArrive); // Oncreate
private Emitter.Listener onMessageArrive = new Emitter.Listener() {
#Override
public void call(final Object... args) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
String data = (String)args[0];
// Here is all message. add it to list :) Or Push notif
}
});
}
};
// Server side:
var http = require('http');
var express = require('express'),
app = module.exports.app = express();
var io = require('socket.io').listen(app.listen(4444));
io.on('connection', function (socket) {
socket.on("message",function(msg){
io.sockets.emit('newMessage', msg);
});
});
Run:
npm install express
npm install socket.io
node filename.js
Just dont forget to check you IP! :)
Done! You have a Real Time Chat!!
I'm trying to send a Telegram message to a specific number from within my Android app. Right now my code launches Telegram app, and then the user has to select the destinatary. What I want to do is to send the message to the specified number, without having the user select the contact. My code is as follows:
/**
* Intent to send a telegram message
* #param msg
*/
void intentMessageTelegram(String msg)
{
final String appName = "org.telegram.messenger";
final boolean isAppInstalled = isAppAvailable(mUIActivity.getApplicationContext(), appName);
if (isAppInstalled)
{
Intent myIntent = new Intent(Intent.ACTION_SEND);
myIntent.setType("text/plain");
myIntent.setPackage(appName);
myIntent.putExtra(Intent.EXTRA_TEXT, msg);//
mUIActivity.startActivity(Intent.createChooser(myIntent, "Share with"));
}
else
{
Toast.makeText(mUIActivity, "Telegram not Installed", Toast.LENGTH_SHORT).show();
}
}
You can't send to special number, But You can do this by USERID
try {
Intent telegramIntent = new Intent(Intent.ACTION_VIEW);
telegramIntent.setData(Uri.parse("http://telegram.me/USERID"));
startActivity(telegramIntent);
} catch (Exception e) {
// show error message
}
This code will show user an alert for choosing applications that support telegram uri's like Telegram itself and Mobogram!
Tip: don't set package name. some people install telegram alternatives like mobogram.
The Telegram Android App does not have a way to send messages directly to telegram users, so if you use the share intent, you'll get what telegram / any other app wants to do with the message shared. In this case, open the contact list to send this message to him.
If you want to send messages directly to Telegram users you should use the Telegram API
https://core.telegram.org/api#getting-started
once you have configured your API key in your app, you could send messages, read them or even get the telegram contacts with these methods
https://core.telegram.org/methods
This one worked for me:
try {
Intent telegram = new Intent(Intent.ACTION_VIEW, Uri.parse("https://t.me/USER_NAME"));
telegram.setPackage("org.telegram.messenger");
startActivity(telegram);
}catch (Exception e)
{
Toast.makeText(getContext(), "Telegram app is not installed", Toast.LENGTH_LONG).show();
}
Tip: You can get USER_NAME by click on you telegram profile option you will get option of username in Account session --> if username is none create unique username and put here its work for me.
This one worked for me:
//check if application is installed first before running this code.
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("http://telegram.me/+UT_USER_ID_HERE"));
final String appName = "org.telegram.messenger";
i.setPackage(appName);
this.startActivity(i);
try the intent like this
tg://resolve?domain=YOUR_USER_ID
it's more direct then https://t.me
I'm using this for send message on background :
this cod is api telegram for use send message by url token bot
1 - use WebView on xml like this :
<WebView
android:id="#+id/webView_sendToTelegram"
android:layout_width="0dp"
android:layout_height="0dp"/>
2 - on java use this cod:
public static void SendMessageToBotTelegram(String chatID, String text, String botToken,WebView webView) {
webView.loadUrl(MessageFormat.format("https://api.telegram.org/bot{0}/sendMessage?chat_id={1}&text={2}", botToken, chatID, text));
}
chatID : your telegram id #RawDataBot for get id
text : text your message
botToken : your bot for get message if you don't have bot using #BotFather for crate bot
webView : your id WebView on xml
I'm trying to send the content of a DataMap from an Android device to a wearable. It works fine when the app is in the foreground on my app but once I lock the mobile device it gets stuck at the pendingResult.await() and the wearable doesn't receive any data where as it normal would if I keep the app open.
public void send(final DataMap dataMap) {
new Thread(new Runnable() {
#Override
public void run() {
PutDataMapRequest putDMR = PutDataMapRequest.create(WEARABLE_DATA_PATH);
putDMR.getDataMap().putAll(dataMap);
PendingResult<DataApi.DataItemResult> pendingResult = Wearable.DataApi.putDataItem(googleClient, request);
DataApi.DataItemResult result = pendingResult.await();
if(result.getStatus().isSuccess()) {
Log.d("qwe", "Data item set: " + result.getDataItem().getUri());
}
}
}).start();
}
This method is in a class which extends WearableListenerService and I have added the XML in the AndroidMainfest for the service also. Am I doing something completely wrong or missing something?
Thanks
try to check google api client status for each send.
use blockingConnect when google api client is not connected.
Found out I was doing googleClient.disconnect() in my main activity onStop() which was causing it to hang as googleClient wasn't connected once my app was in the background.
I'm trying to start a Skype intent from my Android App, passing a phone number. So far, thanks to other people who ad similiar needs here on stackoverflow, I've managed to start skype, but still I can't pass the phone number. This is the code I'm using:
Intent sky = new Intent("android.intent.action.CALL_PRIVILEGED");
sky.setClassName("com.skype.raider",
"com.skype.raider.Main");
sky.setData(Uri.parse("tel:" + number));
Log.d("UTILS", "tel:" + number);
ctx.startActivity(sky);
What's happening is that skype starts, but gives me a toast saying that the number is not valid, and suggests me to add the international prefix.
The Log.d gives me tel:+39........ (the number works, I'm using it also for
public static void call(String number, Context ctx) {
try {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + number));
ctx.startActivity(callIntent);
} catch (ActivityNotFoundException e) {
Log.e("helloandroid dialing example", "Call failed", e);
}
}
In fact, when I go to the Skype's view for calling, I see it's been composed +0
So what it seems to me is that I'm passing the phone number in the wrong way, or to the wrong Activity....any help would be very appreciated!
In the meantime, I just want to say that StackOverflow simply rocks.
See this answer: https://stackoverflow.com/a/8844526/819355
Jeff suggests using a skype:<user name> instead of tel:<phone number>
After some studing of the skype apk with apktool, as suggested in that answer, I came up with this code, for me it's working:
public static void skype(String number, Context ctx) {
try {
//Intent sky = new Intent("android.intent.action.CALL_PRIVILEGED");
//the above line tries to create an intent for which the skype app doesn't supply public api
Intent sky = new Intent("android.intent.action.VIEW");
sky.setData(Uri.parse("skype:" + number));
Log.d("UTILS", "tel:" + number);
ctx.startActivity(sky);
} catch (ActivityNotFoundException e) {
Log.e("SKYPE CALL", "Skype failed", e);
}
}
Refer to Skype developer: Skype URI tutorial: Android apps
Also remember to add "?call" in your url. E.g
intent.setData(Uri.parse("skype:" + phoneNumber + "?call"));
Without it, Skype may not dial the number.
You should not include a specific class when calling an external app. Let the user decide of the application he/she wants to use. That's the way android has been designed and it's a better solution than obliging people to use a soft (moreover quite a slow, closed and inconvenient app to my mind).
In other words, just use the Uri, that's the job of skype of declaring its ability to capture such intents.
Refer this skype doc link Skype URI tutorial: Android apps
First need to check skype is installed or not using
/**
* Determine whether the Skype for Android client is installed on this device.
*/
public boolean isSkypeClientInstalled(Context myContext) {
PackageManager myPackageMgr = myContext.getPackageManager();
try {
myPackageMgr.getPackageInfo("com.skype.raider", PackageManager.GET_ACTIVITIES);
}
catch (PackageManager.NameNotFoundException e) {
return (false);
}
return (true);
}
initiate skype uri using
/**
* Initiate the actions encoded in the specified URI.
*/
public void initiateSkypeUri(Context myContext, String mySkypeUri) {
// Make sure the Skype for Android client is installed.
if (!isSkypeClientInstalled(myContext)) {
goToMarket(myContext);
return;
}
// Create the Intent from our Skype URI.
Uri skypeUri = Uri.parse(mySkypeUri);
Intent myIntent = new Intent(Intent.ACTION_VIEW, skypeUri);
// Restrict the Intent to being handled by the Skype for Android client only.
myIntent.setComponent(new ComponentName("com.skype.raider", "com.skype.raider.Main"));
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Initiate the Intent. It should never fail because you've already established the
// presence of its handler (although there is an extremely minute window where that
// handler can go away).
myContext.startActivity(myIntent);
return;
}
if Skype is not installed then redirect to market place using
/**
* Install the Skype client through the market: URI scheme.
*/
public void goToMarket(Context myContext) {
Uri marketUri = Uri.parse("market://details?id=com.skype.raider");
Intent myIntent = new Intent(Intent.ACTION_VIEW, marketUri);
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
myContext.startActivity(myIntent);
return;
}