i want show notification on stock value change in android - android

I developed stock market app.now I want to develop app that have features like notification when stock value has been change to 1 % of current ...help me ...thanks in advance..i want show notification on stock value change in android

Try the following it may helps you
1) First take one service in your application
2) In the service check the stock market updates frequently
EDIT
public class StockService extends Service{
Thread t=new Thread(){
public void run(){
while(true){
checkStockUpdates();
Thread.sleep(give how much time you want);
}
}
};
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
t.start();
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public void checkStockUpdates(){
//write code here for checking stock market updates
//if any updates found send notification here itself
}
}
3) If you observe any change then you can send notification to user
Following is the code for send notification
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
/* Invoking the default notification service */
mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.icon)
.setContentTitle("My notification")
.setContentText("Hello World!");
manager.notify(1234, mBuilder.build());
Note : Thread is lightweight so if you write while loop also it doesn't effect on Application performance.
hope it will helps you.

Related

ContentObserver registered in service is killed when app killed

I need to be able to detect when changes occur in contact data (any type of change to any contact in the address book).
I am using this ContentObserver:
public class ContactsContentObserver extends ContentObserver {
private Context context;
private Handler toastMessageHandler;
public ContactsContentObserver(Handler handler, Context ctx) {
super(handler);
context = ctx;
}
#Override
public void onChange(boolean selfChange) {
this.onChange(selfChange,null);
}
#Override
public void onChange(boolean selfChange, Uri uri) {
// Change Detected! Do something.
}
}
I register this observer in a service like this:
#Override
public int onStartCommand (Intent intent, int flags, int startId){
super.onStartCommand(intent, flags, startId);
registerContactsContentObserver();
return START_STICKY;
}
private void registerContactsContentObserver(){
ContactsContentObserver myObserver = new ContactsContentObserver(new Handler(), this);
getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, myObserver);
}
I start this service in my main activity.
It works fine as long as the activity is open (even if in the background), and the onChange() method is called every time I change any contact data.
But it doesn't work at all if I manually close the app by clearing it from recent apps in android
Am I doing something wrong? Isn't the service supposed to run even when the app is closed?
I've been able to solve the issue with the help of pskink
Starting the service in the forground like this:
private void runAsForeground(){
Intent notificationIntent = new Intent(this, LauncherActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(this, 0,
notificationIntent, PendingIntent.FLAG_ONE_SHOT);
Notification notification=new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText("test")
.setContentIntent(pendingIntent).build();
startForeground(1, notification);
}
#Override
public int onStartCommand (Intent intent, int flags, int startId){
super.onStartCommand(intent, flags, startId);
runAsForeground();
registerContactsContentObserver();
return START_STICKY;
}
solved the issue.
Although, I still don't understand why the issue occurred in the first place, since, the service is sticky and supposed to run even if the app is closed. Even if android stopped the service to save memory, it is supposed to restart it.
Can somebody explain to me why starting the service in the foreground is any different than a regular sticky service in the background?

Android service is stopping without calling ondestroy

I'm calling a service every three minutes using the following function:
public void RunBackgroundService() {
final Handler service_handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
service_handler.post(new Runnable() {
public void run() {
context.startService(new Intent(context,BackgroundService.class));
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 180 * 1000);
}
And this is my service in which I'm launching a notification:
public class BackgroundService extends Service {
Helper helper;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
//Toast.makeText(this, "Service created!", Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
//Toast.makeText(this, "Service stopped", Toast.LENGTH_LONG).show();
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onStart(Intent intent, int startid)
{
helper=new Helper(this);
// Log.d("Service started at:", helper.getdatetime());
Intent n_intent = new Intent(this, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, n_intent, 0);
// build notification
// the addAction re-use the same intent to keep the example short
long[] vibrate = { 0, 100, 200, 300 };
Notification n = new Notification.Builder(this)
.setContentTitle("Application")
.setContentText("This is a test")
.setSmallIcon(R.drawable.notification_icon)
.setContentIntent(pIntent)
.setDefaults(Notification.DEFAULT_SOUND)
.setVibrate(vibrate)
.setAutoCancel(true)
.build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, n);
}
}
It's very important to me to remain the service running at all time, when the app crashes the service stops. How can I prevent the service from stopping ?
When an app crashes, the entire process goes down with it. This includes all Services and other threads in that process. You can't stop that from happening.
The best you can do is to configure your app to run in a different process from the main app process, but then you have to know how that affects the rest of your app.
Be sure to read the docs for how to define a service to run in another process. You use the android:process attribute for that.
You cna not stop system killing your service. But what you can do is to restart the service when it is crashed. Take a look at detailed sof post How to restart service after the app is killed from recent. This solution works not only when app is killed through recent taks by user but also when system kills app.
Use android:process tag to start process in different process.
Then use it as bind to service from your application, this way you can communicate with service via ipc and service runs indefinitely even if your app crashes.

run service even if the application is closed (killed)

I want that this service run even if the application is closed (kiiled) or even if the user dont start the app.
i want the service start after the application is installed and from this point, the service should run always.
public class notifications extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
}
#Override
public void onStart(Intent intent, int startId) {
final Handler handler = new Handler();
final Runnable runb = new Runnable()
{
public void run()
{
Toast.makeText(getApplicationContext(), " Service Started", Toast.LENGTH_LONG).show();
handler.postDelayed(this, 10000);
}
};
handler.postDelayed(runb, 0);
}
#Override
public void onDestroy() {
}
}*/
public class notifications extends IntentService
{
private Timer mBackGroundTimer;
public notifications()
{
super("myservice");
this.mBackGroundTimer=new Timer();
}
#Override
protected void onHandleIntent(Intent intent)
{
// TODO Auto-generated method stub
mBackGroundTimer.schedule(new TimerTask()
{
public void run()
{
try
{
Notification("This is message from Dipak Keshariya (Android Application Developer)", "This is Android Notification Message");
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
},1000, 2000);
} // END onHandleIntent()
private void mStopTimer()
{
//Call this whenever you need to stop the service
mBackGroundTimer.cancel();
}
private void Notification(String notificationTitle, String notificationMessage) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
android.app.Notification notification = new android.app.Notification(R.drawable.ic_launcher, "A New Message from Dipak Keshariya (Android Developer)!",
System.currentTimeMillis());
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(getApplicationContext(), notificationTitle, notificationMessage, pendingIntent);
notificationManager.notify(10001, notification);
}
}
how i can do that?
Looking at your code, it appears you want your service to periodically give notifications.
As far as having it run continuously goes, keep in mind that by design, the Android system may terminate your service process at any time. You can influence this a bit, but you cannot prevent the system from killing your service.
So for your periodical actions, it would be best to use AlarmManager with a recurring alarm. Your service would then basically be one-shot, i.e. perform the action once and then exit.
For some code, look here for example:
Android: Alarm Manager
You need to implement the OnStartCommand method of the Service class and in it, return Service.START_STICKY. That will do the trick. If you kill the application, the service will continue to run in the background. However, if you restart your phone, I think you need to implement something else in your app, as well, a boot service or something like that.
As you requirement is to run the service in the background. you are on the right track to use the service because this is meant for background running purpose only.
from the activitiy you can start the service by
startService(new Intent(activityName.this, serviceName.class));
or if your application is not having any activity then you can make the service as default and main launcher of the application by putting
<service android:name="name of the service" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</service>
I think answer to this question is this : https://developer.android.com/training/sync-adapters/creating-sync-adapter.html
Sync Adapters introduced in Google I/O 2013.

onGoing notification disappears after a few second

I am trying to put a notification in the status bar when a service starts and keep it there until I stop the service but is disappears after a few seconds(about 10). Any suggestions as to what I am missing? This worked before I tried to re write using notification.builder for compatibility with api 15. The log entry shows onDestroy is not called until I stop the service so it is still running.
public class MyService extends Service {
private NotificationManager mNM;
private int NOTIFICATION = R.string.service_started;
public void onCreate() {
super.onCreate();
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
showNotification();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("MyService", "Service Started");
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
mNM.cancel(NOTIFICATION);
Log.e("MyService", "Service Ended");
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private final IBinder mBinder = new LocalBinder();
private void showNotification() {
Notification.Builder builder = new Notification.Builder(getApplicationContext());
builder.setAutoCancel(false)
.setOngoing(true)
.setSmallIcon(R.drawable.myicon)
.setTicker(getText(R.string.service_label))
.setWhen(System.currentTimeMillis())
.setContentTitle(getText(R.string.service_started))
.setContentText(getText(R.string.service_label));
Notification notification = builder.getNotification();
mNM.notify(NOTIFICATION, notification);
}
I had the same problem with an ongoing notification disappearing in ICS on a new phone. The app and notification had worked perfectly in every version of Android I had tested it on previously, and it even works on an ICS emulator. Needless to say this has been driving me crazy for a couple months now, but I finally found the answer.
http://code.google.com/p/android/issues/detail?id=21635
I am using a BroadcastReceiver to monitor incoming calls on the handset and I programmatically enable the receiver when a button is toggled in addition to setting the notification. So I wrote a small test app with the same BroadcastReceiver hooked up and was able to reproduced the problem. I commented out the setComponentEnabledSetting call and the notification no longer disappears.

Android - Planning a userbar notification

Im creating an application where I can add appointments to a list.
If an appointment is nearby, I want my app to show a notification in the status bar the day of the appointment at a certain hour.
I used the code from http://developer.android.com/guide/topics/ui/notifiers/notifications.html
to create my notification.
However, the "when" parameter in the script is somewhat confusing because a statusbar notification is always triggered when called.
Notification notification = new Notification(icon, tickerText, when);
What is the best way to schedule such notification?
It seems there is no easy way and I have to create a service that starts a listener Activity with a thread to loop my appointmentdates and show a notification when a date fits the current date?
However, the "when" parameter in the script is somewhat confusing
because a statusbar notification is always triggered when called.
Notification notification = new Notification(icon, tickerText, when);
Exactly - notification is triggered when called. If you set when variable to System.currentTimeMilis() as in the example, it means - show the notification now.
As what triggers your notifications, that is up to you to handle. An Activity doesn't seem like a good choice, but a Service does. Initialize your service on application start (and don't forget to stop it on application exit), and let it do the "listening" and triggering of notifications. It might look as:
public class NotifyService extends Service {
private NotificationManager mNM;
#Override
public void onCreate() {
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
//do some work, listen for change
if (triggerSatisfied) showNotification();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onDestroy() {
// Cancel the persistent notification.
mNM.cancelAll();
}
#Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
private final IBinder mBinder = new LocalBinder();
private void showNotification() {
//code for notification goes here
}
public class LocalBinder extends Binder {
NotifyService getService() {
return NotifyService.this;
}
}

Categories

Resources