Broadcast doesn't update battery change value - android

I have created a notification in my application to show the battery level in percentage. My manifest file is
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.create.bg"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.BATTERY_STATS"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:label="#string/app_name"
android:name=".CreateBgActivity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".BatteryReceive" >
<intent-filter>
<action android:name="android.intent.action.BATTERY_CHANGED"></action>
</intent-filter>
</receiver>
</application>
I created a separate class that extends BroadcastReceiver to receive the battery level and notify in the status bar. My code is:
public class BatteryReceive extends BroadcastReceiver {
private String bat = "android.intent.action.BATTERY_CHANGED";
#Override
public void onReceive(Context context, Intent intent) {
//Log.d("Battery Level", ""+intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1));
if(intent.getAction().equals(bat)) {
Toast.makeText(context, "Battery Level"+intent.getIntExtra("level", 0), Toast.LENGTH_SHORT).show();
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
final Notification notifyDetails = new Notification(R.drawable.ic_launcher,""+intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1),System.currentTimeMillis());
//notifyDetails.flags = Notification.FLAG_AUTO_CANCEL;
notifyDetails.setLatestEventInfo(context, "Batter Level", ""+intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1), null);
mNotificationManager.notify(1, notifyDetails);
}
}
}
I could't get any notification or Log output for the battery level :( Is it anything wrong with my code. SOme one help me out of this.

#Override
public void onReceive(Context context, Intent intent) {
//Log.d("Battery Level", ""+intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1));
if(intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) {
// This is called when Your battery is changed
}
}

Change:
if(intent.getAction().equals(bat))
To:
if(intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED))

Related

BroadcastReceiver ClassNotFoundException Xamarin Android

I am getting ClassNotFoundException when trying to run the below code to start BroadCastReceiver. there is a custom notification and a buttonview to it, when i click the button the notification will close, but it is giving the below exception.
and i have created the notification channel for API 26 and above in OnCreate method too
public void OpenActivity(object sender, EventArgs e)
{
Intent intent = new Intent(this, typeof(DrawRect));
intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop);
PendingIntent pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
RemoteViews remoteView = new RemoteViews(PackageName, Resource.Layout.NotificationLayout);
int notificationId = (int)SystemClock.CurrentThreadTimeMillis();
Intent buttonIntent = new Intent("button_clicked");
buttonIntent.PutExtra("id", notificationId);
PendingIntent buttonPendingIntent =
PendingIntent.GetBroadcast(this, notificationId, buttonIntent, 0);
remoteView.SetOnClickPendingIntent(Resource.Id.cloceNotification,
buttonPendingIntent);
NotificationCompat.Builder notify = new
NotificationCompat.Builder(this, "Diet")
.SetSmallIcon(Resource.Mipmap.icon)
.SetContentTitle("Diet")
.SetContentText("My App")
.SetPriority(NotificationCompat.PriorityHigh).SetContentIntent(pendingIntent).SetOngoing(true).SetStyle(new NotificationCompat.DecoratedCustomViewStyle()).SetCustomContentView(remoteView);
NotificationManagerCompat notificationCompat = NotificationManagerCompat.From(this);
notify.Build().Flags |= NotificationFlags.OnlyAlertOnce;
notificationCompat.Notify(notificationId, notify.Build());
FinishAndRemoveTask();
}
BroadCastReceiver Class:
public class Button_listener : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
NotificationManagerCompat notificationManager = NotificationManagerCompat.From(context);
notificationManager.Cancel(intent.GetIntExtra("id",1));
Toast.MakeText(context, "From Broadcaster", ToastLength.Long).Show();
}
}
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="DietCam.DietCam" android:installLocation="auto">
<uses-sdk android:minSdkVersion="19" android:targetSdkVersion="28" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<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" android:debuggable="true">
<activity android:label="DrawRect" android:theme="#style/Theme.AppCompat.Transparent.NoActionBar" android:name="md580a1eddd40074c89f21a5ec99d8b044c.DrawRect" android:screenOrientation="sensor"/>
<activity android:label="SplashScreen" android:name="md580a1eddd40074c89f21a5ec99d8b044c.SplashScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".Main.Button_listener">
<intent-filter>
<action android:name="button_clicked"/>
</intent-filter>
</receiver>
</application>
</manifest>
Exception:
Unhandled Exception:
Java.Lang.RuntimeException: Unable to instantiate receiver DietCam.DietCam.Main.Button_listener: java.lang.ClassNotFoundException: Didn't find class "DietCam.DietCam.Main.Button_listener" on path: DexPathList[[zip file "/data/app/DietCam.DietCam-1/base.apk"],nativeLibraryDirectories=[/data/app/DietCam.DietCam-1/lib/x86, /data/app/DietCam.DietCam-1/base.apk!/lib/x86, /system/lib, /vendor/lib]]
Removed <receiver> tag from AndroidManifest.xml file and added the BroadcastReceiver and IntentFilter attributes to the BroadcastReceiver class
Removed the below tag from Manifest file
<receiver android:name=".Main.Button_listener">
<intent-filter>
<action android:name="button_clicked"/>
</intent-filter>
</receiver>
Added Attributes to BroadcastReceiver class:
[BroadcastReceiver(Enabled = true, Exported = false)]
[IntentFilter(new[] { "button_clicked" } )]
public class Button_listener : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
NotificationManagerCompat notificationManager = NotificationManagerCompat.From(context);
notificationManager.Cancel(intent.GetIntExtra("id",1));
Toast.MakeText(context, "From Broadcaster", ToastLength.Long).Show();
}
}

