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();
}
}
Related
I am developing android application which need auto restart when restart device for that I am using broadcast receiver with action BOOT_COMPLETED.
Broadcast receiver is receiving message when I am restarting device but in restart method I want to start main activity for that I used Intent but in onReceive method of receiver I am getting null context so I am unable to restart main Activity.
Below is code for that.
MainActivity.java
private Object activity;
private TextView tvImeiNum;
private BroadcastReceiver rebootreceiver;
private IntentFilter filter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvImeiNum = (TextView)findViewById(R.id.tv_imeinum);
filter = new IntentFilter();
filter.addAction(Intent.ACTION_BOOT_COMPLETED);
filter.addAction(Intent.ACTION_REBOOT);
rebootreceiver = new BootUpReceiver(MainActivity.this);
LocalBroadcastManager.getInstance(this).registerReceiver(rebootreceiver,
filter);//registering receiver
generateUniqueCode();
}
BootupReceiver.java
public class BootUpReceiver extends BroadcastReceiver {
MainActivity ma;
public BootUpReceiver(MainActivity maContext){
ma=maContext;
}
public BootUpReceiver(){
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
Log.d("TAG REBOOT", "onReceive: " + intent);
Log.d("Reboot complete", "connection");
GlobalTool.restartApplication(context);
}
}
}
GlobalTool.java
public class GlobalTool {
#RequiresApi(api = Build.VERSION_CODES.M)
public static void restartApplication(Context context) {
Log.d("IN App restart:", "");
Log.d("TAG", "restartApplication: ");
if(context != null)
{
Log.d("TAG NULL", "restartApplication: ");
Intent mainIntent = new Intent(context, MainActivity.class);
AlarmManager alarmMgr = (AlarmManager)
context.getSystemService(ALARM_SERVICE);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntent(mainIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
long alarmTime = System.currentTimeMillis() + (1 * 1000);
alarmMgr.setExact(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent);
Log.d("TAG", "restartApplication: 111");
Log.d("TAG", "restartApplication: 111");
}
else {
Intent mainIntent = new Intent(context, MainActivity.class);
AlarmManager alarmMgr = (AlarmManager)
context.getSystemService(ALARM_SERVICE);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntent(mainIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
long alarmTime = System.currentTimeMillis() + (1 * 1000);
alarmMgr.setExact(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent);
Log.d("TAG", "restartApplication: 111");
Log.d("TAG", "restartApplication: 111");
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.kioskappdemo">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission
android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:name="KioskApplication"
android:allowBackup="true"
android:dataExtractionRules="#xml/data_extraction_rules"
android:fullBackupContent="#xml/backup_rules"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.KioskAppDemo"
tools:targetApi="31"
tools:ignore="Instantiatable">
<service
android:name=".RebootService"
android:enabled="true"
android:exported="true"></service>
<activity
android:name=".MainActivity"
android:exported="true"
android:screenOrientation="landscape"
android:theme="#style/Theme.AppCompat.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".Activity.BootUpReceiver"
android:enabled="true"
android:exported="true">
<intent-filter >
<action
android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.REBOOT" />
<action
android:name="android.intent.action.QUICKBOOT_POWERON" />
<action android:name="com.reboot.test" />
<action
android:name="android.intent.action.TIMEZONE_CHANGED" />
<action
android:name="android.intent.action.DATE_CHANGED" />
</intent-filter>
</receiver>
</application>
</manifest>
Some you code improvements:
Don't put context to Brodcast Receiver constructor. Use the Context from onReceive method
public class BootUpReceiver extends BroadcastReceiver {
public BootUpReceiver(){
//TODO log
}
...
You should not use LocalBroadcastManager::registerReceiver call. If Broadcast receiver is added to AndroidManifest then it will be started by the system.
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver
android:name=".activity.BootUpReceiver"
android:enabled="true"
android:exported="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter >
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
Don't use CamelCase for package names (use .activity.BootUpReceiver insetad .Activity.BootUpReceiver)
I am trying to show notification at specific date I am using alarm manager and broadcast receiver to show notifications but the problem is notification works only when app is open and when app is closed notification does not show. Below is my code:
Reminder.java
public class Reminder extends AppCompatActivity {
long reminderDateTimeInMilliseconds = 000;
Button but;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reminder);
but = findViewById(R.id.but);
but.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createNotifyChannel();
Intent intent = new Intent(Reminder.this,ReminderBroadcast.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(Reminder.this,0,intent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Calendar calendarToSchedule = Calendar.getInstance();
calendarToSchedule.setTimeInMillis(System.currentTimeMillis());
calendarToSchedule.clear();
//.Set(Year, Month, Day, Hour, Minutes, Seconds);
calendarToSchedule.set(2020, 8, 20, 19, 12, 0);
reminderDateTimeInMilliseconds = calendarToSchedule.getTimeInMillis();
alarmManager.setExact(AlarmManager.RTC_WAKEUP,reminderDateTimeInMilliseconds,pendingIntent);
}
});
}
private void createNotifyChannel(){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
CharSequence name = "ReminChannel";
String desc = "This is my channel";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("mynotif",name,importance);
channel.setDescription(desc);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
}
ReminderBroadcast.java
public class ReminderBroadcast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationCompat.Builder notif = new NotificationCompat.Builder(context,"mynotif")
.setContentTitle("Appointment reminder")
.setContentText("Hello there")
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
NotificationManagerCompat manager = NotificationManagerCompat.from(context);
manager.notify(200,notif.build());
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.app.firstapp">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<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">
<activity android:name=".Reminder">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ThirdActivity" />
<activity android:name=".SecondActivity" />
<activity android:name=".MainActivity">
</activity>
<receiver android:name=".ReminderBroadcast"/>
</application>
</manifest>
What am I doing wrong?
i m generating notification.so i created the notification and i m getting the notification when i click the button.now,i created onclick function and some toast,but when i clicked on thone button in notificatio i m getting toast message. i dont know whats wrong in below code.so please help.thanks in adavance.
this is my broadcast activity
public class NotificationBroadcast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(NotificationGenerator.NOTIFY_PLAY))
{
Toast.makeText(context,"NOTIFY PLAY",Toast.LENGTH_LONG).show();
}
if(intent.getAction().equals(NotificationGenerator.NOTIFY_PAUSE))
{
Toast.makeText(context,"NOTIFY PAUSE",Toast.LENGTH_LONG).show();
}
if(intent.getAction().equals(NotificationGenerator.NOTIFY_NEXT))
{
Toast.makeText(context,"NOTIFY NEXT",Toast.LENGTH_LONG).show();
}
if(intent.getAction().equals(NotificationGenerator.NOTIFY_DELETE))
{
Toast.makeText(context,"NOTIFY DELETE",Toast.LENGTH_LONG).show();
}
if(intent.getAction().equals("com.example.murarilal.atry.previous"))
{
Toast.makeText(context,"NOTIFY PREVIOUS",Toast.LENGTH_LONG).show();
}
}
}
this is notifiction builder activity
public class NotificationGenerator{
public static final String NOTIFY_PREVIOUS="com.example.murarilal.atry.previous";
public static final String NOTIFY_DELETE="com.example.murarilal.atry.delete";
public static final String NOTIFY_PAUSE="com.example.murarilal.atry.pause";
public static final String NOTIFY_PLAY="com.example.murarilal.atry.play";
public static final String NOTIFY_NEXT="com.example.murarilal.atry.next";
private static final int NOTIFICATION_ID_OPEN_ACTIVITY=1;
private static String ID = "default";
public static void openActivityNotification(Context context) {
RemoteViews expandView=new RemoteViews(context.getPackageName(),R.layout.notification);
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
int requestID = (int) System.currentTimeMillis();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_MAX);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context);
notificationBuilder.setChannelId(ID);
Intent notifyIntent=new Intent(context,BlankFragment2.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent=PendingIntent.getActivity(context,requestID,notifyIntent,PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.setContentIntent(pendingIntent);
Intent intent = new Intent(context, BlankFragment2.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(intent);
notificationBuilder.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ed)
.setTicker("Hearty365")
// .setPriority(Notification.PRIORITY_MAX)
.setContentTitle("try")
.setCustomBigContentView(expandView)
.setContentText("notification")
.setContentInfo("Info");
notificationManager.notify(NOTIFICATION_ID_OPEN_ACTIVITY, notificationBuilder.build());
}
public static void customBigNotification(Context context)
{
int requestID = (int) System.currentTimeMillis();
RemoteViews expandView=new RemoteViews(context.getPackageName(),R.layout.notification);
NotificationCompat.Builder nc=new NotificationCompat.Builder(context);
NotificationManager nm=(NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
Intent notifyIntent=new Intent(context,BlankFragment2.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent=PendingIntent.getActivity(context,requestID,notifyIntent,PendingIntent.FLAG_UPDATE_CURRENT);
nc.setContentIntent(pendingIntent);
nc.setSmallIcon(R.drawable.ic_play_circle_filled_black_24dp);
nc.setAutoCancel(true);
nc.setCustomBigContentView(expandView);
nc.setContentTitle("music player");
nc.setContentText("control audio");
nc.getBigContentView().setTextViewText(R.id.songName,"shape of you");
setListeners(expandView,context);
}
private static void setListeners(RemoteViews views, Context context)
{
int requestID = (int) System.currentTimeMillis();
Intent previous= new Intent(NOTIFY_PREVIOUS);
Intent next=new Intent(NOTIFY_NEXT);
Intent delete=new Intent(NOTIFY_DELETE);
Intent play=new Intent(NOTIFY_PLAY);
Intent pause=new Intent(NOTIFY_PAUSE);
PendingIntent pPrevious=PendingIntent.getBroadcast(context,requestID,previous,PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.previous,pPrevious);
PendingIntent pDelete=PendingIntent.getBroadcast(context,requestID,delete,PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.cancel,pDelete);
PendingIntent pNext=PendingIntent.getBroadcast(context,requestID,next,PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.next,pNext);
PendingIntent pPlay=PendingIntent.getBroadcast(context,requestID,play,PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.play,pPlay);
PendingIntent pPause=PendingIntent.getBroadcast(context,requestID,pause,PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.play,pPause);
}
}
manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.murarilal.atry">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<permission android:name="android.permission.MEDIA_CONTENT_CONTROL" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:largeHeap="true"
android:supportsRtl="true"
android:theme="#style/mytheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
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=".screen"
android:label="#string/title_activity_screen"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".com.layout.blankFragment2"
android:label="#string/hello_blank_fragment"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name="com.exlayout.albumSongs"
android:label="#string/title_activity_album_songs"
android:theme="#android:style/Theme.Holo.Light.DarkActionBar" />
<activity
android:name="com.exlayout.Main2Activity"
android:label="#string/title_activity_main2"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".Main2Activity"
android:label="#string/title_activity_main2"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".albumSongs"
android:label="#string/title_activity_album_songs"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".albumSong"
android:label="#string/title_activity_album_song"
android:theme="#android:style/Theme.Holo.Light.DarkActionBar" />
<activity
android:name=".BlankFragment2"
android:label="#string/hello_blank_fragment"
android:theme="#style/AppTheme.NoActionBar" />
<receiver android:name=".NotificationBroadcast">
<intent-filter>
<action android:name="com.example.murarilal.atry.previous" />
<action android:name="com.example.murarilal.atry.delete" />
<action android:name="com.example.murarilal.atry.pause" />
<action android:name="com.example.murarilal.atry.next" />
<action android:name="com.example.murarilal.atry.play" />
</intent-filter>
</receiver>
<activity
android:name=".genreSongs"
android:label="#string/title_activity_genre_songs"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name="com.exlayout.genreSongs"
android:label="#string/title_activity_genre_songs"
android:theme="#android:style/Theme.Holo.Light.DarkActionBar" />
<activity
android:name=".artist_Songs"
android:label="#string/title_activity_artist__songs"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name="com.exlayout.artist_Songs"
android:label="#string/title_activity_artist__songs"
android:theme="#android:style/Theme.Holo.Light.DarkActionBar" />
<activity
android:name=".checkActivity"
android:label="#string/title_activity_check"
android:theme="#style/Theme.AppCompat.Light.NoActionBar" />
<activity
android:name=".favoutitesActivity"
android:label="#string/title_activity_favoutites"
android:theme="#style/AppTheme" />
<activity
android:name=".recent"
android:label="#string/title_activity_recent"></activity>
</application>
</manifest>
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>
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))