In our android webview app, we start a foreground service (RingtonePlayingservice.class) from our firebase.class on notification action. The foreground service in turn starts playing the ringtone vide mediaplayer. The ringtone runs to like 10 seconds and stops, so we implemented setloop parameter, but still the mediaplayer just stops without looping at all. We are at loss as where we are going wrong. The codes are as given below
Firebase.Class (summarized)
public class Firebase extends FirebaseMessagingService {
public static Ringtone ringtone;
Intent i = new Intent(this, RingtonePlayingService.class);
this.startForegroundService(i);
}
Ringtoneplayingservice class
public class RingtonePlayingService extends Service {
private static final String TAG = RingtonePlayingService.class.getSimpleName();
private static final String URI_BASE = RingtonePlayingService.class.getName() + ".";
public static final String ACTION_DISMISS = URI_BASE + "ACTION_DISMISS";
public static final String ACTION_START = URI_BASE + "ACTION_START";
private MediaPlayer mp;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand");
if (intent == null) {
Log.d(TAG, "The intent is null.");
return START_REDELIVER_INTENT;
}
String action = intent.getAction();
if (ACTION_DISMISS.equals(action)) {
int notificationId = intent.getIntExtra("notificationId", 0);
dismissRingtone();
NotificationManager notificationManager =
(NotificationManager) getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
notificationManager.cancel(notificationId);
}
else {
mp = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
mp.setlooping (true);
mp.start();
}
return START_STICKY;
}
public void dismissRingtone() {
// stop the alarm rigntone
Intent i = new Intent(this, RingtonePlayingService.class);
this.stopService(i);
}
#Override
public void onDestroy() {
super.onDestroy();
if(mp.isPlaying())
{
mp.reset();
}
else {
}
}}
Any help would be deeply appreciated
Related
When the app is in the foreground can get calls well, but when is in the background and a call is active and the run app: it can not get that's call.
When the app is in the foreground, get call works well (get push-notification and connecting is being automatically, also you can push "Incoming Call" notification to connecting call).
I fixed it in swift but I cant fix it for android.
ios fixed with this funcs:
func applicationDidEnterBackground(_ application: UIApplication) {
if !isCallScreen {
UIApplication.shared.unregisterForRemoteNotifications()
}
}
func funBack() {
let state = UIApplication.shared.applicationState
if state == .background {
UIApplication.shared.unregisterForRemoteNotifications()
}
if isCallScreen {
isCallScreen = false
DispatchQueue.main.async {
self.window?.rootViewController?.navigationController?.popViewController(animated: true)
}
}
}
Messaging service
public class MessagingService extends FirebaseMessagingService {
private int notificationNumber = 1;
private LocalBroadcastManager broadcaster;
private int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
private DatabaseReference mDatabase;
private SinchClient sinchClient;
private SharedPref pref;
public static boolean firsttimeFun = true;
#Override
public void onCreate() {
broadcaster = LocalBroadcastManager.getInstance(this);
pref = new SharedPref(this);
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//
if (SinchHelpers.isSinchPushPayload(remoteMessage.getData())) {
NotificationResult result = sinchClient.relayRemotePushNotificationPayload(
remoteMessage.getData());
}
if (!AppLifecycleListener.isActivityVisible()) {
AppLifecycleListener.activityResumed();
}
// it's NOT Sinch message - process yourself
class FcmListenerService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage){
Map data = remoteMessage.getData();
if (SinchHelpers.isSinchPushPayload(data)) {
new ServiceConnection() {
private Map payload;
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
if (sinchClient != null) {
NotificationResult result = sinchClient.relayRemotePushNotificationPayload(payload);
// handle result, e.g. show a notification or similar
}
}
#Override
public void onServiceDisconnected(ComponentName name) {}
public void relayMessageData(Map<String, String> data) {
payload = data;
getApplicationContext().bindService(new Intent(getApplicationContext(), CallActivity.class), this, BIND_AUTO_CREATE);
}
}.relayMessageData(data);
}
}
}
// String bundleString = remoteMessage.getNotification().getBody();
//
// String bundleString = remoteMessage.getData().get("message");
Map bundle = remoteMessage.getData();
String callId = bundle.get("callID").toString();
String groupname = bundle.get("group").toString();
try {
bundle.get("hangup").toString();
Intent intent = new Intent("MyData");
intent.putExtra("callID", callId);
broadcaster.sendBroadcast(intent);
return;
} catch (Exception e) {
e.printStackTrace();
}
//IF app is in background use return for ignore notifications
if (!AppLifecycleListener.isActivityVisible()) {
sendNotification(callId, groupname);
//return;
}
Log.i("MessageFrom", "From: " + callId);
if (firsttimeFun) {
firsttimeFun = false;
startActivity(new Intent(this, CallActivity.class).putExtra("callerId", callId).putExtra("name", groupname).putExtra("isOutGoing", false).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
if (AppLifecycleListener.isActivityVisible())
sendNotification(callId, groupname);
//return;
// sendNotification(bundle.get("message").toString());
}
#Override
public void onNewToken(String s) {
/* HashMap map=new HashMap();
map.put("fcmToken",s);
mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("Users").child(pref.getUserId()).updateChildren(map);*/
}
#RequiresApi(api = Build.VERSION_CODES.N)
private void sendNotification(String callId, String groupname) {
PendingIntent contentIntent;
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, CallActivity.class).putExtra("callerId", callId).putExtra("name", groupname).putExtra("isOutGoing", false), 0);
int notifyID = 1;
String CHANNEL_ID = "CallAppChanel";// The id of the channel.
CharSequence name = getString(R.string.channel_name);// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mChannel = new NotificationChannel(CHANNEL_ID, "Channel 1", importance);
}
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.icon)
.setContentTitle("Incoming Call")
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setContentIntent(contentIntent)
.setColor(getResources().getColor(R.color.purple))
.setAutoCancel(true)
.setOnlyAlertOnce(true)
.setChannelId(CHANNEL_ID)
.setPriority(importance)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.build();
int notificationId = new Random().nextInt(100) + 1;
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mNotificationManager.createNotificationChannel(mChannel);
mNotificationManager.notify(notificationId, notification);
} else {
mNotificationManager.notify(notificationId, notification);
}
}
}
AppLifecycleListener
public class AppLifecycleListener extends Application implements Application.ActivityLifecycleCallbacks, LifecycleObserver {
private Context context;
Activity activityRunning;
private static Application instance;
private static boolean activityVisible;
private boolean inForeground;
public void setContext(Context context) {
this.context = context;
}
public Context getContext() {
return this.context;
}
public static Context getContextApp() {
return instance.getApplicationContext();
}
#Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
/*getVersionRequest(this);*/
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
activityRunning = activity;
}
#Override
public void onActivityStarted(#NonNull Activity activity) {
}
#Override
public void onActivityResumed(Activity activity) {
// Utility.logCatMsg("Activity Resume : " + activity.getLocalClassName());
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener((Activity) context, new OnSuccessListener<InstanceIdResult>() {
#Override
public void onSuccess(InstanceIdResult instanceIdResult) {
String newToken = instanceIdResult.getToken();
Log.e("newToken",newToken);
}
});
}
#Override
public void onActivityPaused(Activity activity) {
// Utility.logCatMsg("Activity Pause : " + activity.getLocalClassName());
}
#Override
public void onActivityStopped(Activity activity) {
// Utility.logCatMsg("Activity Stop : " + activity.getLocalClassName());
}
#Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
#Override
public void onActivityDestroyed(Activity activity) {
// Utility.logCatMsg("Activity Destroyed : " + activity.getLocalClassName());
}
public static boolean isActivityVisible() {
return activityVisible;
}
public static void activityResumed() {
activityVisible = true;
}
public static void activityPaused() {
activityVisible = false;
}
}
I made an Android app that should play a sound when event is received, it works when app is in focus, but when the app is closed/collapsed sound doesnt play, only standard notification.
How to start a sound/music that is placed inside the app when app with the foreground service?
Main activity:
public class MainActivity extends AppCompatActivity {
private Intent alarmServiceIntent;
private ServiceConnection sConn;
private boolean bound;
private boolean alarm = false;
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Init();
}
private void Init() {
alarmServiceIntent = new Intent(this, AlarmService.class);
sConn = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder binder) {
bound = true;
}
public void onServiceDisconnected(ComponentName name) {
bound = false;
}
};
ContextCompat.startForegroundService(this, alarmServiceIntent);
}
private void playAlarm() {
bindService(alarmServiceIntent, sConn, BIND_AUTO_CREATE);
}
public void stopAlarm(View v) {
if (sConn != null ) {
unbindService(sConn);
}
if(alarmServiceIntent != null) {
stopService(alarmServiceIntent);
}
}
//here is the method to receive event and call playAlarm
}
Alarm service:
public class AlarmService extends Service{
private final String CHANNEL_ID = "ID";
private final String CHANNEL_NAME = "NAME";
private IBinder mBinder = new MyBinder();
private MediaPlayer player;
#Nullable
#Override
public IBinder onBind(Intent intent) {
play();
return mBinder;
}
#Override
public boolean onUnbind(Intent intent) {
onStop();
return super.onUnbind(intent);
}
#Override
public void onCreate() {
player = MediaPlayer.create(this,R.raw.alarm);
player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
pendingIntent = PendingIntent.getActivity
(this, 0, notificationIntent, PendingIntent.FLAG_MUTABLE);
}
else
{
pendingIntent = PendingIntent.getActivity
(this, 0, notificationIntent, PendingIntent.FLAG_ONE_SHOT);
}
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("TITLE")
.setSmallIcon(R.mipmap.icon)
.setContentIntent(pendingIntent)
.build();
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel( CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
mNotificationManager.createNotificationChannel(channel);
new NotificationCompat.Builder(this, CHANNEL_ID);
}
startForeground(619, notification);
return START_REDELIVER_INTENT;
}
public void play() {
if(player == null) {
player = MediaPlayer.create(this,R.raw.alarm);
player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
}
Log.v("ALARM", "play: 12345");
player.setAudioAttributes(
new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_ALARM)
.build()
);
player.setVolume(2,2);
AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
// audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
player.setLooping(true);
player.start();
}
class MyBinder extends Binder {
AlarmService getService(){
return AlarmService.this;
}
}
}
You should override onDestroy method and call stop there.
#Override
public void onDestroy() {
player.stop();
}
I've made an Android app that main feature is to play audio stream from my server. But for some reason music stops playing after about 20 minutes and the app is throwing ProtocolException (logs from app on Android Studio logcat image).
Android Studio logcat
This error is even more weird because it occurs only on some devices. Error occurs on multiple Xiaomi devices (all with Android 10) and Samsung Galaxy S9 (also with Android 10) but on Samsung Galaxy S10 (Android 10) and Huawai tablet that error doesn't occur and music is being played as long as user does not stop it.
This is my PlayerService class code that is responsible for running MediaPlayer as a service:
public class PlayerService extends Service {
private static final String CHANNEL_ID = "PlayerServiceChannel";
private static final int SERVICE_ID = 1;
private MediaPlayer player;
private Notification notification;
private JsonObjectHandler jsonObjectHandler;
private int streamIndex = 9999;
private Messenger messenger;
private PendingIntent pendingIntent;
private NotificationManager notificationManager;
private PendingIntent closeApp;
private WifiManager.WifiLock wifiLock;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
JSONObject jsonObject = new JSONObject(Objects.requireNonNull(intent.getStringExtra("JsonInfo")));
jsonObjectHandler = new JsonObjectHandler(jsonObject);
} catch (JSONException e) {
jsonObjectHandler = null;
}
return START_REDELIVER_INTENT;
}
#Override
public void onCreate() {
super.onCreate();
wifiLock = ((WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE))
.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "playerServiceWiFiLock");
HandlerThread thread = new HandlerThread("ServiceStartArgument", Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
Looper mServiceLooper = thread.getLooper();
ServiceHandler mServiceHandler = new ServiceHandler(mServiceLooper);
messenger = new Messenger(mServiceHandler);
PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
case TelephonyManager.CALL_STATE_OFFHOOK:
stopForeground(true);
stopSelf();
break;
case TelephonyManager.CALL_STATE_IDLE:
break;
}
super.onCallStateChanged(state, incomingNumber);
}
};
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if (mgr != null) {
mgr.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
createNotificationChannel();
Intent notificationIntent = new Intent(this, LoginActivity.class);
pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
stopSelf();
unregisterReceiver(this);
System.exit(0);
}
};
IntentFilter intentFilter = new IntentFilter("android.intent.CLOSE_APP");
registerReceiver(broadcastReceiver, intentFilter);
Intent intentClose = new Intent("android.intent.CLOSE_APP");
closeApp = PendingIntent.getBroadcast(this, 0, intentClose, 0);
updateNotification(streamIndex);
startForeground(SERVICE_ID, notification);
}
private NotificationCompat.Builder createNotification(int streamIndex) {
String defaultValue;
if (jsonObjectHandler == null || streamIndex == 9999) {
defaultValue = "";
} else {
defaultValue =
jsonObjectHandler.getPlaylistButtons().get(streamIndex).getButtonName();
}
return new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ikonastream48)
.setContentIntent(pendingIntent)
.setContentTitle(getString(R.string.app_name))
.setContentText(defaultValue)
.setDefaults(0)
.setSound(null)
.addAction(R.drawable.ic_close_black, getString(R.string.close), closeApp);
}
private void updateNotification(int streamIndex) {
notification = createNotification(streamIndex).build();
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert notificationManager != null;
notificationManager.notify(SERVICE_ID, notification);
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID, "Example Service Channel", NotificationManager.IMPORTANCE_DEFAULT);
serviceChannel.setSound(null, null);
notificationManager = getSystemService(NotificationManager.class);
if (notificationManager != null) {
notificationManager.createNotificationChannel(serviceChannel);
}
}
}
private void stopServicePlayer() {
if (player != null) {
player.stop();
player.reset();
player.release();
player = null;
}
stopForeground(true);
}
#Override
public void onDestroy() {
super.onDestroy();
stopServicePlayer();
if (wifiLock.isHeld()) wifiLock.release();
}
private void sendMessageBroadcast(Intent intent) {
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
if (streamIndex != 9999) {
Intent intent1 = new Intent("streamIndex");
intent1.putExtra("INDEX", streamIndex);
sendMessageBroadcast(intent1);
}
return messenger.getBinder();
}
private final class ServiceHandler extends Handler {
ServiceHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 0) {
player = new MediaPlayer();
player.setOnErrorListener((mp, what, extra) -> false);
player.setAudioAttributes(new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_MEDIA)
.build());
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
streamIndex = msg.arg1;
updateNotification(streamIndex);
try {
player.setOnPreparedListener(mediaPlayer -> {
mediaPlayer.start();
Intent intent = new Intent("streamIndex");
intent.putExtra("INDEX", streamIndex);
sendMessageBroadcast(intent);
});
player.setDataSource(jsonObjectHandler
.getPlaylistButtons()
.get(streamIndex)
.getButtonStreamAddress());
} catch (IOException e) {
e.printStackTrace();
}
player.prepareAsync();
if (!wifiLock.isHeld()) wifiLock.acquire();
} else if (msg.what == 1) {
Intent intent2 = new Intent("streamIndex");
intent2.putExtra("INDEX", streamIndex);
sendMessageBroadcast(intent2);
}
}
}
}
Thank you for all responses in advance!
P.S. The code was written few years ago (at the beginning of my programming journey), so I'm aware that it looks bad and need to be rewritten in better way.
Disable caches and retry :
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "audio/mp3");
headers.put("Accept-Ranges", "bytes");
headers.put("Status", "206");
headers.put("Cache-control", "no-cache");
Uri uri = Uri.parse(yourContentUrl);
player.setDataSource(getApplicationContext(), uri, headers);
The problem was on the server side. When the stream was switched from CBR to the VBR in the Lame encoder, the problem stop occurring.
SO, I have a MainActivity that has a button which starts a service, MyService. I want the service to show the notification with a custom title,text,icon,etc. The service is a foreground service. not a bound service. everything works fine but the only thing is about my notification is keep showing "tap for more information" and clicking on it leads me to the settings page of my application. despite having the pendingIntent on my MainActivity.
What I want is to have a Notification with custom Title,Text,icon and an action to stop the service.
this is my MainActivity.java class
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.start_tracking).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startCommand();
}
});
}
void startCommand() {
startService(new Intent(this, MyService.class));
}
}
Myservice.java file
public class MyService extends Service {
boolean mServiceIsStarted = false;
void moveToStartedState() {
Intent myIntentbuilder = new IntentBuilder(this).setmCommandId(Command.START).build();
Log.d(TAG, "moveToStartedState: Running on Android O - startForegroundService(intent)");
ContextCompat.startForegroundService(this, myIntentbuilder);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand: ");
boolean containsCommand = IntentBuilder.containsCommand(intent);
routeIntentToCommand(intent);
return START_NOT_STICKY;
}
void routeIntentToCommand(Intent intent) {
if (intent != null) {
if (IntentBuilder.containsCommand(intent)) {
processCommand(IntentBuilder.getCommand(intent));
} else
commandStart();
}
}
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate: ");
}
void showNotification() {
Log.d(TAG, "showNotification: ");
HandleNotification.O.createNotification(this);
}
private void processCommand(int command) {
try {
switch (command) {
case Command.START:
commandStart();
break;
case Command.STOP:
commandStop();
break;
}
} catch (Exception e) {
e(TAG, "processCommand: exception", e);
}
}
void commandStop() {
stopSelf();
stopForeground(true);
}
void commandStart() {
if (!mServiceIsStarted) {
mServiceIsStarted = true;
moveToStartedState();
return;
}
//
HandleNotification.O.createNotification(this);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
IntentBuilder.java class
#IntDef({Command.INVALID, Command.STOP, Command.START})
#Retention(RetentionPolicy.SOURCE)
#interface Command {
int INVALID = -1;
int STOP = 0;
int START = 1;
}
public class IntentBuilder {
private static final String KEY_MESSAGE = "msg";
private static final String KEY_COMMAND = "cmd";
private Context mContext;
private String mMessage;
private #Command
int mCommandId = Command.INVALID;
public static IntentBuilder getInstance(Context mContext) {
return new IntentBuilder(mContext);
}
public IntentBuilder(Context mContext) {
this.mContext = mContext;
}
public void setmContext(Context mContext) {
this.mContext = mContext;
}
public IntentBuilder setmMessage(String mMessage) {
this.mMessage = mMessage;
return this;
}
public IntentBuilder setmCommandId(int mCommandId) {
this.mCommandId = mCommandId;
return this;
}
private static final String TAG = "IntentBuilder";
public Intent build() {
Log.e(TAG, "build: context cannot be null" + mContext);
Intent intent = new Intent(mContext, MyService.class);
if (mMessage != null)
intent.putExtra(KEY_MESSAGE, mMessage);
if (mCommandId != Command.INVALID)
intent.putExtra(KEY_COMMAND, mCommandId);
return intent;
}
public static boolean containsCommand(Intent intent) {
return intent.getExtras() != null && intent.getExtras().containsKey(KEY_COMMAND);
}
public static boolean containsMessage(Intent intent) {
return intent.getExtras() != null && intent.getExtras().containsKey(KEY_MESSAGE);
}
public static #Command
int getCommand(Intent intent) {
final #Command int commandId = intent.getExtras().getInt(KEY_COMMAND);
return commandId;
}
public static String getMessage(Intent intent) {
return intent.getExtras().getString(KEY_MESSAGE);
}
}
HandleNotification.java file
public class HandleNotification {
public static class O {
public static int getRandomNumber() {
return new Random().nextInt(100000);
}
static PendingIntent getLaunchActivityPI(Service context) {
Intent intent = new Intent(context, MainActivity.class);
return PendingIntent.getActivity(context, getRandomNumber(), intent, 0);
}
static PendingIntent getStopServicePI(Service context) {
PendingIntent pendingIntent;
{
Intent intent = new IntentBuilder(context).setmCommandId(Command.STOP).build();
pendingIntent = PendingIntent.getService(context, getRandomNumber(), intent, 0);
}
return pendingIntent;
}
public static final Integer ONGOING_NOTIFICATION_ID = getRandomNumber();
public static final String CHANNEL_ID = String.valueOf(getRandomNumber());
private static final String TAG = "O";
public static void createNotification(Service context) {
Log.d(TAG, "createNotification: ");
String channelId = createChannel(context);
Notification notification = buildNotification(channelId, context);
context.startForeground(ONGOING_NOTIFICATION_ID, notification);
}
static Notification buildNotification(String channelId, Service context) {
PendingIntent piMainActivity = getLaunchActivityPI(context);
PendingIntent piStopService = getStopServicePI(context);
Icon poweroff = Icon.createWithResource(context, android.R.drawable.star_big_on);
Notification.Action stopAction = new Notification.Action
.Builder(poweroff, "STOP", piStopService).build();
return new Notification.Builder(context, channelId)
.addAction(stopAction)
.setContentTitle("Tracking...")
.setContentText("I'm tracking your location now... ")
.setContentIntent(piMainActivity)
.build();
}
#NonNull
private static String createChannel(Context service) {
NotificationManager notificationManager = (NotificationManager) service.getSystemService(Context.NOTIFICATION_SERVICE);
CharSequence channelName = "Start Location Updates";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, channelName, importance);
notificationManager.createNotificationChannel(notificationChannel);
return CHANNEL_ID;
}
}
}
Use NotificationCompat.Builder. You can follow how to create one here
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(textTitle)
.setContentText(textContent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
You can add your custom small or big icon, title, content, and other properties.
An example from a project that I did long ago
private void LockNotification() {
NotificationCompat.Builder builder = new
NotificationCompat.Builder(getApplicationContext());
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("key","launch_about");
PendingIntent pendingIntent =
PendingIntent.getActivity(getApplicationContext(), 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
// Set the title, text, and icon
builder.setContentTitle(getString(R.string.app_name))
.setContentText("App Lock Enabled")
.setSmallIcon(R.drawable.ic_applock)
.setContentIntent(pendingIntent)
.setOngoing(true);
// Get an instance of the Notification Manager
NotificationManager notifyManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
// Build the notification and post it
notifyManager.notify(0, builder.build());
}
I'm doing an app that checks the live scores. I don't know if it's the best way, but I created a Timertask, a Service and and Activity to notify.
The Timertask checks every x seconds if the score changes and if it changes, informs the Service.
If the Service is informed, it calls the Activity that will notify the user. My problem is I failed at calling the activity to Notify from the Service.
Here is my code (For the example, I didn't take the score but a variable i.
//import ...
public class MyService extends Service{
Notif notif = new Notif();
private static final String TAG = "MyService";
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "Congrats! MyService Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}
#Override
public void onStart(Intent intent, int startId) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
Timer time = new Timer(); // Instantiate Timer Object
final ScheduleTask st = new ScheduleTask(); // Instantiate SheduledTask class
time.schedule(st, 0, 5000); // Create Repetitively task for every 1 secs
}
#Override
public void onDestroy() {
Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
public void checkI(int i){
if (i==3){
notif.initializeUIElements();
}
}
}
TimerTask
import ...
// Create a class extends with TimerTask
public class ScheduleTask extends TimerTask {
MyService myService = new MyService();
Notif notif = new Notif();
int i = 0;
// Add your task here
public void run() {
i++;
System.out.println("affichage numero " + i );
myService.checkI(i);
}
public int getI() {
return i;
}
}
Notif
import ...
public class Notif extends Activity {
private static final int NOTIFY_ME_ID = 1987;
private NotificationManager mgr = null;
ScheduleTask scheduleTask = new ScheduleTask();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
void initializeUIElements() {
Notification note = new Notification(R.drawable.ic_launcher,
"Welcome to MyDoople.com", System.currentTimeMillis());
PendingIntent i = PendingIntent.getActivity(this, 0, new Intent(
this, MainActivity.class), Notification.FLAG_ONGOING_EVENT);
note.setLatestEventInfo(this, "MyDoople.com", "An Android Portal for Development",
i);
// note.number = ++count;
note.flags |= Notification.FLAG_ONGOING_EVENT;
mgr.notify(NOTIFY_ME_ID, note);
}
}
Services may be terminated by the system if resources are needed. For your requirement, it's best to use AlarmManager to periodically do something.
Here are more references: [1], [2]