Cannot use notification in android? [duplicate]

This question already has an answer here:
Android show a notification not working
(1 answer)
Closed 6 years ago.
I am sending a notificatioin from this Broadcast reciver which is triiggered by an alarm manager to send sms but i cant see any notification.
I also tried to include sent intent and delivery intent but cant use registerReciever here.
Here is my Code.
Broadcast Reciever
public class MyReceiver extends BroadcastReceiver {
String SENT="sent";
public final String tag="com.example.pritesh.smstimer";
public MyReceiver() {
}
//#Override
public void onReceive(Context context, Intent intent) {
Log.i(tag,"Sending");
NotificationManager notificationManager= (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent1=new Intent(context,Time_Picker.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context,0,intent1,0);
Notification.Builder notification=new Notification.Builder(context)
.setContentTitle("SMS SENT")
.setContentText("Your SMS has Been Sent")
.setContentIntent(pendingIntent);
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(Time_Picker.Phone,null, Time_Picker.Message, null, null);
notificationManager.notify(0,notification.build());
Toast.makeText(context, "Sms Sent", Toast.LENGTH_LONG).show();
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.SEND_SMS" />
<application
android:allowBackup="true"
android:icon="#drawable/favicon"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".Time_Picker"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".noti"/>
<activity android:name=".MainActivity">
</activity>
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true"
android:launchMode="singleTask"
android:taskAffinity=""
android:excludeFromRecents="true"/>
</application>
Have you registered the receiver in your androidmanifest.xml or called registerReceiver to do the same? I don't think it will work until you do.
See here:https://developer.android.com/guide/topics/manifest/receiver-element.html

Notification manager not working with alarmManager

I am trying to use alarm manager to show notification after 5 sec. I have tried many sites but was not able to understand please give a simple example for explaining how to use alarm manager and connect notification with it.
I am newbie.
this is function i used to set alarm and I am not getting notification after 5 secs actually not at all not in emulator nor in android mobile. If put code to create notififcation with a button pressing that is working great.
public void setAlarm(View view)
{
Intent alertIntent = new Intent(this, AlertReciver.class);
Long alertTime = new GregorianCalendar().getTimeInMillis()+5*1000;
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, alertTime, PendingIntent.getBroadcast(this, 1, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT));
tv.setText("completed");
}
and this class to make it work
public class AlertReciver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
createNotification(context,"times Up", "5 SEcond has passed", "Alert");
}
public void createNotification(Context context,String msg, String msgText, String msgAlert){
PendingIntent notificIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ne)
.setContentTitle(msg)
.setTicker(msgAlert)
.setContentText(msgText);
mBuilder.setContentIntent(notificIntent);
mBuilder.setDefaults(NotificationCompat.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
this is the manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.deepaksingh.goinnotifying" >
<uses-permission android:name="android.permission.alarm.permission.SET_ALARM" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MoreInfoNotification"
android:label="#string/title_activity_more_info_notification" >
<meta-data
android:name="android support.PARENT_ACTIVITY"
android:value=".MainActivity" />
</application>
You havn't set permission for wake:
<uses-permission android:name="android.permission.WAKE_LOCK" />
ANd you didn't register your recevier.Here.
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MoreInfoNotification"
android:label="#string/title_activity_more_info_notification" >
<meta-data
android:name="android support.PARENT_ACTIVITY"
android:value=".MainActivity" />
<receiver android:name=".AlertReciver "/>
</application>

Android 4.x devices receive GCM messages, but Android 2.3 devices Don't

My android app never receives GCM messages on 2.3 devices, but it does on 4.x devices. I can register all devices (2.3 and 4.x) successfully. I thought it might have something to do with this issue, but it seems like I have my android manifest configured properly. Would anyone be able to eyeball my IntentService and BroadcastReceiver and see if they notice any problems? Any help would be greatly appreciated. Note that onHandeIntent() is never called for Android 2.3 when sending notifications while I have the debugger attached. I checked 4.x devices, and they do trigger the debugger in onHandleIntent().
Thanks!
Android Manfest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="my.package"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="9" android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="my.package.matchtracker.permission.C2D_MESSAGE" />
<permission android:name="my.package.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<receiver
android:name=".GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="my.package" />
</intent-filter>
</receiver>
<service android:name=".NotificationIntentService" android:enabled="true" />
<activity android:name="com.gigya.socialize.android.GSWebViewActivity" />
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:configChanges="orientation|screenSize"
android:theme="#android:style/Theme.NoTitleBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Broadcast Receiver:
package my.package;
import android.app.*;
import android.content.*;
public class GcmBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationIntentService.runIntentInService(context, intent);
setResultCode(Activity.RESULT_OK);
}
}
Notification Intent Service
public class NotificationIntentService extends IntentService {
private String TAG = "NotificationIntentService";
public NotificationIntentService() {
super(AppConstants.GCM_SENDER_ID);
}
public NotificationIntentService(String name) {
super(name);
// TODO Auto-generated constructor stub
}
private static PowerManager.WakeLock sWakeLock;
private static final Object LOCK = NotificationIntentService.class;
static void runIntentInService(Context context, Intent intent) {
synchronized(LOCK) {
if (sWakeLock == null) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "my_wakelock");
}
}
sWakeLock.acquire();
intent.setClassName(context, NotificationIntentService.class.getName());
context.startService(intent);
}
public final void onHandleIntent(Intent intent) {
try {
String action = intent.getAction();
if (action.equals("com.google.android.c2dm.intent.REGISTRATION")) {
//don't care.
} else if (action.equals("com.google.android.c2dm.intent.RECEIVE")) {
handleMessage(intent);
}
} finally {
synchronized(LOCK) {
sWakeLock.release();
}
}
}
private void handleMessage(Intent intent) {
Bundle b = intent.getExtras();
String text = b.getString("text"),
title = b.getString("title"),
largeImageUrl = b.getString("largeImageUrl");
Log.i(TAG, "Message is " + text);
NotificationManager nm = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
Bitmap bit=null;
if (largeImageUrl != null && !largeImageUrl.isEmpty()) {
try{bit = BitmapFactory.decodeStream((InputStream)new URL(largeImageUrl).getContent());
} catch (Exception e){}
}
NotificationCompat.Builder nc = new NotificationCompat.Builder(this)
.setContentTitle(title)
.setContentText(text)
.setSmallIcon(R.drawable.ic_launcher)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setAutoCancel(true) //notification disappears when clicked
.setContentIntent(PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT));
//bit = Bitmap.createScaledBitmap(bit, android.R.dimen.notification_large_icon_width, android.R.dimen.notification_large_icon_height, true);
if (bit != null) nc.setLargeIcon(bit);
nm.notify(0, nc.build());
}
}
The first potential problem I can see is this :
The package name in the permission element is not the same as the one in the uses-permission element. In my app (which targets Android 2.2) they are identical.
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="my.package.matchtracker.permission.C2D_MESSAGE" />
<permission android:name="my.package.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
If you are using product flavor with different applicationId, see my answer to the question GCM messages are not received on android 2.3.6 v but working fine on android 4.X v
GCM need google play services installed on device but in version 2.3 it's not installed by default.

