Continue vibration even after the screen goes to sleep mode in Android - java

In my application, I am starting the VIBRATOR_SERVICE through the following code
long[] pattern = {50,100,1000}
Vibrator vibe=(Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vibe.vibrate(pattern, 0);
I want the vibration continue till I call
vibe.cancel();
The Code is working fine, but the vibration getting off when the screen goes to sleep mode.
I want the vibration continue even after the screen goes to sleep mode. Is there any ways to do this? Please help me.
Thanks in advance. :)

The correct answer to the question is as follows
Before doing this, don't forget to add the permission "android.permission.VIBRATE" to your app manifest file.
public BroadcastReceiver vibrateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
vibe.vibrate(pattern, 0);
}
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
registerReceiver(vibrateReceiver, filter);
wakelock will not work here, because the receiver will receive the intent only after the screen goes off. Though we can acquire the wakelock after the screen goes to off mode the vibration stops, because it happens with the ACTION_SCREEN_OFF. So it can be done by starting the vibration again after receiving the broadcast.

Try this it might help you. First make broadcast receiver for this such that when mobile light screen off then write logic of vibrate mobile.
public BroadcastReceiver wakeLockReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent)
{
if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
//WRITE LOGIC OF VIBRATION.
}
}
};
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
registerReceiver(wakeLockReceiver, filter);
Add permission in AndroidManifest.xml
<uses-permission android:name="android.permission.VIBRATE"/>

Related

How to open activity (incoming voip call) in Android 10

In Android 10 there apply new restrictions for apps.
We can no longer start an activity from background. While this may be fine for the majority of apps, it's a killing blow for voip-apps that need to show an incoming call after a push notification arrived.
According to this https://developer.android.com/guide/components/activities/background-starts there is a list of conditions that can be met to still allow opening an activity, but tbh I do not understand that fully (non-english-native here).
What I definitely know, is:
I do not have any running activity, task, backstack and the like
The app is NOT EVEN RUNNING
What I need to achieve:
The FCM service of the app receives a push from our server and shall present the incoming call screen (over lock screen and all - just as it did with android 9 and below)
What can I do to open an activity for an incoming voip call in android 10?
Over the lockscreen and all, just as a normal user would expect from a PHONE app.
Thanks in advance for any hints.
To open Activity over lock screen. you can use a high-notification with "full-screen intent" as CommonsWare's answer. But for more detail, you can try my solution as below code:
Create a foreground service then call buildNotification in onStartCommand method, the buildNotification method will return a notification which put into startForeground method parameter.
public class IncomingCallService extends Service {
public int onStartCommand(Intent intent, int flags, int startId) {
Notification notification = buildNotification();
startForeground(1, notification);
return START_NOT_STICKY;
}
}
In buildNotification method, we will create notification with high priority, call category and a full screen intent.
private Notification buildNotification() {
Intent fullScreenIntent = new Intent(this, IncomingCallActivity.class);
PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(this, 0, fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_notification_icon)
.setContentTitle("Incoming call")
.setContentText("(919) 555-1234")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_CALL)
// Use a full-screen intent only for the highest-priority alerts where you
// have an associated activity that you would like to launch after the user
// interacts with the notification. Also, if your app targets Android 10
// or higher, you need to request the USE_FULL_SCREEN_INTENT permission in
// order for the platform to invoke this notification.
.setFullScreenIntent(fullScreenPendingIntent, true);
notificationBuilder.setAutoCancel(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationManager.createNotificationChannel(new NotificationChannel("123", "123", NotificationManager.IMPORTANCE_HIGH));
notificationBuilder.setChannelId("123");
}
Notification incomingCallNotification = notificationBuilder.build();
return incomingCallNotification;
}
In onStartCommand, add a line of code to send ACTION_CLOSE_SYSTEM_DIALOGS broadcast action. This verify IMPORTANT to kick off full screen pending intent.
public int onStartCommand(Intent intent, int flags, int startId) {
Notification notification = buildNotification();
startForeground(1, notification);
sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
return START_NOT_STICKY;
}
Create full screen activity which you want to display over lock screen then you need to add setShowWhenLocked and setTurnScreenOn for display over lock screen. If not, your activity will be displayed behind lock screen. Below is my sample.
public class IncomingCallActivity extends AppCompatActivity {
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_explore);
setShowWhenLocked(true);
setTurnScreenOn(true);
getWindow().addFlags(
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
| WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
}
}
Now you must start IncomingCallService when you receive a call from your logic.
public void startCallService() {
Intent intent = new Intent(context, IncomingCallService.class);
startForegroundService(intent);
}
You must declare activity, service and some permission in your manifest as below:
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<application
...>
<activity android:name=".IncomingCallActivity" />
<service
android:name=".IncomingCallService"
android:enabled="true"
android:exported="true" />
</application>
I tested on google, samsung, vsmart phone. It work well. But for xaomi device. you need to enable some permission by flow below steps:
Long click to you app icon
Open app info
Click to "Other permission" item
Allow show on Lock screen
Now your app will work on xaomi device. If you face any problems with my solution, please leave a comment here. I will help you If I could.
Use a high-priority notification with a "full-screen intent". That will:
Invoke your "full-screen intent" if the device is locked
Otherwise, display a "heads-up" notification
Please go through my blog on how to open activity for OS 10 and also how to display heads up notification and handle clicks on the action buttons.
https://medium.com/#dcostalloyd90/show-incoming-voip-call-notification-and-open-activity-for-android-os-10-5aada2d4c1e4
Check this link this will help you
here
or
You need to ask for a permission "draw over other app" then you can make this as previous versions
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
if (!Settings.canDrawOverlays(this)) {
RequestPermission();
}
}
private void RequestPermission() {
// Check if Android P or higher
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Show alert dialog to the user saying a separate permission is needed
// Launch the settings activity if the user prefers
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + BuildConfig.APPLICATION_ID));
startActivityForResult(intent,
ACTION_MANAGE_OVERLAY_PERMISSION_REQUEST_CODE);
}
}
or You can use my this answer
https://stackoverflow.com/a/63699960/7108113

