I'm developing a simple app for Android. I would like to change the image of my notifications on Samsung Galaxy Watch smartwatch. I tried to do it like this, unfortunately it doesn't work. In addition, the setBackround method is deprecated. Please help.
NotificationCompat.WearableExtender extender = new NotificationCompat.WearableExtender();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.logo);
extender.setBackground(bitmap);
notificationn = new NotificationCompat.Builder(getApplicationContext(),WateringChannel.ID_OF_CHANNEL_2)
.setSmallIcon(R.drawable.icon_drop_of_water)
.setContentTitle("Tura " + sharedPreferences.getInt(SharedPreferencesNames.WateringData.ACTUAL_ROUND,1))
.setContentText("PozostaĆy czas: " + ToolClass.generateCountDownTimerTime(millisUntilFinished/1000))
.setPriority(NotificationCompat.PRIORITY_LOW)
.setOngoing(true)
.setOnlyAlertOnce(true)
.extend(extender);
notificationManager = NotificationManagerCompat.from(getApplicationContext());
notificationManager.notify(2, notificationn.build());
Related
In my Android app, I want to play sounds on the phone internal speakers even when the user is connected to the device through a Bluetooth device or other external speakers. Can this be done?
I came up with way of playing audio on the phone speakers even when I have a connected Bluetooth audio device:
fun createPhoneSpeakerPreferredPlayer(context: Context, resource: Int): MediaPlayer{
val mediaPlayer = MediaPlayer.create(context, resource)
val audioDeviceType = if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) AudioDeviceInfo.TYPE_BUILTIN_SPEAKER_SAFE else AudioDeviceInfo.TYPE_BUILTIN_SPEAKER
val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
val devices = audioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS)
//create mapped devices variable to allow better logging. The devices collection is not being serialized well (or at all)
val mappedDevices = (devices.map {
#Suppress("unused")
object {
val id = it.id
val type = it.type
val productName = it.productName
}})
val jsonRepresentation = Gson().toJson(mappedDevices)
Log.d(Tag, "devices: $jsonRepresentation")
val playbackDevice = devices.firstOrNull { it.type == audioDeviceType }
Log.d(Tag, "selectedDevice: {id=${playbackDevice?.id}}, type=\"${playbackDevice?.type}\", productName=\"${playbackDevice?.productName}\"")
mediaPlayer.preferredDevice = playbackDevice
return mediaPlayer
}
to use that method and play audio:
val mediaPlayer = createPhoneSpeakerPreferredPlayer(this.context, R.raw.myAudioId)
mediaPlayer.looping = true
mediaPlayer.start()
This seems to work if I have a Bluetooth speaker connected, but once I start playing audio in the background, like watching Netflix, or listening to a podcast, the audio no longer plays on the phone speaker.
Here is a sample app I made with two buttons. One to play music through the phone speaker and one to play through whatever speaker is connected:
https://github.com/danwize/play-sound-android/blob/main/SoundPlayer/app/src/main/java/com/example/soundplayer/MainActivity.kt
I'm seeing that the first time I create a media player and play sound this way, the sound does play on the phone speakers. The second audio plays on the Bluetooth speaker. When I'm not playing any video or music, but still connected to a Bluetooth device, both my sounds play on the phone speakers. Here are the logs to show that I am correctly setting the preferred device:
2022-09-07 11:21:33.969 6101-6101/com.myApp D/MediaPlayerExtensions: devices: [{"id":2,"productName":"Pixel 3","type":1},{"id":3,"productName":"Pixel 3","type":2},{"id":11,"productName":"Pixel 3","type":18},{"id":369,"productName":"Jabra Elite 85h","type":8},{"id":363,"productName":"Jabra Elite 85h","type":7}]
2022-09-07 11:21:33.969 6101-6101/com.myApp D/MediaPlayerExtensions: selectedDevice: {id=3}, type="2", productName="Pixel 3"
2022-09-07 11:22:14.290 6101-6101/com.myApp D/MediaPlayerExtensions: devices: [{"id":2,"productName":"Pixel 3","type":1},{"id":3,"productName":"Pixel 3","type":2},{"id":11,"productName":"Pixel 3","type":18},{"id":369,"productName":"Jabra Elite 85h","type":8},{"id":363,"productName":"Jabra Elite 85h","type":7}]
2022-09-07 11:22:14.290 6101-6101/com.myApp D/MediaPlayerExtensions: selectedDevice: {id=3}, type="2", productName="Pixel 3"
I'm working on a Project that takes a date and time and automatically sends a pre-written message on that day to the specified Mobile number.
I'm using alarm Manager for this, but it's not working. I've been trying to debug my program for so long that I'm unable to see what's exactly wrong.
final Calendar c = Calendar.getInstance();
String date=releaseDateEditText.getText().toString();
String data[]= date.split("-");
c.set(Calendar.DAY_OF_MONTH, Integer.parseInt(data[0]));
c.set(Calendar.MONTH,Integer.parseInt(data[1]));
c.set(Calendar.YEAR,Integer.parseInt(data[2]));
c.set(Calendar.AM_PM, Calendar.PM);
c.set(Calendar.HOUR_OF_DAY, 11);
c.set(Calendar.MINUTE, 18);
c.set(Calendar.SECOND, 0);
Intent _myIntent = new Intent(getApplicationContext(), message.class);
_myIntent.putExtra("name", name.getText());
_myIntent.putExtra("agency", agency.getText());
_myIntent.putExtra("book", bookingDateEditText.getText());
_myIntent.putExtra("release", releaseDateEditText.getText());
pintent = PendingIntent.getBroadcast(getApplicationContext(), 1, _myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pintent);
Toast.makeText(getApplicationContext(), "Alarm set for " + releaseDateEditText.getText(), Toast.LENGTH_LONG).show();
public class message extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String SPhone = "Phonenumber";
String SSms = intent.getStringExtra("name");
SSms = SSms + "\n" + intent.getStringExtra("agency") + "\n" + intent.getStringExtra("book") + "\n" + intent.getStringExtra("release");
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(SPhone, null, SSms, null, null);
}
}
If you go through Use of SMS or Call Log permission groups, you will find that from DEC 2018 onwards, apps using permissions to SEND_SMS are not allowed on playstore, unless they are default SMS/Dialer app. Either you will have to file your app as exception or remove the SMS permissions.
For apps requesting access to the SMS or Call Log permissions, the intended and permitted uses include default SMS handling, default phone handling, or Assistant handling capability.
Apps must be actively registered as the default SMS, Phone, or Assistant handler before prompting users to accept any of the above permissions and must immediately stop the use of the permission when they no longer are the default handler.
ANSWER TO QUESTION:
Well, coming back to your question, many android device manufacturers are using aggressive policies to save battery. When a user clears his/her app from recent tabs, the app is force closed, thus cancelling all alarms,broadcastReceivers,services etc. This happens in most of the device manufacturers like OnePlus,Huwaei, Xiaomi, Vivo, Oppo etc.
They have AutoStartManagers/AutoLaunchManagers that prevent the background running of the apps. You will have to white list your app using steps mentioned in THIS SO ANSWER.
now my notification sounds are in server side
{
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data" : {
"Nick" : "Mario",
"body" : "great match!",
"Room" : "PortugalVSDenmark"
},
}
How to change it in app side (Locally java program for android or swift program for IOs)
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
put this code , when you want to play sound
On Android -
First, you need to add your sound file into your project under /main/res/raw/<file_name>.
You can now reference the file using a URI like - Uri notificationSoundUri = Uri.parse("android.resource://" + context.packageName + "/" + R.raw.<file_name>)
Next, you would have to handle an edge case for notification channels when you're working with Oreo and above. So this would look something like this -
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
channel.setSound(notificationSoundUri,AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_NOTIFICATION).build())
} else {
notificationBuilder.setSound(notificationSoundUri)
}
Finally - NotificationManagerCompat.from(context).notify(id, notificationBuilder.build()) should do the trick.
This is a cleaner approach since the user has a way to turn it off in notification settings.
On iOS -
You don't have to do anything fancy.
Add the sound file .caf/.aiff into your project and make sure it's under -> Build Phases -> Copy Bundle Resources, if not add it.
The notification payload should have a sound param with the same name as you .caf/.aiff file. Which would look something like this -
{
"aps" : {
"alert" : "You got your emails.",
"badge" : 9,
"sound" : "bingbong.aiff"
},
"acme1" : "bar",
"acme2" : 42
}
More details here -https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CreatingtheNotificationPayload.html
Cheers & Happy coding!
So we all know that the getRecentTasks() and getRunningTasks() on ActivityManager are now deprecated and will return a reduced result set on Android L and higher devices.
Alternative to getRunningTasks in Android L
https://code.google.com/p/android-developer-preview/issues/detail?id=29
However, I am trying to find a solution to keep my App Locker app alive on Android L. I need the package name of the top Activity in order to show the lock screen when the users opens/launches the locked app.
It is very similar to this app: https://play.google.com/store/apps/details?id=com.domobile.applock&hl=en
Currently I am using this code:
ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> RunningTask = mActivityManager
.getRunningTasks(1);
ActivityManager.RunningTaskInfo ar = RunningTask.get(0);
String activityOnTop = ar.topActivity.getPackageName();
But it won't work in Android L, so I am not sure what exactly to do...
How can I implement something like this in Android L?
Unfortunately, there is no equivalent in Android 5.0: it is not possible to get the top most activity, nor is it possible get any callback when a new application/activity is launched in realtime.
please refer this link.
i hope it will helpful to you, in my project it work. thanks.
Try this line of code for Android L
ActivityManager activityManager = (ActivityManager) getSystemService (Context.ACTIVITY_SERVICE);
String packageName = activityManager.getRunningAppProcesses().get(0).processName;
and please note that this works only for Lollipop devices .. If you want any platform support then add the following code.
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP)
{
String packageName = activityManager.getRunningAppProcesses().get(0).processName;
}
else if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP)
{
String packageName = ProcessManager.getRunningForegroundApps(getApplicationContext()).get(0).getPackageName();
}
else
{
String packageName = activityManager.getRunningTasks(1).get(0).topActivity.getPackageName();
}
I am writing an Android application to read input from a HID USB foot pedal (press the pedal, get a message, do something).
The UsbManager is not recognizing the device. The foot pedal may be throwing an error in Android kernel when it plugs in, because I see this error message in the logcat:
"EventHub could not get driver version for /dev/input/mouse0, not a typewriter"
However, I know the foot pedal works, because when I plug it in and press it, it changes the focus to the next button on the activity... So I know it is communicating with my Nexus tablet and apparently its default action is to move the focus to the next button/object. I don't think there are any problems with my code, since it will recognize other USB devices, just not this foot pedal. I can actually tell when it's pressed by checking for when the focus changes, but that won't work for what I want since this app will run in the background as a service. I've tried setting an intent filter for this specific USB device (I know its product id and vendor id). However, it still shows no connected devices and the pop-up message that is supposed to ask the user to confirm launching the application never shows up. I've tried just listing all the connected USB devices as well, but I always get an empty list.
Is there any way to intercept input from this device so I can tell when the foot pedal gets pressed, even though Android's USB Manager will not recognize it?
For completeness, here is my code. I am testing on a Galaxy Nexus 10 tablet:
public int list_usb_devices()
{
int device_count = 0;
UsbManager mUsbManager;
mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
String LOG_TAG = "USB";
for (UsbDevice device : mUsbManager.getDeviceList().values()) {
//This code is never reached...
Log.d(LOG_TAG, "Detected device: " + device.toString());
Log.d(LOG_TAG, "Model: " + device.getDeviceName());
Log.d(LOG_TAG, "Id: " + device.getDeviceId());
Log.d(LOG_TAG, "Class: " + device.getDeviceClass());
Log.d(LOG_TAG, "Protocol: " + device.getDeviceProtocol());
Log.d(LOG_TAG, "VendorId: " + device.getVendorId());
Log.d(LOG_TAG, "ProductId: " + device.getProductId());
CharSequence text = device.toString();
show_toast(text);
device_count++;
}
return device_count;
}
I did some research in the Android source and it seems that all HID boot devices (mouse, keyboard etc.) are blacklisted and can therefore not be accessed using the USBManager API.
Here is the relevant part from the UsbHostManager.java , see here: http://grepcode.com/file_/repository.grepcode.com/java/ext/com.google.android/android/4.4.2_r1/com/android/server/usb/UsbHostManager.java/?v=source
/* returns true if the USB device should not be accessible by applications */
private boolean isBlackListed(int clazz, int subClass, int protocol) {
// blacklist hubs
if (clazz == UsbConstants.USB_CLASS_HUB) return true;
// blacklist HID boot devices (mouse and keyboard)
if (clazz == UsbConstants.USB_CLASS_HID &&
subClass == UsbConstants.USB_INTERFACE_SUBCLASS_BOOT) {
return true;
}
return false;
}