How to run a service periodically without opening the app - android

hi I am developing an application where I need to get the unread SMS from my phone. I need to check my inbox once a fixed amount of time. I have written the code to retrieve the unread SMS. I have included a timer which checks the unread SMS every 30 seconds. But the problem is it checks only when the app is open. I need to check even when the app is not open. Please provide any suggestions and modification I need to make. Below is my code.
MainActivity
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends ActionBarActivity {
MyReceiver myReceiver;
ListView lViewSMS;
ArrayList datapassed;
//private static final String TAG_SUCCESS = "success";
//String URL = "http://10.10.234.232/test_android/index2.php";
// JSONParser jsonParser = new JSONParser();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lViewSMS = (ListView) findViewById(R.id.listViewSMS);
//String []r;
// r=new String[2];
// if (r != null) {
//#SuppressWarnings("unchecked")
//ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, fetchInbox());
//lViewSMS.setAdapter(adapter);/
//AttemptLogin attemptLogin = new AttemptLogin();
//attemptLogin.execute(r[0],r[1]);
// #SuppressWarnings("unchecked")
// ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, datapassed);
//lViewSMS.setAdapter(adapter);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
//Register BroadcastReceiver
//to receive event from our service
myReceiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(MyService.MY_ACTION);
registerReceiver(myReceiver, intentFilter);
//Start our own service
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Intent intent = new Intent(MainActivity.this, MyService.class);
startService(intent);
}
},
0,
30000);
super.onStart();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
unregisterReceiver(myReceiver);
super.onStop();
}
private class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
datapassed = arg1.getStringArrayListExtra("DATAPASSED");
// #SuppressWarnings("unchecked")
// ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, datapassed);
// lViewSMS.setAdapter(adapter);
Toast.makeText(MainActivity.this,
"Triggered by Service!\n"
+ "Data passed: " + datapassed,
Toast.LENGTH_LONG).show();
}
}
}
MyService.java
import android.app.Service;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.IBinder;
import java.util.ArrayList;
public class MyService extends Service {
final static String MY_ACTION = "MY_ACTION";
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
MyThread myThread = new MyThread();
myThread.start();
return super.onStartCommand(intent, flags, startId);
}
public class MyThread extends Thread{
#Override
public void run() {
// TODO Auto-generated method stub
try {
//Thread.sleep(5000);
Intent intent = new Intent();
intent.setAction(MY_ACTION);
if(fetchInbox()!=null) {
intent.putExtra("DATAPASSED", fetchInbox());
sendBroadcast(intent);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stopSelf();
}
}
ArrayList fetchInbox (){
final Uri SMS_INBOX = Uri.parse("content://sms/inbox");
//Retrieves all SMS (if you want only unread SMS, put "read = 0" for the 3rd parameter)
Cursor cursor = getContentResolver().query(SMS_INBOX, null,"read=0", null, null);
ArrayList sms = new ArrayList();
//Get all lines
String read=" ";
String body=" ";
String[] arr = new String[2];
while (cursor.moveToNext()) {
//Gets the SMS information
String address = cursor.getString(cursor.getColumnIndex("address"));
String person = cursor.getString(cursor.getColumnIndex("person"));
String date = cursor.getString(cursor.getColumnIndex("date"));
String protocol = cursor.getString(cursor.getColumnIndex("protocol"));
read = cursor.getString(cursor.getColumnIndex("read"));
String status = cursor.getString(cursor.getColumnIndex("status"));
String type = cursor.getString(cursor.getColumnIndex("type"));
String subject = cursor.getString(cursor.getColumnIndex("subject"));
body = cursor.getString(cursor.getColumnIndex("body"));
sms.add(address+"\n"+person+"\n"+body+"\n");
//Do what you want
// else
// {
// AttemptLogin attemptLogin = new AttemptLogin();
// attemptLogin.execute("", "");
//}
}
//return arr;
//return body;
return sms;
}
}

you can Use AlarmManager Class in Android to run the service periodically.
AlarmManager alarmMgr= (AlarmManager)
context.getSystemService(Context.ALARM_SERVICE);
int timeInterval=300*1000;//in milliseconds
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
Intent intent = new Intent(context, YourService.class);
alarmIntent = PendingIntent.getService(context, 0, intent, 0);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), timeInterval, alarmIntent);`

You may use AlarmManeger class https://developer.android.com/training/scheduling/alarms.html for Example
Calendar calendar = Calendar.getInstance();
long repeatInterval = 30000;
AlarmManager am = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(getActivity(), MyReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(getActivity(), 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), repeatInterval , pi);
Where repeatInterval time, in milliseconds.
onReceive() is called when the MyReceiver is receiving an Intent broadcast.

You need to do this repeat code inside your Service instead of your Activity
So you start your service once :
#Override
protected void onStart() {
// TODO Auto-generated method stub
//Register BroadcastReceiver
//to receive event from our service
myReceiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(MyService.MY_ACTION);
registerReceiver(myReceiver, intentFilter);
//Start our own service
Intent intent = new Intent(MainActivity.this, MyService.class);
startService(intent);
super.onStart();
}
And in your Service
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
MyThread myThread = new MyThread();
myThread.start();
}
}, 0, 30000);
return super.onStartCommand(intent, flags, startId);
}
Also remove stopSelf(); from your MyThread
And one try passing context received in Broadcast and not of your Activity

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends ActionBarActivity {
MyReceiver myReceiver;
ListView lViewSMS;
ArrayList datapassed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lViewSMS = (ListView) findViewById(R.id.listViewSMS);
Calendar calendar = Calendar.getInstance();
long repeatInterval = 30000;
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(this, MyServiceReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), repeatInterval, pi);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
//Register BroadcastReceiver
//to receive event from our service
myReceiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(MyService.MY_ACTION);
registerReceiver(myReceiver, intentFilter);
//Start our own service
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Intent intent = new Intent(MainActivity.this, MyService.class);
startService(intent);
}
},
0,
30000);
super.onStart();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
unregisterReceiver(myReceiver);
super.onStop();
}
private class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
datapassed = arg1.getStringArrayListExtra("DATAPASSED");
// #SuppressWarnings("unchecked")
// ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, datapassed);
// lViewSMS.setAdapter(adapter);
Toast.makeText(MainActivity.this,
"Triggered by Service!\n"
+ "Data passed: " + datapassed,
Toast.LENGTH_LONG).show();
}
}
}
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
public class MyServiceReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ComponentName comp = new ComponentName(context.getPackageName(), MyService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
}
}
Try above code

Related

Is it possible to call a BroadcastReceiver from the same Activity where the receiver is written?

I have a BroadcastReceiver class in my Activity. I want to start a Fragment from the receiver class. Can i call that from the same Activity where the receiver is written?
Try something like this... And if your using your custom Broadcast Receiver then replace BroadcastReceiver this class with your receiver's class.
public class Demo extends AppCompatActivity {
private final IntentFilter filter = new IntentFilter();
private BroadcastReceiver networkStateReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void onResume() {
super.onResume();
// Defining broadcast receiver in onResume()
networkStateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Do what you want
}
};
// Registering receiver with intent filter, here intent filter can be changed
filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(networkStateReceiver, filter);
}
#Override
protected void onPause() {
super.onPause();
// Unregister receiver in onStop to avoid any runtime exception
unregisterReceiver(networkStateReceiver);
}
}
Yes you can do it using LocalBroadCastManger
import android.app.Activity;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class LocalBroadcastExampleActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.log_list);
Button buttonStartService = (Button)findViewById(R.id.button_ok);
buttonStartService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Register MessageService in Manifest to work
startService(new Intent(LocalBroadcastExampleActivity.this, MessageService.class));
}
});
}
#Override
protected void onPause() {
// Unregister since the activity is paused.
LocalBroadcastManager.getInstance(this).unregisterReceiver(
mMessageReceiver);
super.onPause();
}
#Override
protected void onResume() {
// Register to receive messages.
// We are registering an observer (mMessageReceiver) to receive Intents
// with actions named "custom-event-name".
LocalBroadcastManager.getInstance(this).registerReceiver(
mMessageReceiver, new IntentFilter("custom-event-name"));
super.onResume();
}
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// Get extra data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
};
public class MessageService extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
sendMessage();
return super.onStartCommand(intent, flags, startId);
}
// Send an Intent with an action named "custom-event-name". The Intent
// sent should
// be received by the ReceiverActivity.
private void sendMessage() {
Log.d("sender", "Broadcasting message");
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("message", "This is my message!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
}

set notification alert every 24 hours android

I want to fire a local notification every 24 hours at a specific time say evening 6 o clock
i have refered this code
here
and
here
This is the code i am trying
package com.banane.alarm;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final String TAG = "BANANEALARM";
public AlarmManager alarmManager;
Intent alarmIntent;
PendingIntent pendingIntent;
Button bananaButton;
TextView notificationCount;
TextView notificationCountLabel;
int mNotificationCount;
static final String NOTIFICATION_COUNT = "notificationCount";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
// Restore value of members from saved state
mNotificationCount = savedInstanceState.getInt(NOTIFICATION_COUNT);
}
setContentView(R.layout.activity_main);
bananaButton = (Button)findViewById(R.id.bananaButton);
notificationCount = (TextView)findViewById(R.id.notificationCount);
notificationCountLabel = (TextView)findViewById(R.id.notificationCountLabel);
}
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(NOTIFICATION_COUNT, mNotificationCount);
super.onSaveInstanceState(savedInstanceState);
}
#Override
protected void onNewIntent( Intent intent ) {
Log.i( TAG, "onNewIntent(), intent = " + intent );
if (intent.getExtras() != null)
{
Log.i(TAG, "in onNewIntent = " + intent.getExtras().getString("test"));
}
super.onNewIntent( intent );
setIntent( intent );
}
public void triggerAlarm(View v){
setAlarm();
bananaButton.setVisibility(View.GONE);
notificationCountLabel.setVisibility(View.VISIBLE);
notificationCount.setVisibility(View.VISIBLE);
notificationCount.setText("0");
}
public void setAlarm(){
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmIntent = new Intent(MainActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast( MainActivity.this, 0, alarmIntent, 0);
Calendar alarmStartTime = Calendar.getInstance();
alarmStartTime.set(Calendar.HOUR, 18); // At the hour you wanna fire
alarmStartTime.set(Calendar.MINUTE, 00); // Particular minute
alarmStartTime.set(Calendar.SECOND, 0);
// alarmStartTime.add(Calendar.MINUTE, 2);
alarmManager.setRepeating(AlarmManager.RTC, alarmStartTime.getTimeInMillis(), getInterval(), pendingIntent);
//Log.i(TAG,"Alarms set every two minutes.");
}
private int getInterval(){
int seconds = 60;
int milliseconds = 1000;
int repeatMS = seconds * 1440 * milliseconds;
return repeatMS;
}
#Override
protected void onStart(){
super.onStart();
updateUI();
}
public void cancelNotifications(){
Log.i(TAG,"All notifications cancelled.");
}
public void updateUI(){
MyAlarm app = (MyAlarm)getApplicationContext();
mNotificationCount = app.getNotificationCount();
notificationCount.setText(Integer.toString(mNotificationCount));
}
#Override
protected void onResume(){
super.onResume();
if(this.getIntent().getExtras() != null){
Log.i(TAG,"extras: " + this.getIntent().getExtras());
updateUI();
}
}
}
when try the code given in the example it works perfectly hwoever when i try to fire a notification i just wont show up what error

background services stop when the app is closed via the BACK button

A background service in Android stops running when the user exits the app using the BACK button. The same service works fine if the app is in foreground or in background (clicking the HOME button).
there are 3 cases:
Keep the app running: every 15 seconds a notification is shown (OK).
Put the app in background by clicking the HOME button: notifications keep showing (OK)
Click the BACK button (this closes the app): the background service is stopped and no more notifications are shown (BUG)
Expected behavior
Also in case #3, the notifications should keep running every 15 seconds.
my entire source is below
MainActivity.java
package com.example.service_demo;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private TextView timerValue;
private Button startTimer;
private Button cancleTimer;
Intent i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapview();
}
private void mapview() {
timerValue = (TextView) findViewById(R.id.timertext);
startTimer = (Button) findViewById(R.id.starttimer);
cancleTimer = (Button) findViewById(R.id.cancletimer);
startTimer.setOnClickListener(this);
cancleTimer.setOnClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
i = new Intent(this, SimpleService.class);
if (isMyServiceRunning()) {
Toast.makeText(getBaseContext(), "Service is running,",
Toast.LENGTH_SHORT).show();
registerReceiver(broadcastReceiver, new IntentFilter(
SimpleService.BROADCAST_ACTION));
startTimer.setEnabled(false);
} else {
Toast.makeText(getBaseContext(), "There is no service running",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onClick(View v) {
if (v == startTimer) {
startTimer.setEnabled(false);
i = new Intent(this, SimpleService.class);
startService(i);
registerReceiver(broadcastReceiver, new IntentFilter(
SimpleService.BROADCAST_ACTION));
} else if (v == cancleTimer) {
i = new Intent(this, SimpleService.class);
stopService(i);
timerValue.setText("00:00:00");
startTimer.setEnabled(true);
}
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateUI(intent);
}
};
private void updateUI(Intent intent) {
String str = intent.getStringExtra("textval");
timerValue.setText(str);
}
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager
.getRunningServices(Integer.MAX_VALUE)) {
if (SimpleService.class.getName().equals(
service.service.getClassName())) {
return true;
}
}
return false;
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
i = new Intent(this, SimpleService.class);
startService(i);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
System.exit(0); // system.exit(0) is mendatory for my app so it can't be
// removed
}
}
SimpleService
package com.example.service_demo;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class SimpleService extends Service {
private NotificationManager mNM;
private long startTime = 0L;
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
long basestart = System.currentTimeMillis();
Timer timer = new Timer();
long timeswap = 0L;
int secs = 0;
int mins = 0;
int hour = 0;
Intent intent;
String s;
public static final String BROADCAST_ACTION = "com.example.service_demo.MainActivity";
private int NOTIFICATION = 1;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
intent = new Intent(BROADCAST_ACTION);
Toast.makeText(this, "Service Started", 2000).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
timer.schedule(new RemindTask(), 0, 1000);
}
});
t.start();
return Service.START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
mNM.cancel(NOTIFICATION);
if (timer != null) {
timer.cancel();
timer.purge();
timer = null;
}
Toast.makeText(this, "Service Stoped", 2000).show();
}
class RemindTask extends TimerTask {
#Override
public void run() {
timeInMilliseconds = System.currentTimeMillis() - basestart;
timeSwapBuff = timeswap;
updatedTime = timeSwapBuff + timeInMilliseconds;
secs = (int) (updatedTime / 1000);
mins = secs / 60;
hour = mins / 60;
secs = secs % 60;
mins = mins % 60;
s = "" + String.format("%02d", hour) + ":" + ""
+ String.format("%02d", mins) + ":"
+ String.format("%02d", secs);
if (s.equalsIgnoreCase("00:00:15")) {
showNotification();
}
intent.putExtra("textval", s);
sendBroadcast(intent);
}
}
private void showNotification() {
// In this sample, we'll use the same text for the ticker and the
// expanded notification
CharSequence text = s;
// Set the icon, scrolling text and timestamp
#SuppressWarnings("deprecation")
Notification notification = new Notification(R.drawable.ic_launcher,
text, System.currentTimeMillis());
// The PendingIntent to launch our activity if the user selects this
// notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, "Notification Label", text,
contentIntent);
// Send the notification.
mNM.notify(NOTIFICATION, notification);
}
}
In the method onStartCommand() of the service, return START_STICKY.
The service will continue to run until you explicitly call stopSelf() in the service or call stopService() from your activity.
Try implementing foreground service. foreground service
Foreground service displays notification and is never stopped.
Implement this code snippet in your service's onCreate().
Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION_ID, notification);
This works for me:
notifyIntent.setAction(Intent.ACTION_MAIN);
notifyIntent.addCategory(Intent.CATEGORY_LAUNCHER);

How to receive a notification that an application has been started?

In my application I launch another activity (an external activity) using the startActivity method.
I would like to be notified when this second application is started, so I could use startActivityForResult method instead of the startActivity method. Are there other mechanisms to receive such notification?
you can try this, call startService in your first activity at the place where you call the second one.
startService(new Intent(this,NotificationService.class));
create NotificationService.java that consists the following:
package com.sample;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
public class NotificationService extends Service
{
private final int UPDATE_INTERVAL = 10 * 1000;
private Timer timer = new Timer();
private static final int NOTIFICATION_EX = 1;
private static final String TAG = "NotificationService";
private NotificationManager notificationManager;
ArrayList<HashMap<String, String>> currentForecast = new ArrayList<HashMap<String, String>>();
CharSequence tickerText="notifi";
public NotificationService(){}
public IBinder onBind1(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
//code to execute when the service is first created
}
#Override
public void onDestroy() {
if (timer != null){
timer.cancel();
}
}
#Override
public int onStartCommand(final Intent intent, final int flags, final int startid) {
notificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
int icon = R.drawable.iconToDisplayOnNotification;
long when = System.currentTimeMillis();
final Notification notification = new Notification(icon, tickerText, when);
final Context context = getApplicationContext();
final CharSequence contentTitle = "titleForNotification";
final CharSequence contentText = "TextForNotification";
Intent notificationIntent = new Intent(this, ActivityTobeCalledOnNotificationSelect.class);
final PendingIntent contentIntent = PendingIntent.getActivity(this,0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle,contentText, contentIntent);
notificationManager.notify(NOTIFICATION_EX, notification);
Toast.makeText(this, "Started!", Toast.LENGTH_LONG);
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
// Check if there are updates here and notify if true
Log.w(TAG,"run");
}
}
,10, UPDATE_INTERVAL);
return START_STICKY ;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}

How to start new service in run() of Thread?

How To start new service in Thread...
Thread is running continuously but the startservice() method in run() is not gets started...
Please Help Me.
The code is as follows.....
package com.example.demo;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class Act extends Service {
/** Called when the activity is first created. */
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(Act.this,"In On Create",Toast.LENGTH_SHORT).show();
Intent i=new Intent(getApplicationContext(),HelloService.class);
startService(i);
Toast.makeText(Act.this,"In End Create",Toast.LENGTH_SHORT).show();
updateTimeTask.start();
}
private Thread updateTimeTask = new Thread() {
public void run() {
Intent i=new Intent(getApplicationContext(),HelloService.class);
startService(i); //This Service not gets started
}
};
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
You must have a Pending Intent for this:
// start something with Intent
Intent widgetUpdate = new Intent(SomeClass.this,
SomeService.class);
widgetUpdate.putExtra("Something", something);
// make this pending intent unique
widgetUpdate.setData(Uri.withAppendedPath(
Uri.parse(mUriSchemaId + "://widget/id/"),
String.valueOf(appWidgetId)));
PendingIntent newPending = PendingIntent.getService(
getApplicationContext(), 0, widgetUpdate,
PendingIntent.FLAG_UPDATE_CURRENT);
remoteview.setOnClickPendingIntent(R.id.someview,
newPending);

Categories

Resources