Android Nougat Media Player how put music Animation in Lock Screen?

I am using the original Music player in android Nougat, while the music is playing in the Lock Screen Appear an animation in the Buttom like this screenshot.
But when i using my own App Media Player in the same Android Nougat and Same device in the Lock Screen dont appear that animation.
The question is: How can i Add that animation in my Media Player App? it´s not a gif image because The animation moves to the rhythm of the music.
**This is my Notification Method ** if i am missing something or if i have to add something else.
ublic void Custom_Notificacion(){
Notification notification = new Notification(R.drawable.logobubble, null, System.currentTimeMillis());
notificationView = new RemoteViews(getPackageName(), R.layout.layout_notificacion_personalizada);
notificationView.setImageViewBitmap(R.id.id_FotoAlbumNotif,FotoNotif);
notificationView.setTextViewText(R.id.id_NombreMp3Notif,NommbreArtista);
notificationView.setTextViewText(R.id.id_NombreCancionNotif,NombreCancion);
notification.contentView = notificationView;
notification.flags |= Notification.FLAG_NO_CLEAR;
startForeground(constantes.NOTIFICATION_ID.FOREGROUND_SERVICE,notification);
}
I've read an article about this,an feasible solution is custom a lock screen page and display the Animation view within it,to achieve this you need a Service listening to the LOCK_SCREEN Broadcast,and start your LockScreenActivity ;replace the system lock screen at the same time.
here is some code segment might be helpful:
Register Broadcast Receiver
IntentFilter mScreenOffFilter = new IntentFilter();
mScreenOffFilter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(mScreenOffReceiver, mScreenOffFilter);
  // on receive method
private BroadcastReceiver mScreenOffReceiver = new BroadcastReceiver() {
#SuppressWarnings("deprecation")
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(NOTIFY_SCREEN_OFF)) {
Intent mLockIntent = new Intent(context, LockScreenActivity.class);
mLockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(mLockIntent);
}
}
Disable the Lock screen
KeyguardManager mKeyguardManager = (KeyguardManager)getSystemService(Context.KEYGUARD_SERVICE);
KeyguardManager.KeyguardLock mKeyguardLock = mKeyguardManager.newKeyguardLock("CustomLockScreen");
mKeyguardLock.disableKeyguard();
Hope this could be a little help

battery receiver fully charged doesnt work

I found that in the manifest can not be registered (intent-filter battery low, battery changed).
I need to get the notification when the battery is fully charged. when I have a running app so it is working, but when I close the application so it does not work.
I need the receiver to run in the background when the application is closed.
Main.class
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
mContext.registerReceiver(this.batteryInfoReceiver,filter);
private BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent)
{
...
}

Android - Location Manager requestLocationUpdates bottleneck

