toast when phone is plugged for charging using BroadCast Receiver but not working - broadcastreceiver

I had done an simple app which display some text when the phone is plugged for charging. But its not working on my HTC One X. The below is the code, can any one help?
public class ChargingBroadcastReceiverActivity extends BroadcastReceiver {
#Override
public void onReceive(Context c, Intent i) {
String POWER_CONNECTED = "android.intent.action.ACTION_POWER_CONNECTED";
if (i.getAction().equals(POWER_CONNECTED))
{
Toast.makeText(c, "Thanks For the Power", Toast.LENGTH_LONG).show();
}
}
}

did you set the required uses-permission in android manifest?
and try to use yorclassname.this for the context!

Related

How to create a background service in .NET Maui

I'm new to mobile app development and am learning .NET Maui. The app I'm creating needs to listen for Accelerometer events, and send a notification to a web service if the events meet certain criteria. The bit I'm struggling with is how to have the app run in the background, i.e. with no UI visible, without going to sleep, as I'd want the user to close the UI completely. So I'm thinking the app needs to run as some kind of service, with the option to show a UI when needed - how can this be done?
i know it's beign a while but will post an answer for future users!
First we need to understand that background services depends on which platform we use.(thanks Jason) And i will focus on ANDROID, based on Xamarin Documentation (thanks Eli), adapted to Maui.
Since we are working with ANDROID, on MauiProgram we will add the following:
/// Add dependecy injection to main page
builder.Services.AddSingleton<MainPage>();
#if ANDROID
builder.Services.AddTransient<IServiceTest, DemoServices>();
#endif
And we create our Interface for DI which provides us the methods to start and stop the foreground service
public interface IServiceTest
{
void Start();
void Stop();
}
Then, before platform code we need to add Android Permissions on AndroidManifest.xml:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
Android Main Activity
public class MainActivity : MauiAppCompatActivity
{
//set an activity on main application to get the reference on the service
public static MainActivity ActivityCurrent { get; set; }
public MainActivity()
{
ActivityCurrent = this;
}
}
And Finally we create our Android foreground service. Check Comments Below. Also on xamarin docs, they show the different properties for notification Builder.
[Service]
public class DemoServices : Service, IServiceTest //we implement our service (IServiceTest) and use Android Native Service Class
{
public override IBinder OnBind(Intent intent)
{
throw new NotImplementedException();
}
[return: GeneratedEnum]//we catch the actions intents to know the state of the foreground service
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
if (intent.Action == "START_SERVICE")
{
RegisterNotification();//Proceed to notify
}
else if (intent.Action == "STOP_SERVICE")
{
StopForeground(true);//Stop the service
StopSelfResult(startId);
}
return StartCommandResult.NotSticky;
}
//Start and Stop Intents, set the actions for the MainActivity to get the state of the foreground service
//Setting one action to start and one action to stop the foreground service
public void Start()
{
Intent startService = new Intent(MainActivity.ActivityCurrent, typeof(DemoServices));
startService.SetAction("START_SERVICE");
MainActivity.ActivityCurrent.StartService(startService);
}
public void Stop()
{
Intent stopIntent = new Intent(MainActivity.ActivityCurrent, this.Class);
stopIntent.SetAction("STOP_SERVICE");
MainActivity.ActivityCurrent.StartService(stopIntent);
}
private void RegisterNotification()
{
NotificationChannel channel = new NotificationChannel("ServiceChannel", "ServiceDemo", NotificationImportance.Max);
NotificationManager manager = (NotificationManager)MainActivity.ActivityCurrent.GetSystemService(Context.NotificationService);
manager.CreateNotificationChannel(channel);
Notification notification = new Notification.Builder(this, "ServiceChannel")
.SetContentTitle("Service Working")
.SetSmallIcon(Resource.Drawable.abc_ab_share_pack_mtrl_alpha)
.SetOngoing(true)
.Build();
StartForeground(100, notification);
}
}
Now we have our foreground Service working on Android, that show a notification ("Service Working"). Every time it starts. I make a show message foreground service to see it better while testing, in your case it suppose to close the app if that's what you want, but the functioning it's the same.
So having our background service working only left a way to call it so on our main page (as example) i will do the following:
MainPage.xaml
<VerticalStackLayout>
<Label
Text="Welcome to .NET Multi-platform App UI"
FontSize="18"
HorizontalOptions="Center" />
<Button
x:Name="CounterBtn"
Text="start Services"
Clicked="OnServiceStartClicked"
HorizontalOptions="Center" />
<Button Text="Stop Service" Clicked="Button_Clicked"></Button>
</VerticalStackLayout>
MainPage.xaml.cs
public partial class MainPage : ContentPage
{
IServiceTest Services;
public MainPage(IServiceTest Services_)
{
InitializeComponent();
ToggleAccelerometer();
Services = Services_;
}
//method to start manually foreground service
private void OnServiceStartClicked(object sender, EventArgs e)
{
Services.Start();
}
//method to stop manually foreground service
private void Button_Clicked(object sender, EventArgs e)
{
Services.Stop();
}
//method to work with accelerometer
public void ToggleAccelerometer()
{
if (Accelerometer.Default.IsSupported)
{
if (!Accelerometer.Default.IsMonitoring)
{
Accelerometer.Default.ReadingChanged += Accelerometer_ReadingChanged;
Accelerometer.Default.Start(SensorSpeed.UI);
}
else
{
Accelerometer.Default.Stop();
Accelerometer.Default.ReadingChanged -= Accelerometer_ReadingChanged;
}
}
}
//on accelerometer property change we call our service and it would send a message
private void Accelerometer_ReadingChanged(object sender, AccelerometerChangedEventArgs e)
{
Services.Start(); //this will never stop until we made some logic here
}
}
It's a long Answer and it would be great to have more official documentation about this! Hope it helps! If anyone can provide more info about IOS, Windows, MacCatalyst would be awesome!

