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;
}
}
Related
I'm trying to make a simple musicPlayer that works on Android device.To make Background-play come true, I'm using Service class.
What I want to do is below:
1.User launches app and taps start button
2.Music starts and Notification that notes the Music is playing appears
3.User taps home button and the app's UI disappears
4.Music doesn't stop
5.User tap Notification
6.UI appears with disabled start button and enabled stop button ← I'm in trouble
With My Code, UI appears. But it is not the UI which user made to disappear. How do I describe...It is new-ed UI.
So when user taps stop button,of course music doesn't stop. The Service is different one.
I want music to stop.
Is there any way to show the first created UI? the original UI?
If there's no way to show first created UI,how can I reach to first running service?
Thank you for browsing.
My Activity
package com.websarva.wings.android.servicesample;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements ServiceConnection {
public static final String LOG_TAG = "ServiceSample:";
private Intent _intent;
public static final String INTENT_ACTION = "intentAction";
private ServiceConnection _connection = new ServiceConnection(){
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
}
#Override
public void onServiceDisconnected(ComponentName name) {
}
};
public void onPlayButtonClick(View view){
Log.e(LOG_TAG,
"#onPlayButtonClick -_intentHash - " + _intent.hashCode()
+ "-_connectionHash" + _connection.hashCode());
bindService(_intent, _connection,Context.BIND_AUTO_CREATE);
startService(_intent);
Button btPlay = findViewById(R.id.btPlay);
btPlay.setEnabled(false);
Button btStop = findViewById(R.id.btStop);
btStop.setEnabled(true);
}
public void onStopButtonClick(View view){
Log.e(LOG_TAG,
"#onStopButtonClick -_intentHash - " + _intent.hashCode()
+ "-_connectionHash" + _connection.hashCode());
unbindService(_connection);
stopService(_intent);
Button btStop = findViewById(R.id.btStop);
btStop.setEnabled(false);
Button btPlay = findViewById(R.id.btPlay);
btPlay.setEnabled(true);
}
private BroadcastReceiver _MessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Button btStop = findViewById(R.id.btStop);
btStop.setEnabled(false);
Button btPlay = findViewById(R.id.btPlay);
btPlay.setEnabled(true);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocalBroadcastManager.getInstance(this).registerReceiver(_MessageReceiver,new IntentFilter(INTENT_ACTION));
_intent = getIntent();
boolean isAlreadyPlaying = _intent.getBooleanExtra(SoundManageService.EXTRA_KEY_ISPLAYING,false);
if(isAlreadyPlaying){
Button btPlay = findViewById(R.id.btPlay);
btPlay.setEnabled(false);
Button btStop = findViewById(R.id.btStop);
btStop.setEnabled(true);
}
_intent = new Intent(MainActivity.this,SoundManageService.class);
bindService(_intent, _connection,Context.BIND_AUTO_CREATE);
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
}
#Override
public void onServiceDisconnected(ComponentName name) {
}
#Override
public void onDestroy(){
LocalBroadcastManager.getInstance(this).unregisterReceiver(_MessageReceiver);
super.onDestroy();
}
}
My Service
package com.websarva.wings.android.servicesample;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;
import androidx.core.app.NotificationCompat;
import androidx.lifecycle.LifecycleService;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import java.io.IOException;
public class SoundManageService extends LifecycleService{
public static final String CHANNEL_ID = "soundmanagerservice_notification_channel";
public static final int FINISH_NOTIFICATION_ID = 2;
public static final int START_NOTIFICATION_ID = 1;
public static final String EXTRA_KEY_ISPLAYING = "isPlaying";
MediaPlayer _player;
public SoundManageService() {
}
private class PlayerPreparedListener implements MediaPlayer.OnPreparedListener{
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
NotificationCompat.Builder builder = new NotificationCompat.Builder(SoundManageService.this,CHANNEL_ID);
builder.setSmallIcon(android.R.drawable.ic_dialog_info);
builder.setContentTitle(getString(R.string.msg_notification_title_start));
builder.setContentText(getString(R.string.msg_notification_text_start));
Intent intent = new Intent(SoundManageService.this,MainActivity.class);
intent.putExtra(EXTRA_KEY_ISPLAYING,mp.isPlaying());
PendingIntent stopServiceIntent = PendingIntent.getActivity(
SoundManageService.this,0,intent,PendingIntent.FLAG_CANCEL_CURRENT);
builder.setContentIntent(stopServiceIntent);
builder.setAutoCancel(true);
Notification notification = builder.build();
startForeground(START_NOTIFICATION_ID,notification);
}
}
private class PlayerCompletionListener implements MediaPlayer.OnCompletionListener{
#Override
public void onCompletion(MediaPlayer mp) {
stopSelf();
sendMessage();
}
}
private void sendMessage() {
Intent intent = new Intent(MainActivity.INTENT_ACTION);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
#Override
public void onCreate(){
super.onCreate();
_player = new MediaPlayer();
String channelName = getString(R.string.notification_channnel_name);
int notificationImportance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID,channelName,notificationImportance);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(notificationChannel);
}
#Override
public int onStartCommand(Intent intent,int flags,int startId){
super.onStartCommand(intent,flags,startId);
String mediaUriStr ="android.resource://" + getPackageName() + "/" + R.raw.testmusic;
Uri uri = Uri.parse(mediaUriStr);
_player = new MediaPlayer();
try{
_player.setDataSource(SoundManageService.this,uri);
_player.setOnPreparedListener(new PlayerPreparedListener());
_player.setOnCompletionListener(new PlayerCompletionListener());
_player.prepareAsync();
} catch (IOException e) {
Log.e("ServiceSample", "メディアプレーヤー準備失敗");
}
return START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
super.onBind(intent);
return null;
}
#Override
public boolean onUnbind(Intent intent){
return true;
}
#Override
public void onDestroy(){
if(_player.isPlaying()){
_player.stop();
}
_player.release();
_player = null;
super.onDestroy();
}
}
Changing the code (creating Intent for PendingIntent for Notification)
Intent intent = new Intent(SoundManageService.this,MainActivity.class);
to
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setClassName(getApplicationContext().getPackageName(), MainActivity.class.getName());
intent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED | Intent.FLAG_ACTIVITY_NEW_TASK);
made the problem solved.
https://qiita.com/imp954sti/items/e075fb8a99b68dda8180
↑this Japanese note helped me.
I'm developing android application using local notifications. I was implemented local notifications using Services. In services local notifications work but when I kill the app the service destroyed. Notifications not working. Now I want to implement local notifications using alarm manager how can I do this with alarm manager
Here is Service Class.
import android.app.AlarmManager;
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.content.SharedPreferences;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;
import com.deemsysinc.cyberhealthapp.R;
import com.deemsysinc.cyberhealthapp.weightgoal.WeightGoalActivity;
import com.google.gson.Gson;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;
public class NotificationService extends Service{
private IBinder iBinder=new MyBinder();
SharedPreferences prefs;
SharedPreferences.Editor editor;
Handler handler;
// timer handling
NotificationManager manager;
Notification myNotication;
static TimerTask timerTask;
Date date1;
Date date2;
ArrayList<NotificationList> notificationLists;
int temp=0;
#Override
public void onRebind(Intent intent) {
super.onRebind(intent);
}
#Override
public boolean onUnbind(Intent intent) {
return true;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return iBinder;
}
#Override
public void onCreate() {
super.onCreate();
handler=new Handler();
prefs = getSharedPreferences(configuration.AppPrefernce, MODE_PRIVATE);
editor = prefs.edit();
notificationLists=new ArrayList<NotificationList>();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
timerStart();
//Remove();
return Service.START_STICKY;
}
public void showNotifications()
{
Calendar cal = Calendar.getInstance();
Date currentLocalTime = cal.getTime();
DateFormat date = new SimpleDateFormat("hh:mm a");
String localTime = date.format(currentLocalTime);
String converted = localTime.replace("am", "AM").replace("pm", "PM");
Toast.makeText(getApplicationContext(),"Timer Running",Toast.LENGTH_LONG).show();
Log.d("Locals",""+local);
//Toast.makeText(getApplicationContext(),"Service Checked",Toast.LENGTH_SHORT).show();
if(!prefs.getString("weight_hr","").equals("")) {
if (prefs.getString("weight_hr", "").equals(converted)) {
temp++;
Bundle bundle=new Bundle();
//SimpleDateFormat writeformat = new SimpleDateFormat("dd/MM/yyyy");
//String formattedDate = writeformat.format(calendar.getTime());
if(temp==1) {
notificationLists.add(new NotificationList("Weight", "It's time to log your weight today. Click to update weight!", ""));
Gson gson = new Gson();
String json = gson.toJson(notificationLists);
editor.putString("notificationlist", json);
editor.commit();
bundle.putString("fromNotificationCenter","1");
}
else
{
bundle.putString("fromNotificationCenter","0");
}
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(getApplicationContext(), WeightGoalActivity.class);
notificationIntent.putExtras(bundle);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 6, notificationIntent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext());
builder.setAutoCancel(true);
builder.setContentTitle("Cyberhealths");
builder.setContentText("It's time to log your weight today. Click to update weight!");
builder.setSmallIcon(R.drawable.my_icon);
builder.setContentIntent(pendingIntent);
builder.setOngoing(false);
manager.notify(6, builder.build());
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
timer.cancel();
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.cancel(6);
Toast.makeText(getApplicationContext(),"Service Destroyed",Toast.LENGTH_LONG).show();
}
private void timerStart() {
timer = new Timer();
timerTask = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
showNotifications();
} catch (Exception e) {
}
}
});
}
};
timer.scheduleAtFixedRate(timerTask, 0, 65000);
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Intent restartService = new Intent(getApplicationContext(),
this.getClass());
restartService.setPackage(getPackageName());
PendingIntent restartServicePI = PendingIntent.getService(
getApplicationContext(), 1, restartService,
PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000, restartServicePI);
}
private void runOnUiThread(Runnable runnable) {
handler.post(runnable);
}
public class MyBinder extends Binder {
public NotificationService getService() {
return NotificationService.this;
}
}
}
From the documentation of startForeground():
Make this service run in the foreground, supplying the ongoing
notification to be shown to the user while in this state. By default
services are background, meaning that if the system needs to kill them
to reclaim more memory (such as to display a large page in a web
browser), they can be killed without too much harm. You can set this
flag if killing your service would be disruptive to the user, such as
if your service is performing background music playback, so the user
would notice if their music stopped playing.
In your showNotification() method you need to start service on foreground upon Notification,
int FOREGROUND_ID = 6;
....
builder.setOngoing(false);
Notification notification = builder.build();
manager.notify(FOREGROUND_ID, notification);
startForeground(FOREGROUND_ID, notification);
Once you need to stop the service, simply call:
stopForeground(**false / true**);
Pass false if you don't want Notification to be removed once service stops, or true if you want that Notification should be removed automatically.
I have the following code in which I have one date picker and time picker
When I select that date and time I want to show notification...
It is perfectly working but when I again put notification means if I pu6 multiple notification it will show me only last one...
Means only last notification is showing not all...
NotifyService.java
package com.blundell.tut.service;
import android.R;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import com.blundell.tut.ui.phone.SecondActivity;
public class NotifyService extends Service {
/**
* Class for clients to access
*/
public class ServiceBinder extends Binder {
NotifyService getService() {
return NotifyService.this;
}
}
// Unique id to identify the notification.
public static int NOTIFICATION = 123;
// Name of an intent extra we can use to identify if this service was started to create a notification
public static final String INTENT_NOTIFY = "com.blundell.tut.service.INTENT_NOTIFY";
// The system notification manager
private NotificationManager mNM;
#Override
public void onCreate() {
Log.i("NotifyService", "onCreate()");
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
// If this service was started by out AlarmTask intent then we want to show our notification
if(intent.getBooleanExtra(INTENT_NOTIFY, false))
showNotification();
// We don't care if this service is stopped as we have already delivered our notification
return START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
// This is the object that receives interactions from clients
private final IBinder mBinder = new ServiceBinder();
/**
* Creates a notification and shows it in the OS drag-down status bar
*/
private void showNotification() {
// This is the 'title' of the notification
CharSequence title = "Alarm!!";
// This is the icon to use on the notification
int icon = R.drawable.ic_dialog_alert;
// This is the scrolling text of the notification
CharSequence text = "Your notification time is upon us.";
// What time to show on the notification
long time = System.currentTimeMillis();
Notification notification = new Notification(icon, text, time);
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, SecondActivity.class), 0);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, title, text, contentIntent);
// Clear the notification when it is pressed
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
NOTIFICATION++;
Toast.makeText(NotifyService.this, Integer.toString(NOTIFICATION), Toast.LENGTH_SHORT).show();
mNM.notify(NOTIFICATION, notification);
// Stop the service when we are finished
stopSelf();
}
}
ScheduleClient.java
package com.blundell.tut.service;
import java.util.Calendar;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
/**
* This is our service client, it is the 'middle-man' between the
* service and any activity that wants to connect to the service
*
* #author paul.blundell
*/
public class ScheduleClient {
// The hook into our service
private ScheduleService mBoundService;
// The context to start the service in
private Context mContext;
// A flag if we are connected to the service or not
private boolean mIsBound;
public ScheduleClient(Context context) {
mContext = context;
}
/**
* Call this to connect your activity to your service
*/
public void doBindService() {
// Establish a connection with our service
mContext.bindService(new Intent(mContext, ScheduleService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
/**
* When you attempt to connect to the service, this connection will be called with the result.
* If we have successfully connected we instantiate our service object so that we can call methods on it.
*/
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with our service has been established,
// giving us the service object we can use to interact with our service.
mBoundService = ((ScheduleService.ServiceBinder) service).getService();
}
public void onServiceDisconnected(ComponentName className) {
mBoundService = null;
}
};
/**
* Tell our service to set an alarm for the given date
* #param c a date to set the notification for
*/
public void setAlarmForNotification(Calendar c){
mBoundService.setAlarm(c);
}
/**
* When you have finished with the service call this method to stop it
* releasing your connection and resources
*/
public void doUnbindService() {
if (mIsBound) {
// Detach our existing connection.
mContext.unbindService(mConnection);
mIsBound = false;
}
}
}
ScheduleService.java
package com.blundell.tut.service;
import java.util.Calendar;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import com.blundell.tut.service.task.AlarmTask;
public class ScheduleService extends Service {
/**
* Class for clients to access
*/
NotifyService ns=new NotifyService();
public class ServiceBinder extends Binder {
ScheduleService getService() {
return ScheduleService.this;
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("ScheduleService", "Received start id " + ns.NOTIFICATION + ": " + intent);
// We want this service to continue running until it is explicitly stopped, so return sticky.
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
// This is the object that receives interactions from clients. See
private final IBinder mBinder = new ServiceBinder();
/**
* Show an alarm for a certain date when the alarm is called it will pop up a notification
*/
public void setAlarm(Calendar c) {
// This starts a new thread to set the alarm
// You want to push off your tasks onto a new thread to free up the UI to carry on responding
new AlarmTask(this, c).run();
}
}
AlarmTask.java
package com.blundell.tut.service.task;
import java.util.Calendar;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import com.blundell.tut.service.NotifyService;
public class AlarmTask implements Runnable{
// The date selected for the alarm
private final Calendar date;
// The android system alarm manager
private final AlarmManager am;
// Your context to retrieve the alarm manager from
private final Context context;
public AlarmTask(Context context, Calendar date) {
this.context = context;
this.am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
this.date = date;
}
#Override
public void run() {
// Request to start are service when the alarm date is upon us
// We don't start an activity as we just want to pop up a notification into the system bar not a full activity
Intent intent = new Intent(context, NotifyService.class);
intent.putExtra(NotifyService.INTENT_NOTIFY, true);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
// Sets an alarm - note this alarm will be lost if the phone is turned off and on again
am.set(AlarmManager.RTC_WAKEUP, date.getTimeInMillis(), pendingIntent);
long firstTime = date.getTimeInMillis();
am.setRepeating(AlarmManager.RTC_WAKEUP, firstTime, am.INTERVAL_DAY * 7, pendingIntent);
}
}
MainActivity.java
package com.blundell.tut.ui.phone;
import java.util.Calendar;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.widget.Toast;
import com.blundell.tut.R;
import com.blundell.tut.service.NotifyService;
import com.blundell.tut.service.ScheduleClient;
public class MainActivity extends Activity
{
// This is a handle so that we can call methods on our service
private ScheduleClient scheduleClient;
private DatePicker picker;
NotifyService ns;
private TimePicker tp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scheduleClient = new ScheduleClient(this);
scheduleClient.doBindService();
ns=new NotifyService();
picker = (DatePicker) findViewById(R.id.scheduleTimePicker);
tp=(TimePicker)findViewById(R.id.TimePicker);
tp.setIs24HourView(true);
}
public void onDateSelectedButtonClick(View v){
int day = picker.getDayOfMonth();
int month = picker.getMonth();
int year = picker.getYear();
int hour=tp.getCurrentHour();
int min=tp.getCurrentMinute();
// Create a new calendar set to the date chosen
// we set the time to midnight (i.e. the first minute of that day)
Calendar c = Calendar.getInstance();
c.set(year, month, day,hour,min,0);
scheduleClient.setAlarmForNotification(c);
// Notify the user what they just did
//Toast.makeText(this, Integer.toString(ns.NOTIFICATION), Toast.LENGTH_SHORT).show();
//Toast.makeText(this, "Notification set for: "+ day +"/"+ (month+1) +"/"+ year, Toast.LENGTH_SHORT).show();
}
#Override
protected void onStop()
{
// When our activity is stopped ensure we also stop the connection to the service
// this stops us leaking our activity into the system *bad*
if(scheduleClient != null)
scheduleClient.doUnbindService();
super.onStop();
}
}
SecondActivity.java
package com.blundell.tut.ui.phone;
import android.app.Activity;
import android.os.Bundle;
import com.blundell.tut.R;
/**
* This is the activity that is started when the user presses the notification in the status bar
* #author paul.blundell
*/
public class SecondActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
}
Please suggest me at which place i have to change code...????
In this line,
mNM.notify(NOTIFICATION, notification);
Just make sure that each time the different value of NOTIFICATION is being passed.
at AlarmTask.java, you are hard coded always 0 in PendingIntent.
requestCode must be
UNIQUE INTEGER NUMBER
so change your code,
from
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
to
int random = (int)System.currentTimeMillis();
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, random, intent, 0);
Just write code like this.
int random = (int)System.currentTimeMillis();
manager.notify(random , activeNotification);
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);
I'm new to android and I have the following code in my Service :
int icon = R.drawable.gcm_notification;
long when = System.currentTimeMillis();
String notificationText = "Message From SimplePay";
//get the notification service
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon,notificationText,when);
String title = context.getString(R.string.app_name);
String messageBody = "You have " + 1 + " payment request pending";
Intent notificationIntent = new Intent(context,InvoiceActivity.class);
notificationIntent.putExtra("invoice",message);
System.out.println(message);
//always create a new activity! So recent values get updated
PendingIntent intent = PendingIntent.getActivity(context,0,notificationIntent,PendingIntent.FLAG_ONE_SHOT);
notification.setLatestEventInfo(context,title,messageBody,intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0,notification);
and I can see that message that I'm passing to intent is present (i.e its not null) . But on my InvoiceActivity side when I try to get the message value back I get null all time. I use the following code in InvoiceActivity like this:
Bundle extras = getIntent().getExtras();
message = extras.getString("invoice");
System.out.println(message); //always null
I'm not sure why this happens. Where I'm making the mistake?
Thanks in advance.
This is what I have for the service: (Make sure you are using the correct intent inside onReceive. onReceive receives an intent; the one that started the service. I noticed that when Eclipse creates onReceive the default name for the Intent parameter is "intent"(You do not want to use this one). Also, why are you using the variable context instead of the keyword this? The Service class extends ContextWrapper which extends Context.
package com.example.solution;
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;
public class Serv extends Service {
#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
String message = "Hello";
long when = System.currentTimeMillis();
String notificationText = "Message From SimplePay";
//get the notification service
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher, notificationText,when);
String title = this.getString(R.string.app_name);
String messageBody = "You have " + 1 + " payment request pending";
Intent notificationIntent = new Intent(this,InvoiceActivity.class);
notificationIntent.putExtra("invoice",message);
//always create a new activity! So recent values get updated
PendingIntent intentp = PendingIntent.getActivity(this,0,notificationIntent,PendingIntent.FLAG_ONE_SHOT);
notification.setLatestEventInfo(this,title,messageBody,intentp);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0,notification);
return START_STICKY;
}
}
Here are the Main Activity (Launcher).
package com.example.solution;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
startService(new Intent(this,Serv.class));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
stopService(new Intent(this,Serv.class));
}
}
and here is InvoiceActivity
package com.example.solution;
import android.app.Activity;
import android.util.Log;
public class InvoiceActivity extends Activity {
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.e("MESSAGE",getIntent().getExtras().getString("invoice"));
}
}
Hope this helps
if your activity is running, the new intent is probably delivered in onNewIntent
#Override
protected void onNewIntent(Intent intent)
{
super.onNewIntent(intent);
message = getIntent().getStringExtra("invoice");
System.out.println(message); //always null
}