I created a simple service and now I am making a notification for this. I am writing a class for notification. After writing all code, three lines are underlined with red color one is this function getSystemService(ns); at line 14, second is this one getApplicationContext(); on line 20 and the third one is again same function as first one but on line 31 in cancelNotification() function. here is my complete code
package com.zafar.batterynotify;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
public class Notify {
private static final int NOTIFICATION_ID = 1;
public void initNotification() {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon = R.drawable.ic_launcher;
CharSequence tickerText = "Service Started";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
notification.flags = Notification.FLAG_ONGOING_EVENT;
Context context = getApplicationContext();
CharSequence contentTitle = "Ongoing service";
CharSequence contentText = "This is service is ongoing";
Intent notificationIntent = new Intent(context, BatteryNotify.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, notification);
}
public void cancelNotification() {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
mNotificationManager.cancel(NOTIFICATION_ID);
}
}
Edit Updated code
My service class
package com.zafar.batterynotify;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class BatteryService extends Service {
Notify notification = new Notify();
String ns = Context.NOTIFICATION_SERVICE;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
notification.initNotification(Context.NOTIFICATION_SERVICE);
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
public void onDestroy() {
super.onDestroy();
notification.cancelNotification(Context.NOTIFICATION_SERVICE);
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
}
Notify class
package com.zafar.batterynotify;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
public class Notify {
private static final int NOTIFICATION_ID = 1;
public void initNotification(Context actContext) {
//String ns = Context.NOTIFICATION_SERVICE;
//Context context = actContext.getApplicationContext();
NotificationManager mNotificationManager = actContext.getSystemService(ns);
int icon = R.drawable.ic_launcher;
CharSequence tickerText = "Service Started";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
notification.flags = Notification.FLAG_ONGOING_EVENT;
Context context = actContext.getApplicationContext();
CharSequence contentTitle = "Ongoing service";
CharSequence contentText = "This is service is ongoing";
Intent notificationIntent = new Intent(context, BatteryNotify.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, notification);
}
public void cancelNotification(Context actContext) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = actContext.getSystemService(ns);
mNotificationManager.cancel(NOTIFICATION_ID);
}
}
don't try to use getApplicationContext(), instead create MyApplication class, inherited from the Application, then inside that class do the following:
public class MyApplication extends Application {
private static MyApplication instance;
#Override
public void onCreate() {
super.onCreate();
instance = this;
.........
}
public static Context getContext() {
return instance;
}
After that, you may use MyApplication.getContext() anywhere if you need a context and don't have an Activity lying around.
Pass your context from calling Activity or service to your class and use it:
public void initNotification(Context actContext) {
//...
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = actContext.getSystemService(ns);
//...
}
public void cancelNotification(Context actContext) {
//...
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = actContext.getSystemService(ns);
//...
}
Related
I'm trying to update the timer in the notification in HH:MM:SS format. I have a Service class where the timer is incremented. I can only display the seconds in the notification. I have some trouble with displaying the time in the mentioned format.
This is MyService.java class
package com.alfen.timerservice;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
public class MyService extends Service {
private static final String TAG = "MyService";
private static final String CHANNEL_ID = "NotificationChannelID";
static int sec = 0;
Timer timer;
public MyService() {
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
restartServiceIntent.setPackage(getPackageName());
startService(restartServiceIntent);
super.onTaskRemoved(rootIntent);
}
#Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
sec = intent.getIntExtra("sec", 0);
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void run() {
Intent intent = new Intent();
intent.setAction("Timer");
sec++;
String ty = setTime(sec); //Also can I do this? I think this is throwing some exception
try{NotificationUpdate(sec,ty);}catch(Exception e){}
intent.putExtra("sec", sec);
sendBroadcast(intent);
}
}, 0, 1000);
// toast("MyService is running");
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
timer.cancel();
toast("Timer Stopped");
Intent intent = new Intent();
intent.putExtra("flag", false);
}
#RequiresApi(api = Build.VERSION_CODES.O)
public void NotificationUpdate(Integer sec, String t) {
Intent notificationIntent = new Intent(this,MainActivity.class);
final PendingIntent pendingIntent = PendingIntent
.getActivity(this,0,notificationIntent,0);
Notification notification = new NotificationCompat.Builder(this,CHANNEL_ID)
.setContentTitle("Timer")
.setContentText(sec.toString()) //this is working fine
// .setContentText(t)
//When I try to do this the app crashes when the service is started
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentIntent(pendingIntent)
.build();
startForeground(1,notification);
NotificationChannel nc = new NotificationChannel(CHANNEL_ID,"Timer Notification"
,NotificationManager.IMPORTANCE_NONE);
NotificationManager nm = getSystemService(NotificationManager.class);
nm.createNotificationChannel(nc);
nm.notify(1,notification);
}
private String setTime(int sec) {
int hours = sec / 3600;
int mins = (sec%3600) /60;
int secs = sec % 60;
String t = String.format(Locale.getDefault(),"%02d:%02d:%02d",hours,mins,secs);
toast(t);
return t;
}
public void toast(String s){
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_SHORT).show();
}
}
Whenever I try to call the setTime() function inside onStartCommand the app keeps crashing
If I change the function like this (without passing the String argument) its working.
public void NotificationUpdate(Integer sec) {
Intent notificationIntent = new Intent(this,MainActivity.class);
final PendingIntent pendingIntent = PendingIntent
.getActivity(this,0,notificationIntent,0);
Notification notification = new NotificationCompat.Builder(this,CHANNEL_ID)
.setContentTitle("Timer")
.setContentText(sec.toString())
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentIntent(pendingIntent)
.build();
How do I solve this? Also how to do the same using a custom Notification layout using RemoteViews?
The simple trick is that update your notification data and call notification with different notification id when time is changed. Hope it will work.
Hello I created Broadcast Receiver in the Service class to receive application notifications but it doesn't receive any intents from Notification. When I make the broadcast receiver static, the problem is solved but at this time I cannot access the elements of the non-static upper class. I have to solve this without making it static.
My Code:
public class BackgroundService extends Service {
private final int TASK_DELAY = 0;
private final int TASK_PERIOD = 5 * 1000;
int NOTIFICATION_ID = 1;
private Context context;
private NotificationCompat.Builder builder;
private NotificationManager notificationManager;
private static Timer timer;
private PendingIntent test;
private int runRate;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//User pressed a notifiacition button
Log.w(TAG, "onReceive: Recived" );
}
// constructor
public MyReceiver(){
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
public static Timer getTimer() {
return timer;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onCreate() {
Toast.makeText(this, "Service has been started!", Toast.LENGTH_SHORT).show();
context = getApplicationContext();
timer = new Timer();
runRate = 0;
builder = new NotificationCompat.Builder(context)
.setSmallIcon(android.R.drawable.ic_dialog_alert)
.setContentTitle("KolBoost")
.setContentText("Arkaplan servisi etkinleştirildi!")
.setAutoCancel(false)
.setPriority(NotificationCompat.PRIORITY_HIGH);
MyReceiver myReceiver = new MyReceiver();
IntentFilter filter = new IntentFilter();
Intent close = new Intent(getBaseContext(), BackgroundService.class);
close.setAction("CLOSE_SERVICE");
PendingIntent closeServiceIntent = PendingIntent.getBroadcast(getBaseContext(), 0, close, 0);
Intent i2 = new Intent(getBaseContext(), BackgroundService.class);
i2.setAction("BOOST_MEMORY");
PendingIntent boostIntent = PendingIntent.getBroadcast(getBaseContext(), 0, i2, 0);
Intent launch = new Intent(getBaseContext(),BackgroundService.class);
launch.setAction("OPEN_MANAGER");
PendingIntent contentIntent = PendingIntent.getBroadcast(getBaseContext(), 0, launch, 0);
builder.setContentIntent(contentIntent);
builder.addAction(0, "Clear Memory", boostIntent);
builder.addAction(0, "Exit", closeServiceIntent);
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(getBaseContext(), MainActivity.class);
test = PendingIntent.getActivity(getBaseContext(), NOTIFICATION_ID, notificationIntent, PendingIntent.FLAG_NO_CREATE);
//I'm adding actions to intentFilter.
filter.addAction(close.getAction());
filter.addAction(i2.getAction());
filter.addAction(launch.getAction());
//Registering Receiver with intentFilter
registerReceiver(myReceiver,filter);
super.onCreate();
}
#Override
public void onDestroy() {
timer.cancel();
notificationManager.cancelAll();
Log.d(TAG, "onDestroy: Destroyed");
super.onDestroy();
}
}
I am trying to connect following MainActivity.java's buttonclick intents to a pendingIntent in my RathuMakara.java Service class. I tried to use CONSTANTS, but I was not successful. I want to add buttons to notification to control the music. So that I know, I should use pending intents, that's why I am trying to connect button click action in MainActivity.java to a pendingIntent in my RathuMakara.java Service class.
This is MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button buttonStart;
private Button buttonStop;
public static final String CHANNEL_ID = "exampleServiceChannel";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonStart = (Button) findViewById(R.id.buttonStart);
buttonStop = (Button)findViewById(R.id.buttonSop);
buttonStart.setOnClickListener(this);
buttonStop.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v == buttonStart){
startService(new Intent(this, RathuMakara.class));
buttonStart.setEnabled(false);
buttonStop.setEnabled(true);
Toast.makeText(getApplicationContext(),"Lets's Go... Collecting the Awesomeness",Toast.LENGTH_LONG).show();
}
else if (v == buttonStop){
stopService(new Intent(this, RathuMakara.class));
Toast.makeText(getApplicationContext(),"Playing Stopped",Toast.LENGTH_LONG).show();
buttonStop.setEnabled(false);
buttonStart.setEnabled(true);
}
}
}
This is RathuMakara.java
public class RathuMakara extends Service {
public static Object action;
private MediaPlayer rathu;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public int onStartCommand(Intent intent,int flags , int startID){
String url ="http://206.189.34.189:8000/rathumakara.mp3";
MediaPlayer rathu = new MediaPlayer();
rathu.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
rathu.setDataSource(url);
rathu.prepare();
rathu.start();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Bitmap icon = BitmapFactory.decodeResource(getResources(),
R.drawable.logo);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Rathu Makara FM")
.setContentText("දැන් අහන්නේ")
.setSmallIcon(R.drawable.logo)
.setLargeIcon(icon)
.setOngoing(true)
// .addAction(android.R.drawable.ic_media_play, "Play", )
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
}
catch (IOException e){
e.printStackTrace();
}catch (IllegalArgumentException e){
e.printStackTrace();
}catch (SecurityException e){
e.printStackTrace();
}catch (IllegalStateException e){
e.printStackTrace();
}
return START_NOT_STICKY;
}
#Override
public void onDestroy(){
rathu.stop();
}
}
This is Rathu.java where I created the Notification channel
package com.example.yomal.rathumakarafm;
import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
public class Rathu extends Application {
public static final String CHANNEL_ID = "exampleServiceChannel";
#Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Example Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
}
Please Help Me.Thank you
Set the notification content
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(textTitle)
.setContentText(textContent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
and add action buttons
Intent snoozeIntent = new Intent(this, MyBroadcastReceiver.class);
snoozeIntent.setAction(ACTION_SNOOZE);
snoozeIntent.putExtra(EXTRA_NOTIFICATION_ID, 0);
PendingIntent snoozePendingIntent =
PendingIntent.getBroadcast(this, 0, snoozeIntent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.addAction(R.drawable.ic_snooze, getString(R.string.snooze),
snoozePendingIntent);
I have a simple NanoHTTPD server running as a foreground service.
I am facing issues in updating the notifications with new content when a new request to a server comes in.
The foreground service starts up and the notification shows. No issue there. But can't update them later.
File structure
- Mainactivity
- NanoServer (server implementaion)
- NanoService (foreground service class)
- NotificationProvider (separate class to handle notifications)
NanoServer.java
public Context context = getContext();
public NotificationProvider notificationProvider;
public NanoServer(int port) {
super(8089);
}
#Override
public Response serve(String uri, Method method,
Map<String, String> header, Map<String, String> parameters,
Map<String, String> files) {
String answer = "";
String msg;
// doesnt work with the context. something wrong here I guess????
notificationProvider = new NotificationProvider();
notificationProvider.setNotification(context, "Title", uri, 0);
FileInputStream fis = null;
try {
fis = new FileInputStream(uri);
Log.w(TAG, uri + " found");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return newChunkedResponse(Status.OK, "audio/mpeg", fis);
}
public Context getContext() {
return context;
}
NanoService.java
String TAG = "NANOSERVICE";
public Context context = this;
public Handler handler = null;
public static Runnable runnable = null;
PowerManager powerManager;
PowerManager.WakeLock wakeLock;
WifiManager.WifiLock wifiLock;
private NanoServer nanoServer;
public NotificationProvider notificationProvider;
public NanoService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Start the httpd.
try {
nanoServer = new NanoServer(8089);
nanoServer.start();
Log.d(TAG, "Service with server started");
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Service failed to start.", Toast.LENGTH_LONG).show();
}
// Keep the CPU awake (but not the screen).
powerManager = (PowerManager)getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
wakeLock.acquire();
// Keep the WIFI turned on.
WifiManager wm = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, TAG);
wifiLock.acquire();
notificationProvider = new NotificationProvider();
notificationProvider.setNotification(this, "Title", "Message", 0);
// had to extend notificationprovider with notification
startForeground(1, notificationProvider);
Log.d(TAG, "Foreground service running");
return Service.START_STICKY;
}
#Override
public void onDestroy() {
stopForeground(true);
wakeLock.release();
wifiLock.release();
nanoServer.stop();
}
NotificationProvider.java
public class NotificationProvider extends Notification {
String TAG = "NOTIFICATIONPROVIDER";
public NotificationProvider() {
}
public void setNotification(Context context, String notificationTitle, String notificationMessage, int notificationRequestCode){
NotificationCompat.Builder builder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle(notificationTitle)
.setContentText(notificationMessage)
.setTicker("My service")
.setColor(101)
.setWhen(System.currentTimeMillis())
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_MAX);
Intent intent = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, notificationRequestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
Log.d(TAG, "Got new Notification");
}
}
I think the easiest solution will be using the same builder method for updating the notification.
Use this updated NotificationProvider.
Change new NotificationProvider() to NotificationProvider.getInstance() in NanoService (or anywhere else).
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.iroid.videoeditor.R;
import com.iroid.videoeditor.main.MainActivity;
public class NotificationProvider extends Notification {
private static NotificationProvider sInstance;
private NotificationCompat.Builder mBuilder;
private String TAG = "NOTIFICATIONPROVIDER";
public static NotificationProvider getInstance() {
if (sInstance == null)
sInstance = new NotificationProvider();
return sInstance;
}
// Prevent creating new instances from outside
private NotificationProvider() {
}
public void setNotification(Context context, String notificationTitle, String
notificationMessage, int notificationRequestCode) {
NotificationManager manager = (NotificationManager) context.getSystemService(Context
.NOTIFICATION_SERVICE);
if (mBuilder == null) {
// Notification doesn't exists. Need to create one.
mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle(notificationTitle)
.setContentText(notificationMessage)
.setTicker("My service")
.setColor(101)
.setWhen(System.currentTimeMillis())
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_MAX);
Intent intent = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context,
notificationRequestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(contentIntent);
manager.notify(0, mBuilder.build());
Log.d(TAG, "Got new Notification");
} else {
// Notification exists. Simply update
}
}
}
The problem is most likely to be with your Notification ID, which must be unique within your application if you later want to update it.
manager.notify(0, builder.build());
Change it to a non-zero constant
private static final int NOTE_ID = 2794; //chosen arbitrarily
manager.notify(NOTE_ID, builder.build());
However you should also not hold (leak) a context, instead get the app context (or service context) when you use it.
To be able to get an Application Context at any time, implement an application class (and register it in the manifest)
public class MyApplication extends Application {
public static Context appContext() {
return this;
}
}
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="...">
<!-- The name here should match whatever you called your application class -->
<application android:name=".MyApplication"
...>
...
</application>
</manifest>
My Application is asking me to create a method for getResources() or getApplicationContext().
Are these methods not allowed to be called in a BroadcastReceiver?
#Override
public void onReceive(Context context, Intent arg1) {
createNotification(Calendar.getInstance().getTimeInMillis());
}
public void createNotification(long when) {
Bitmap largeIcon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.stamptwo);
int smalIcon = R.drawable.stamptwoxhdpi;
Intent intent = new Intent(context.getApplicationContext(),
Lockscreen.class);
intent.putExtra(NOTIFICATION_DATA, notificationData);
intent.setData(Uri.parse("content://" + when));
PendingIntent pendingIntent = PendingIntent.getActivity(
context.getApplicationContext(), 0, intent,
Intent.FLAG_ACTIVITY_NEW_TASK);
NotificationManager notificationManager = (NotificationManager) context
.getApplicationContext().getSystemService(
Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
context.getApplicationContext())
.setWhen(when)
.setContentText(notificationContent)
.setContentTitle(notificationTitle)
.setSmallIcon(smalIcon)
.setAutoCancel(true)
.setTicker(notificationTitle)
.setLargeIcon(largeIcon)
.setDefaults(
Notification.DEFAULT_LIGHTS
| Notification.DEFAULT_VIBRATE
| Notification.DEFAULT_SOUND)
.setContentIntent(pendingIntent);
Notification notification = notificationBuilder.build();
notificationManager.notify((int) when, notification);
}
}
Another alternative to #Pankaj Kumar solution is to store the concept as a data field inside the onReceive method :
public class MyReceiver extends BroadcastReceiver {
private Context context;
#Override
public void onReceive(Context context, Intent arg1) {
this.context = context;
createNotification(Calendar.getInstance().getTimeInMillis());
}
public void createNotification(long when) {
// and use
// context.getApplicationContext()
}
}
You will need to use context.getResources() or context.getApplicationContext() so pass the context to createNotification method.
Try this
public class NotificationAlarm extends BroadcastReceiver {
public static final String NOTIFICATION_DATA = "NOTIFICATION_DATA";
String notificationData = "";
String notificationContent = "Content";
String notificationTitle = "Title";
#Override
public void onReceive(Context context, Intent arg1) {
createNotification(context,Calendar.getInstance().getTimeInMillis());
}
public void createNotification(Context mContext,long when) {
Bitmap largeIcon = BitmapFactory.decodeResource(mContext.getResources(),
R.drawable.stamptwo);
int smalIcon = R.drawable.stamptwoxhdpi;
Intent intent = new Intent(mContext, Lockscreen.class);
intent.putExtra(NOTIFICATION_DATA, notificationData);
intent.setData(Uri.parse("content://" + when));
PendingIntent pendingIntent = PendingIntent.getActivity(
mContext, 0, intent,
Intent.FLAG_ACTIVITY_NEW_TASK);
NotificationManager notificationManager = (NotificationManager) mContext
.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
mContext)
.setWhen(when)
.setContentText(notificationContent)
.setContentTitle(notificationTitle)
.setSmallIcon(smalIcon)
.setAutoCancel(true)
.setTicker(notificationTitle)
.setLargeIcon(largeIcon)
.setDefaults(
Notification.DEFAULT_LIGHTS
| Notification.DEFAULT_VIBRATE
| Notification.DEFAULT_SOUND)
.setContentIntent(pendingIntent);
Notification notification = notificationBuilder.build();
notificationManager.notify((int) when, notification);
}
}