Google AdMob test ads not showing after building in Unity

I wanted to implement google ads into my unity app with the official package (version 5.4.0, unity version is 2019.4.14):
https://github.com/googleads/googleads-mobile-unity/releases
When I run the project in the editor, the test ad is displayed. But when I build the app and install it on my phone, it doesn't show anything (my WiFi connection is good and I have access to Google services).
My ad manager:
using System;
using System.Collections;
using UnityEngine;
using GoogleMobileAds.Api;
public class AdsManager : MonoBehaviour
{
private static readonly string appId = "ca-app-pub-3940256099942544/3419835294";
private static readonly string bannerId = "ca-app-pub-3940256099942544/6300978111";
private static readonly string interstitialId = "ca-app-pub-3940256099942544/1033173712";
private static readonly string rewardedId = "ca-app-pub-3940256099942544/5224354917";
private static readonly string rewardedInterstitialId = "ca-app-pub-3940256099942544/5354046379";
private static readonly string nativeId = "ca-app-pub-3940256099942544/2247696110";
private InterstitialAd interstitialAd;
void Start()
{
MobileAds.Initialize(InitializationStatus => {});
this.RequestInterstitial();
}
public AdRequest CreateAdRequest() {
return new AdRequest.Builder().Build();
}
public void RequestInterstitial() {
Debug.Log("Requesting interstitial ad");
if(this.interstitialAd != null) {
this.interstitialAd.Destroy();
};
this.interstitialAd = new InterstitialAd(interstitialId);
this.interstitialAd.OnAdClosed += HandleOnInterstitialAdClosed;
this.interstitialAd.LoadAd(this.CreateAdRequest());
ShowInterstitial();
}
public void ShowInterstitial() {
if(this.interstitialAd.IsLoaded()) {
this.interstitialAd.Show();
} else {
this.RequestInterstitial();
}
}
public void HandleOnInterstitialAdClosed(object sender, EventArgs args)
{
Debug.Log("Closed interstitial ad");
}
}
I tried using the Android LogCat but it didn't find any mention of "Requesting interstitial ad". I get this log in the editor though and the test ad is shown. Any idea what is the issue?
Thanks
1 - The editor always shows test ads, after all when you use the app on the editor, you are testing it.
2 - If you want to display test ads on the device where you have installed the app, there are two ways: the first is to define your device as a test device in AdMob, the second to use strings for test ad units (https: //developers.google.com/admob/unity/test-ads#android)
3 - If you want to view real ads instead (be careful, if you see too many ads that you publish yourself and / or click them, you may have invalid traffic problems, so it is always better to view them as test ads), the real ads come to the end of a process:
First you need to create the app with the official app ID and ad unit strings that you get from the AdMob page for your app. Then you have to upload the app to a supported store, then you have to connect the app of the store to the app on AdMob, then the AdMob team performs a review on your app to verify that you are in order at a legal and regulatory level. , and eventually you will have your real, monetizable ads.

Android 8.1 REALLY Persistent Foreground Service Notification

I'm updating my Android app to work with 8.1 from 7. It's not mass-market it's the main alerting app for managed devices - so it NEEDS to stay on.
I have a "persistent" notification for my Foreground service, BUT now in 8+ there's a slider to mute my app notifications.
I can see that android system notifications and other apps remove this slider and display message:
"Notifications from this app can't be turned off".
How do I replicate this pattern?
I've read through notification, service, and channel documentation.
I'm already creating a channel with IMPORTANCE_DEFAULT, using setOngoing(true), and calling startForeground() on the service with the persistent notification:
Here's my Service create and start and channel creation to give you the gist:
public static final String CHANNEL_ID = "ForegroundWebsocketNotificationsServiceChannel";
public static final String CHANNEL_NAME = "WCMobility Notifications";
public static final String CHANNEL_DESCRIPTION = "Required notification and update alerts for WCMobility";
#Override
public void onCreate() {
super.onCreate();
noteMgr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
createNotificationChannel(CHANNEL_ID);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String action = intent.getAction();
notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID);
notificationBuilder.setContentTitle("Service Started");
notificationBuilder.setContentText("Not connected, not receiving messages! ");
int notificationIconID = getIconResId(ICON_FILENAME);
notificationBuilder.setSmallIcon(notificationIconID);
notificationBuilder.setOngoing(true);
notificationIntent = new Intent(this, MainActivity.class);
try{ notificationIntent.putExtras(intent.getExtras());
}catch (Exception e){}
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, FLAG_UPDATE_CURRENT);
notificationBuilder.setContentIntent(pendingIntent);
Notification notification = notificationBuilder.build();
startForeground(NOTIFICATION_ID, notification);
return START_NOT_STICKY;
}
private void createNotificationChannel(String channelId) {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(channelId, CHANNEL_NAME, importance);
channel.setDescription(CHANNEL_DESCRIPTION);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
noteMgr.createNotificationChannel(channel);
}
}
We learned that you can't fully block the user from turning off notifications, at least not on consumer devices. Our clients use MDMs and Managed Devices where they restrict access to settings pages etc for end users, plus since the app is primary app used on the phone, user base is not inclined to disable it. This has worked out for us. I did have to add a line to my ForegroundService class code to make the notification dismissable when there was no active session:
stopForeground(false);
stopSelf();
and make it persistant again when session resumed.
startForeground(notificationHelper.NOTIFICATION_ID, notification);
This has worked out for us so far.