I have an Android background service that report positions from time to time. When I test locally over wifi it works pretty well, however when testing in 3G connection for example (sometimes on Edge) I have perceived that the application apparently enters in a bottleneck and do not execute the onLocationChanged method. That's okay because maybe lost signal or so on. However after a while (maybe when connection is re-established) it start updating all requests at once, in a matter of a few seconds many many times the method onLocationChanged is executed.
Does anyone have ideas how to solve that? Is it possible to add timeout into the method locationManager.requestLocationUpdates?
My Listener
public class MyListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
//report location to server
HttlCallToUpdatePostion(loc.Latitude, loc.Longitude, loc.Accuracy);
}
}
My Service
Handler handler = null;
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
MyListener listener = new MyListener();
protected void doWork() {
Looper.prepare();
handler = new Handler();
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, listener);
Looper.loop();
}
I wrote an app, exactly what you need.
When it was a service only I met the same problem. While the UI went to background and screen off the service went to background and it scheduled the system calls, once when triggered the buffer was flushed and I had like 10-50 updates.
The solution it is: an Alarm must be set and scheduled with 5000 value and a BroadcastRreceiver will receive and it will handle properly. Than you will meet other problems, which is not asked here.
For me this was a SOLUTION and the app is in use!
Edit:
Alarm setup code part:
Intent intent = new Intent(getApplicationContext(), AlarmReceiver.class);
// In reality, you would want to have a static variable for the request
// code instead of 192837
PendingIntent sender = PendingIntent.getBroadcast(this, 192837, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Get the AlarmManager service
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
// am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
am.setRepeating(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis(), timerInterval, sender);
AndroidManifest.xml :
<receiver android:process=":remote" android:name=".broadcastreceiver.AlarmReceiver"/>
class implementation part:
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Context appContext = context.getApplicationContext();
...
check for power saving mode in adorid system setting: it must be disable to permit location manager to generete update location when the screen is off

Why don't I get proximity alterts even though I've registered alerts?

I'm trying to simply set a proximity later for an area an for testing, I simply added this to the onCreate method of my main activity.
public void onCreate(Bundle bndBundle) {
IntentFilter filter = new IntentFilter(WidgetService.ACTION_STOP_PROXIMITY);
registerReceiver(new ProximityIntentReceiver(), filter);
LocationManager locManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
Intent ittIntent = new Intent(this, ProximityIntentReceiver.class);
ittIntent.putExtra(WidgetService.KEY_STOP_IDENTIFIER, 1000);
PendingIntent pitIntent = PendingIntent.getBroadcast(this, 0, ittIntent, 0);
locManager.addProximityAlert(60.15769, 24.94150, 150, -1, pitIntent);
super.onCreate(bndBundle);
getActionBar().setDisplayHomeAsUpEnabled(false);
}
..and here's the simple receiver class that I'm using
public class ProximityIntentReceiver extends BroadcastReceiver {
private static final int NOTIFICATION_ID = 1000;
#Override
public void onReceive(Context context, Intent intent) {
String key = LocationManager.KEY_PROXIMITY_ENTERING;
Boolean entering = intent.getBooleanExtra(key, false);
if (entering) {
Log.d(getClass().getSimpleName(), "entering");
}
else {
Log.d(getClass().getSimpleName(), "exiting");
}
}
}
I'm testing this on my emulator and when I use the DDMS console to set the co-ordinates of the phone manually, I still don't see the log message.
My manifest file doesn't have any special code. I've added the correct permissions and have the code for a simple activity- no services or anything.
I read through a whole bunch of posts on StacKOverflow but I haven't been able to resolve the issue. Am I missing something in my snippet?
You are registering this receiver dynamically, through registerReceiver(), to have it respond to broadcasts whose action string is WidgetService.ACTION_STOP_PROXIMITY.
However, the actual broadcast you are sending is trying to use an explicit Intent, identifying your receiver class. This does not line up with the IntentFilter that you are using with registerReceiver().
Either:
Register your receiver in the manifest and get rid of registerReceiver(), in which case your explicit Intent will work, or
Use new Intent(WidgetService.ACTION_STOP_PROXIMITY) instead of new Intent(this, ProximityIntentReceiver.class), so your Intent lines up with your IntentFilter
You cannot use explicit Intent objects to send broadcasts to receivers registered via registerReceiver(). An explicit Intent will only work with a manifest-registered receiver.
make sure you type in the right coordinates. in DDMS they're reversed, longitude first, then latitude

Categories

Resources