Foreground service doesn't start at boot time

I am trying to start a foreground service at boot time, but it never starts, however If i try to start a normal background service. It starts perfectly fine.
Can you please let me what is wrong with my code ?
My code is:
Manifest file:
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<receiver android:name="com.test.andsrvfg.AndSrvFgService">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name="AndSrvFgService">
<intent-filter>
<action android:name="com.test.andsrvfg.AndSrvFgService"></action>
</intent-filter>
</service>
</application>
BroadcastReceiver to handle ACTION_BOOT_COMPLETED:
public class AndSrvFgStarter extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Intent i = new Intent();
i.setAction("com.test.andsrvfg.AndSrvFgService");
context.startService(i);
}
}
}
The actual service is like:
public class AndSrvFgService extends Service {
private boolean bForeground = false;
public AndSrvFgService() {
}
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(!bForeground) {
bForeground = true;
Notification note = new Notification( 0, null, System.currentTimeMillis() );
note.flags |= Notification.FLAG_NO_CLEAR;
startForeground( 1242, note );
}
return START_STICKY;
}
#Override
public void onDestroy() {
if(bForeground) {
stopForeground(true);
}
}
This code works for me:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dfsdf"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.google.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
<service android:name=".MyService"/>
<receiver android:enabled="true"
android:name=".BootUpReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter >
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>
</application>
</manifest>
Put this in the receiver:
android:permission="android.permission.RECEIVE_BOOT_COMPLETED"
Set enable to true:
android:enabled="true"

Categories

Resources