Android Wear: Listen to incoming notifications

Is it possible to listen for incoming notifications in an Wearable Android App? I have tried to implement a NotificationListenerService, but the service's onNotificationPosted() is never called:
public class MyListenerService extends NotificationListenerService {
#Override
public void onCreate() {
super.onCreate();
Log.d("NotificationListener", "This works....");
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
Log.i("NotificationListener", "... but this method won't be called.");
}
}
Try this:
adb shell settings put secure enabled_notification_listeners com.google.android.wearable.app/com.google.android.clockwork.stream.NotificationCollectorService:$YOUR_PACKAGE/$YOUR_PACKAGE.$YOUR_NOTIFICATION_LISTENER
It's not possible to use a NotificationListenerService in Android Wear as there is no screen for the user to allow this.
You have to do it in the device's app and to use the Wearable Data Layer API to perform the action on Wear's side.

Windows Phone 7 equivalent to NSNotificationCenter?

I'm new to WP7 and coming from iPhone development. On iPhone I'm used to use NSNotificationCenter to notify my program of something. NSNotificationCenter is build-in the framework out of the box. Is there something similar in WP7? I stumbled uppon MVVM-Light Toolkit but I'm not sure how to use it correctly.
What I want to do:
Register to an Notification-Id and do something when Notification-Id is received
Send Notification with Notification-Id and a context (object to pass to observers)
Everyone who registers to the same Notification-Id will be notified
So something like: Registering
NotificationCenter.Default.register(receiver, notification-id, delegate);
Sending:
NotificationCenter.Default.send(notification-id, context);
Example for Registering:
NotificationCenter.Default.register(this, NotifyEnum.SayHello, m => Console.WriteLine("hello world with context: " + m.Context));
Sending ...
NotificationCenter.Default.send(NotifyEnum.SayHello, "stackoverflow context");
Here is how to do with the MVVM Light Toolkit:
Registering:
Messenger.Default.Register<string>(this, NotificationId, m => Console.WriteLine("hello world with context: " + m.Context));
Sending:
Messenger.Default.Send<string>("My message", NotificationId);
Here http://www.silverlightshow.net/items/Implementing-Push-Notifications-in-Windows-Phone-7.aspx you will find a great example on how to use push notification on windows phone 7.
I'm pretty sure that you archive the same result as NSNotificationCenter by creating a singleton which holds a list of observables that implements a specific interface based on your bussiness requirements, or call a lamba, or trigger an event, for each message sent by this singleton you will interate the list of observables and checking the message id, once you find one or more, you can call the interface method, or execute the lambda expression or trigger the event defined to digest the message contents.
Something like below:
public class NotificationCenter {
public static NotificationCenter Default = new NotificationCenter();
private List<KeyValuePair<string, INotifiable>> consumers;
private NotificationCenter () {
consumers = new List<INotifiable>();
}
public void Register(string id, INotifiable consumer) {
consumers.Add(new KeyValuePair(id, consumer));
}
public void Send(String id, object data) {
foreach(KeyValuePair consumer : consumers) {
if(consumer.Key == id)
consumer.Value.Notify(data);
}
}
}
public interface INotifiable {
void Notify(object data);
}
public class ConsumerPage : PhoneApplicationPage, INotifiable {
public ConsumerPage() {
NotificationCenter.Default.Register("event", this);
}
private Notify(object data) {
//do what you want
}
}
public class OtherPage : PhoneApplicationPage {
public OtherPage() {
NotificationCenter.Default.Send("event", "Hello!");
}
}