That's what I trying to do in the background, but nothing happens. I'm using push notifications(Firebase Messaging Service) to run this code.
phoneAccountHandle = PhoneAccountHandle(
ComponentName(
packageName,
DoctorConnectionService::class.java.name
), phoneAccountHandleId
)
val builder = PhoneAccount.builder(phoneAccountHandle, "My account")
builder.setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER or PhoneAccount.CAPABILITY_CONNECTION_MANAGER)
val phoneAccount = builder.build()
val test = telecomManager
telecomManager?.registerPhoneAccount(phoneAccount)
telecomManager?.addNewIncomingCall(phoneAccountHandle, Bundle())
You can try BroadcastReceiver. Here is my BroadcastReceiver's Class & MainActivity. In here I just Toast a message (Incoming Call) when application is in background:
MainActivity:
public class MainActivity extends AppCompatActivity {
BroadcastReceiver callReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
checkPermission();
callReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
/*Do Whatever You Want When You Reciveing a Call And App is Open*/
}
};
IntentFilter callFilter = new IntentFilter("android.intent.action.PHONE_STATE");
registerReceiver(callReceiver, callFilter);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(callReceiver);
}
private void checkPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 100);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 100) {
}
}
}
And here is my BroadcastReceiver class:
public class IncomingCallReciver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, ".:Incoming Call:.", Toast.LENGTH_SHORT).show();
/*Do Whatever You Want When You Reciveing a Call And App is In Background*/
}
}
Then Add READ_PHONE_STATE Permission in Manifest and add BroadcastReceiver's class in Manifest, Inside Application Tag:
<receiver android:name=".IncomingCallReciver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
Related
I have an Android Xamarin framework app and I need to lock the device when the focus of an activity is lost. I have DevicePolicyManager object and a DeviceAdmin component in my class. I need to request for device admin permisions so that I override onwindowfocuschange to use the DevicePolicyManager object to lock the device. How can I request for the Device Admin user interface to show up in my oncreate method. I have extended the DeviceAdminReceiver class and registered all the meta data and receivers in the class below
[BroadcastReceiver(Permission = "android.permission.BIND_DEVICE_ADMIN",Name="LockScreenAPI.AdminReceiver")]
[MetaData("android.app.device_admin", Resource = "#xml/device_admin_sample")]
[IntentFilter(new[] { "android.app.action.DEVICE_ADMIN_ENABLED", Intent.ActionMain})]
public class AdminReceiver : DeviceAdminReceiver
{
public override void OnEnabled(Context context, Intent intent)
{
base.OnEnabled(context, intent);
Toast.MakeText(context, "Device Admin Enabled", ToastLength.Short).Show();
}
public override void OnLockTaskModeEntering(Context context, Intent intent, string pkg)
{
Toast.MakeText(context,"'Device entering locked mode",ToastLength.Long).Show();
}
public override void OnLockTaskModeExiting(Context context, Intent intent)
{
}
public override void OnDisabled(Context context, Intent intent)
{
Toast.MakeText(context,"Admin mode disabled",ToastLength.Long).Show();
}
}
and then the declared the DevicePolicyManager and deviceAdmin components in the main activity like below
[Activity(Label = "#string/app_name", Theme = "#style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity,Preference.IOnPreferenceChangeListener
{
private LockReceiver _lockReceiver;
//declare a devicepolicymanager object
private DevicePolicyManager _devicePolicyManager;
//declare a component name
private ComponentName _deviceAdmin;
private Preference preference;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
//request device admin permissions from the user
permissions();
_devicePolicyManager = (DevicePolicyManager)GetSystemService(Context.DevicePolicyService);
_deviceAdmin = new ComponentName(this, Java.Lang.Class.FromType(typeof(AdminReceiver)));
//check if admin mode is enabled
if (_devicePolicyManager.IsAdminActive(_deviceAdmin))
{
Toast.MakeText(this,"Device admin is enabled",ToastLength.Long).Show();
}
else
{
//show the device permissions
try
{
Intent devicePolicy = new Intent(DevicePolicyManager.ActionAddDeviceAdmin);
devicePolicy.PutExtra(DevicePolicyManager.ExtraDeviceAdmin,savedInstanceState);
devicePolicy.PutExtra(DevicePolicyManager.ExtraAddExplanation,
"Enable device administration for this app");
StartActivityForResult(devicePolicy,909);
}
catch (Exception p)
{
Toast.MakeText(this,p.Message,ToastLength.Long).Show();
}
if (_devicePolicyManager.IsAdminActive(_deviceAdmin) == true)
{
try
{
_devicePolicyManager.LockNow();
}
catch (Exception m)
{
Toast.MakeText(this, m.Message,ToastLength.Long).Show();
}
}
IntentFilter filter = new IntentFilter(Intent.ActionScreenOn);
//register the receiver
RegisterReceiver(_lockReceiver, filter);
}
I don't known whether I understand your request clearly. But you can try to check this link which is about native android.
Official document: https://developer.android.com/guide/topics/admin/device-admin#enabling
Similar case in native:Android Device Administrator permission activity not launching
With the code in xamarin.android:
Intent intent = new Intent(DevicePolicyManager.ActionAddDeviceAdmin);
intent.PutExtra(DevicePolicyManager.ExtraDeviceAdmin, _deviceAdmin);
intent.PutExtra(DevicePolicyManager.ExtraAddExplanation, "some description");
StartActivityForResult(intent, ACTIVATION_REQUEST);//ACTIVATION_REQUEST is a custom int value
Update:
The code about receiver:
[BroadcastReceiver(Permission = "android.permission.BIND_DEVICE_ADMIN")]
[MetaData("android.app.device_admin", Resource = "#xml/device_admin_sample")]
[IntentFilter(new[] { "android.app.action.DEVICE_ADMIN_ENABLED", Intent.ActionMain })]
public class AdminReceiver : DeviceAdminReceiver
{
public override void OnEnabled(Context context, Intent intent)
{
base.OnEnabled(context, intent);
Toast.MakeText(context, "Device Admin Enabled", ToastLength.Short).Show();
}
public override void OnLockTaskModeEntering(Context context, Intent intent, string pkg)
{
Toast.MakeText(context, "'Device entering locked mode", ToastLength.Long).Show();
}
public override void OnLockTaskModeExiting(Context context, Intent intent)
{
}
public override void OnDisabled(Context context, Intent intent)
{
Toast.MakeText(context, "Admin mode disabled", ToastLength.Long).Show();
}
}
The code about xml:
<device-admin xmlns:android="http://schemas.android.com/apk/res/android" >
<uses-policies>
<limit-password />
<watch-login />
<reset-password />
<force-lock />
<wipe-data />
<expire-password />
<encrypted-storage />
<disable-camera />
</uses-policies>
</device-admin>
The code in my OnCreate method:
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
ComponentName _deviceAdmin = new ComponentName(this, Java.Lang.Class.FromType(typeof(AdminReceiver)));
Intent intent = new Intent(DevicePolicyManager.ActionAddDeviceAdmin);
intent.PutExtra(DevicePolicyManager.ExtraDeviceAdmin, _deviceAdmin);
intent.PutExtra(DevicePolicyManager.ExtraAddExplanation, "some description");
StartActivityForResult(intent, 47);//ACTIVATION_REQUEST is a custom int value
}
The permission in the AndroidManifest.xml:
<uses-permission android:name="android.permission.BIND_DEVICE_ADMIN" />
Am trying to implement a Broadcast receiver class in my project, I have a receiver that extends class BroadcastReceiver and I intend to check if the Broadcast was received via a button click, The OnReceive method has a Toast code inside that should display the nessage Intent Detected if the broadcast was succesfully sent. My code looks like this...
class FlashActivity : AppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
//Button definition
Button button1 = this.FindViewById<Button>(Resource.Id.button1);
//Clicking on this button should send the Broadcast message
button1.Click += broadCastIntent;
}
//Method to send broadcast message on button click
private void broadCastIntent(object sender,EventArgs e)
{
Intent intent = new Intent();
intent.SetAction("com.Java_Tutorial.CUSTOM_INTENT");
SendBroadcast(intent);
}
//BroadCast Receiver class Implementation
[BroadcastReceiver(Name="com.Java_Tutorial.CUSTOM_INTENT")]
public class MyReceiver: BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
//Acknowledge message was received via a Toast
Toast.MakeText(context, "Intent Detected.", ToastLength.Long).Show();
}
}
}
The Receiver code section of my Manifest.xml file looks like this
<application android:allowBackup="true" android:icon="#mipmap/ic_launcher" android:label="#string/app_name" android:roundIcon="#mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="#style/AppTheme">
<receiver android:name="MyReceiver">
<intent-filter>
<action android:name="com.Java_Tutorial.CUSTOM_INTENT"></action>
</intent-filter>
</receiver>
</application>
When i click the button, No Toast is displayed please help...
When i click the button, No Toast is displayed
You do not register your BroadcastReceiver in your Activity.
Please register it like following code.
[Activity(Label = "#string/app_name", Theme = "#style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
MyReceiver receiver;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
Button button1 = this.FindViewById<Button>(Resource.Id.button1);
receiver = new MyReceiver();
//Clicking on this button should send the Broadcast message
button1.Click += broadCastIntent; ;
}
private void broadCastIntent(object sender, System.EventArgs e)
{
Intent intent = new Intent();
intent.SetAction("com.Java_Tutorial.CUSTOM_INTENT");
SendBroadcast(intent);
}
//BroadCast Receiver class Implementation
protected override void OnResume()
{
base.OnResume();
RegisterReceiver(receiver, new IntentFilter("com.Java_Tutorial.CUSTOM_INTENT"));
// Code omitted for clarity
}
protected override void OnPause()
{
UnregisterReceiver(receiver);
// Code omitted for clarity
base.OnPause();
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
[BroadcastReceiver(Name = "com.Java_Tutorial.CUSTOM_INTENT")]
public class MyReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
//Acknowledge message was received via a Toast
Toast.MakeText(context, "Intent Detected.", ToastLength.Long).Show();
}
}
}
Here is running GIF.
Here is a helpful article about broadcast. You cna refer to it.
https://learn.microsoft.com/en-us/xamarin/android/app-fundamentals/broadcast-receivers#context-registering-a-broadcast-receiver
Update
tried to find a post where you detect if flashlight is already on via a broadcast and then toggle switch accordingly in my app
Android OS do not provide system broadcast for flashlight. But we can check the flashlight's status.If the flashlight's status is open, we can send an broadcast, then our broadcastReceiver to get it.
// note: camera come from: private Android.Hardware.Camera camera=Android.Hardware.Camera.Open();
if (camera.GetParameters().FlashMode.Equals(Android.Hardware.Camera.Parameters.FlashModeOff))
{
switchOn = false;
}
else if (camera.GetParameters().FlashMode.Equals(Android.Hardware.Camera.Parameters.FlashModeTorch))
{
switchOn = true;
Intent intent = new Intent();
intent.SetAction("com.Java_Tutorial.CUSTOM_INTENT");
SendBroadcast(intent);
}
You need to add an IntentFilter attribute
[BroadcastReceiver(Enabled = true)]
[IntentFilter(new[] { "com.Java_Tutorial.CUSTOM_INTENT" })]
public class MyReceiver: BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
//Acknowledge message was received via a Toast
Toast.MakeText(context, "Intent Detected.", ToastLength.Long).Show();
}
}
I am using following code to register the service in Manifest.
<service android:name=".CallScreenService"
android:permission="android.permission.BIND_SCREENING_SERVICE">
<intent-filter>
<action android:name="android.telecom.CallScreeningService"/>
</intent-filter>
</service>
This is my service class that is extending the CallScreeningService.
#RequiresApi(api = Build.VERSION_CODES.N)
public class CallScreenService extends CallScreeningService {
#Override
public void onScreenCall(Call.Details callDetails) {
CallResponse.Builder response = new CallResponse.Builder();
Toast.makeText(this, callDetails.getHandle().toString(), Toast.LENGTH_LONG).show();
}
}
You have to register you app for call screening role first:
https://developer.android.com/reference/android/telecom/CallScreeningService#onScreenCall(android.telecom.Call.Details)
private static final int REQUEST_ID = 1;
public void requestRole() {
RoleManager roleManager = (RoleManager) getSystemService(ROLE_SERVICE);
Intent intent = roleManager.createRequestRoleIntent(RoleManager.ROLE_CALL_SCREENING);
startActivityForResult(intent, REQUEST_ID);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_ID) {
if (resultCode == android.app.Activity.RESULT_OK) {
// Your app is now the call screening app
} else {
// Your app is not the call screening app
}
}
}
If you have implemented onStartCommand remove it. Remove onBind and onUnbind as well.
I need to set alarm icon in status bar, without a notification. It works when application is running, but after finishing an application, the receiver does not respond on "ALARM_CHANGED", only on "BOOT_COMPLETED".
Need to set alarm icon after user turns off alarms in build-in Alarm Clock.
Thanks.
manifest:
<receiver android:name=".Alarm.AlarmInitReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.ALARM_CHANGED" />
</intent-filter>
</receiver>
AlarmInitReceiver.java:
public class AlarmInitReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() != null) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
Toast.makeText(context, "BOOT-completed", Toast.LENGTH_LONG).show();
}
if (intent.getAction().equals("android.intent.action.ALARM_CHANGED")) {
Toast.makeText(context, "Alarm on", Toast.LENGTH_SHORT).show();
setStatusBarIcon(true);
}
}
}
}
MainActivity:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setStatusBarIcon(true);
enableReceiver(true);
}
protected void enableReceiver(boolean enable) {
ComponentName receiver = new ComponentName(mContext, AlarmInitReceiver.class);
PackageManager pm = mContext.getPackageManager();
pm.setComponentEnabledSetting(receiver,
(enable) ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
public static void setStatusBarIcon(boolean enabled)
{
Intent alarmChanged = new Intent("android.intent.action.ALARM_CHANGED");
alarmChanged.putExtra("alarmSet", enabled);
mContext.sendBroadcast(alarmChanged);
}
}
The solution is:
public class AlarmInitReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() != null) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
Toast.makeText(context, "BOOT-completed", Toast.LENGTH_LONG).show();
}
if (intent.getAction().equals("android.intent.action.ALARM_CHANGED")) {
if (intent.getExtras().getBoolean("alarmSet") == false) {
Intent alarmChanged = new Intent("android.intent.action.ALARM_CHANGED");
alarmChanged.putExtra("alarmSet", true);
context.sendBroadcast(alarmChanged);
}
}
}
}
I am using ACTION_USER_PRESENT Broadcast Receiver in my application,
My Problem is that : I am getting the BroadCastReceiver only when my application is in Pause state.
Here is my manifest:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<receiver
android:name=".utils.receivers.ReminderBroadcastReceiver"
android:enabled="true"
android:exported="true" />
<receiver android:name=".utils.receivers.UserPresentBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>
My Receiver:
public class UserPresentBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
/*Sent when the user is present after
* device wakes up (e.g when the keyguard is gone)
* */
// MY STUFF - which works when my app is on paused state, but not when it is closed
}
}
am running on Marshmallo 6.0
Any help?
Getting runtime permision ofr Marshmallo 6.0 or greator.
public class RuntimePermission extends AppCompatActivity {
private static final int REQUEST_RUNTIME_PERMISSION = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (CheckPermission(RuntimePermission.this, Manifest.permission.READ_PHONE_STATE)) {
// you have permission go ahead
} else {
// you do not have permission go request runtime permissions
RequestPermission(RuntimePermission.this, Manifest.permission.READ_PHONE_STATE, REQUEST_RUNTIME_PERMISSION);
}
}
#Override
public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults) {
switch (permsRequestCode) {
case REQUEST_RUNTIME_PERMISSION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// you have permission go ahead
} else {
// you do not have permission show toast.
}
return;
}
}
}
public void RequestPermission(Activity thisActivity, String Permission, int Code) {
if (ContextCompat.checkSelfPermission(thisActivity,
Permission)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Permission)) {
} else {
ActivityCompat.requestPermissions(thisActivity,
new String[]{Permission},
Code);
}
}
}
public boolean CheckPermission(Context context, String Permission) {
if (ContextCompat.checkSelfPermission(context,
Permission) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
}