I am working on an app that reminds the user of an event at a particular date and time. I am having problem using the broadcast receiver. Suppose the user clicks on item 0, then position of the item is 0. I check if the position does equal to 0, then set the specific date and time for the notification. Then receiver class will call the message class to show the message. Based on my code, the receiver method should show three different notification because each has a different id but this is not happening. Only the first notification is shown.
In MyReceiver I want to have the position variable from arrayadapter that keeps tracks of what item was clicked. But I am not able to do that (at onItemClick)
I have more than 94 events, and I don't want to have 94 Broadcast receiver classes to show me the notification for each event. Is THERE ANY WAY I CAN USE ONE RECEIVER CLASS TO SHOW ALL THE NOTIFICATIONS.
I tested it out by having separate Broadcast receiver class for each event and it worked fine.
This is what I did:
1.I created three different receiver classes
2.In the message class, I have methods for each notification
3. and in each receiver class I called the specific method like this
Message nm = new Message();
nm.generateNotification(context);
and the main class I did this:
Intent myInten2t = new Intent(BuddhaEvent.this, MyReceiver.class);
MyReceiver in this case is one of the three receiver classes I implemented.
Could someone please tell me how I can say that if(position ==0) show this notification and so on.
This is my Main class.
public class BuddhaEvent extends AppCompatActivity implements View.OnClickListener {
public List<list> myList = new ArrayList<list>();
private PendingIntent pendingIntent;
android.support.v4.app.NotificationCompat.Builder notification;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_buddhism_event);
fill_eventsList();
fill_ListView();
clickResponse();
Button buddah_button_event = (Button) findViewById(R.id.button_event_back_buddhism);
buddah_button_event.setOnClickListener(this);
}
// public list(String date, int iconId, String details, String name) {
private void fill_eventsList() {
myList.add(new list("Jan-24", R.drawable.chris, "Mahayana countries the new year starts on the first full moon day in January.", "Mahayana New Year"));
myList.add(new list("Feb-2", R.drawable.chris, "Chinese festival celebrated at the turn of the traditional lunisolar Chinese calendar.", "Chinese New Year"));
myList.add(new list("Feb-15", R.drawable.chris, "Celebrates the day when the Buddha is said to have achieved Parinirvana, or complete Nirvana", "Nirvana Day"));
myList.add(new list("Mar-23", R.drawable.chris, "Celebration in honour of the Sangha, or the Buddhist community", "Magha Puja Day"));
myList.add(new list("Apr-22", R.drawable.chris, "Buddhist New Year", "Theravada New Year"));
myList.add(new list("May-15", R.drawable.chris, "Celebrates the Buddha's birthday", "Wesak - Buddha Day"));
myList.add(new list("Jul-11", R.drawable.chris, "Honor the spirits of one's ancestors.", "Obon"));
myList.add(new list("Jul-19", R.drawable.chris, "Celebrates Buddha's teachings of peace and enlightenment", "Asala - Dharma Day"));
myList.add(new list("Dec-8", R.drawable.chris, "The day that the historical Buddha, Siddhartha Gautama (Shakyamuni), experienced enlightenment", "Bodhi Day"));
}
private void fill_ListView() {
ArrayAdapter<list> listArrayAdapter = new myListAdapter();
ListView list = (ListView) findViewById(R.id.list_eventsView);
list.setAdapter(listArrayAdapter);
}
public void clickResponse() {
ListView l = (ListView) findViewById(R.id.list_eventsView);
if (l != null) {
l.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View viewClicked,
final int position, long id) {
AlertDialog.Builder alert = new AlertDialog.Builder(
BuddhaEvent.this);
alert.setTitle("Reminder!!");
alert.setMessage("Do you want to be reminded of this event in future?");
alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (position == 0) {
Calendar calendar = Calendar.getInstance();
MyReceiver mr= new MyReceiver();
calendar.set(Calendar.MONTH, 6);
calendar.set(Calendar.YEAR, 2016);
calendar.set(Calendar.DAY_OF_MONTH, 18);
calendar.set(Calendar.HOUR_OF_DAY, 15);
calendar.set(Calendar.MINUTE, 50);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM, Calendar.PM);
Intent myIntent = new Intent(BuddhaEvent.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(BuddhaEvent.this, 45454, myIntent, 0);
AlarmManager alarmManager2 = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager2.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
}
if (position == 1) {
Calendar calendar2 = Calendar.getInstance();
MyReceiver mr= new MyReceiver();
calendar2.set(Calendar.MONTH, 6);
calendar2.set(Calendar.YEAR, 2016);
calendar2.set(Calendar.DAY_OF_MONTH, 18);
calendar2.set(Calendar.HOUR_OF_DAY, 15);
calendar2.set(Calendar.MINUTE, 51);
calendar2.set(Calendar.SECOND, 0);
calendar2.set(Calendar.AM_PM, Calendar.PM);
Intent myInten2t = new Intent(BuddhaEvent.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(BuddhaEvent.this, 12322, myInten2t, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar2.getTimeInMillis(), pendingIntent);
}
if (position == 2) {
counter++;
Calendar calendar2 = Calendar.getInstance();
MyReceiver mr= new MyReceiver();
calendar2.set(Calendar.MONTH, 6);
calendar2.set(Calendar.YEAR, 2016);
calendar2.set(Calendar.DAY_OF_MONTH, 18);
calendar2.set(Calendar.HOUR_OF_DAY, 15);
calendar2.set(Calendar.MINUTE, 52);
calendar2.set(Calendar.SECOND, 0);
calendar2.set(Calendar.AM_PM, Calendar.PM);
Intent myInten2t = new Intent(BuddhaEvent.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(BuddhaEvent.this, 12322, myInten2t, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar2.getTimeInMillis(), pendingIntent);
}
dialog.dismiss();
}
});
alert.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
}
});
}
}
private class myListAdapter extends ArrayAdapter<list> {
public myListAdapter() {
// what objects are going in there and how are they going to look
super(BuddhaEvent.this, R.layout.custom_events_layout, myList);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if (itemView == null) {
itemView = getLayoutInflater().inflate(R.layout.custom_events_layout, parent, false);
}
list current_list = myList.get(position);
ImageView imageView = (ImageView) itemView.findViewById(R.id.id_image);
imageView.setImageResource(current_list.getIconId());
TextView titleTxt = (TextView) itemView.findViewById(R.id.id_event);
titleTxt.setText(current_list.getName());
EditText text = (EditText) itemView.findViewById(R.id.id_desp);
text.setText(current_list.getDetails());
TextView date = (TextView) itemView.findViewById(R.id.id_date);
date.setText(current_list.getDate());
return itemView;
}
}
public void onClick(View v) {
startActivity(new Intent(BuddhaEvent.this, BuddhaScreen.class));
}
}
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
/*Intent service1 = new Intent(context, MyAlarmService.class);
context.startService(service1);*/
BuddhaEvent check = new BuddhaEvent();
Log.i("App", "called receiver method");
try {
Message nm = new Message();
nm.generateNotification(context);
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is my message class
public class Message {
#SuppressWarnings("static-access")
public void generateNotification(Context context) {
Intent intent = new Intent(context, BuddhaNow.class);
NotificationCompat.Builder notification;
notification = new NotificationCompat.Builder(context);
notification.setAutoCancel(true);
notification.setSmallIcon(R.drawable.ic_launcher);
notification.setTicker("This is the ticker");
notification.setWhen(System.currentTimeMillis());
notification.setContentTitle("Title");
notification.setContentText("Hello this is the description");
PendingIntent pendingIntent = PendingIntent.getActivity(context,1, intent, 0);
notification.setContentIntent(pendingIntent);
NotificationManager nm1 = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nm1.notify(1, notification.build());
}
public void generateNotification2(Context context) {
Intent intent2 = new Intent(context, BuddhaNow.class);
NotificationCompat.Builder notification2;
notification2 = new NotificationCompat.Builder(context);
notification2.setAutoCancel(true);
notification2.setSmallIcon(R.drawable.ic_launcher);
notification2.setTicker("This is the ticker2");
notification2.setWhen(System.currentTimeMillis());
notification2.setContentTitle("second title");
notification2.setContentText("I am the body");
PendingIntent pendingIntent2 = PendingIntent.getActivity(context,2, intent2, 0);
notification2.setContentIntent(pendingIntent2);
NotificationManager nm2 = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nm2.notify(2, notification2.build());
}
public void generateNotification3(Context context) {
Intent intent2 = new Intent(context, BuddhaNow.class);
NotificationCompat.Builder notification2;
notification2 = new NotificationCompat.Builder(context);
notification2.setAutoCancel(true);
notification2.setSmallIcon(R.drawable.ic_launcher);
notification2.setTicker("This is the ticker3");
notification2.setWhen(System.currentTimeMillis());
notification2.setContentTitle("third title");
notification2.setContentText("I am the body");
PendingIntent pendingIntent2 = PendingIntent.getActivity(context,3, intent2, 0);
notification2.setContentIntent(pendingIntent2);
NotificationManager nm2 = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nm2.notify(3, notification2.build());
}
}
Related
I'm trying 1 month now to make a feature witch sends to the user one notification daily at the time the user has selected but when the onTimeSet() called i'm getting only this error below and the Notification is not coming to the user
I try these solutions below:
removing all code from onTimeSet() & startAlarm() inside my activity
changing this to SetNotificationActivity.this
Invalidate chaches / restart
Error:
E/InputDispatcher: Window handle Window{838da5a u0 com.george.igrow/com.george.igrow.SetNotificationActivity} has no registered input channel
SetNotificationActivity.java:
public class SetNotificationActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_notification);
final Button setAlarm = findViewById(R.id.buttonAlarm);
final Button skip_btn = findViewById(R.id.button4);
setAlarm.setOnClickListener(v -> {
DialogFragment timePicker = new TimePickerFragment();
timePicker.show(getSupportFragmentManager(), "time picker");
});
skip_btn.setOnClickListener(v -> {
finish();
startActivity(new Intent(SetNotificationActivity.this, HomeActivity.class));
});
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
startAlarm(c);
}
private void startAlarm(Calendar c) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0);
if (c.before(Calendar.getInstance()))
c.add(Calendar.DATE, 1);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
startActivity(new Intent(SetNotificationActivity.this, HomeActivity.class));
}
}
AlertReceiver.java:
public class AlertReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent intent1 = new Intent(context, SplashScreenActivity.class);
intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 100, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
// Send notification for the current Alarm
NotificationHelper notificationHelper = new NotificationHelper(context);
NotificationCompat.Builder nb = notificationHelper.getChannelNotification();
//nb.setContentIntent(pendingIntent);
notificationHelper.getManager().notify(1, nb.build());
}
}
I have an app that if something happens it will pop up a Notification with an action button. if it pressed it will the app running but if not for a certain amount of time it will run another code.
I'm still confused about how to make that
EDIT :
Here is The code I tried
Main Activity.java :
public class MainActivity extends AppCompatActivity {
public NotificationManagerCompat notificationManager;
public TextView mViewLabel;
public ArrayList<Integer> lst = new ArrayList<Integer>();
boolean continueThread = true;
int count =0;
Thread t;
Timer j = new java.util.Timer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
notificationManager = NotificationManagerCompat.from(this);
mViewLabel = (TextView) findViewById(R.id.textChanger);
t = new Thread(){
#Override
public void run() {
if (continueThread) {
while (continueThread) {
lst.add(70);
lst.add(71);
lst.add(72);
lst.add(73);
lst.add(74);
lst.add(75);
try {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
Collections.shuffle(lst);
mViewLabel.setText(String.valueOf(lst.get(count)));
}
});
}catch (InterruptedException e) {
e.printStackTrace();
}
count++;
}
}
}
};
}
public void BtnStart(View view){
t.start();
j.schedule(
new java.util.TimerTask() {
#Override
public void run() {
while(continueThread){
if(lst.get(count) < 80){
sendOnChannel1();
break;
}
count++;
}
}
},
5000
);
}
public void BtnStop(View view){
if(continueThread){
continueThread=false;
mViewLabel.setText("0");
}
}
public void BtnReset(View view){
if(!continueThread){
continueThread=true;
mViewLabel.setText("Click Start To Simulate Heartbeat");
}
}
public void sendOnChannel1() {
String title = "Title";
String message = "Testing";
Intent activityIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this,
0, activityIntent, 0);
Intent broadcastIntent = new Intent(this, NotificationReceiver.class);
broadcastIntent.putExtra("toastMessage", message);
PendingIntent actionIntent = PendingIntent.getBroadcast(this,
0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_one)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setColor(Color.BLUE)
.setContentIntent(contentIntent)
.addAction(R.mipmap.ic_launcher, "Toast", actionIntent)
.build();
notificationManager.notify(1, notification);
}
if something happens it will pop up a Notification with an action button
is on this code
j.schedule(
new java.util.TimerTask() {
#Override
public void run() {
while(continueThread){
if(lst.get(count) < 80){
sendOnChannel1();
break;
}
count++;
}
}
},
5000
);
From your example. You could pass the current time into the intent.
So from your MainActivity.java
public void sendOnChannel1(View v) {
String title = editTextTitle.getText().toString();
String message = editTextMessage.getText().toString();
Intent activityIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this,
0, activityIntent, 0);
Intent broadcastIntent = new Intent(this, NotificationReceiver.class);
broadcastIntent.putExtra("toastMessage", message);
broadcastIntent.putExtra("time", Calendar.getInstance().getTimeInMillis()); //**Add here
PendingIntent actionIntent = PendingIntent.getBroadcast(this,
0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_one)
.setContentTitle(title)
.setContentText(message)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setColor(Color.BLUE)
.setContentIntent(contentIntent)
.setAutoCancel(true)
.setOnlyAlertOnce(true)
.addAction(R.mipmap.ic_launcher, "Toast", actionIntent)
.build();
notificationManager.notify(1, notification);
}
Then when you receive it within the NotificationReceiver.java Compare the date time etc.
public class NotificationReceiver extends BroadcastReceiver {
Integer TEN_MINUETS = 1000 * 60 * 10;
#Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("toastMessage");
long time = intent.getLongExtra("time", -1);
if(time == -1){
Toast.makeText(context, "Example, no time found", Toast.LENGTH_SHORT).show();
}
if(time + TEN_MINUETS < Calendar.getInstance().getTimeInMillis()){
//10 minutes passed do something else
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
return;
}
//10 miuntes not passed do something more?
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
}
Just make sure to check the intent has data etc.
I am trying to set a Alarm. The user selects a time with the time picker and when time comes a Notification shows up. This works perfectly. But the problem is, the User Input the name of the alarm the user wrote doesn't show up. I do NOT get a error message!
https://prnt.sc/mfs5hx
https://prnt.sc/mfs5w2
NotificationHelper.java:
public NotificationCompat.Builder getChannelNotification() {
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View frAl = inflater.inflate(R.layout.fragment_alarm, null);
titelAlarm = frAl.findViewById(R.id.eingUserAlarm);
String nameAlarm = titelAlarm.getText().toString();
return new NotificationCompat.Builder(getApplicationContext(), channelID)
.setContentTitle("Erinnerung")
.setContentText(nameAlarm)
.setSmallIcon(R.drawable.ic_one);
}
The EditText where the user can name the Alarm is inside a Fragment which can be accessed by a Navigation Drawer.
<EditText
android:id="#+id/eingUserAlarm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="180dp"
android:hint="Was wirst du machen?" />
Also the code for the Alarm is inside my Fragment.java.
Fragment.java:
Button buttonTimePicker = fraAla.findViewById(R.id.button_timepicker);
buttonTimePicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment timePicker = new AlarmTimePicker();
timePicker.show(getChildFragmentManager(), "time picker");
}
});
Button buttonCancelAlarm = fraAla.findViewById(R.id.button_cancel);
buttonCancelAlarm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cancelAlarm();
}
});
return fraAla;
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND, 0);
updateTimeText(c);
startAlarm(c);
}
private void updateTimeText(Calendar c) {
String timeText = "Wir erinnern dich um ";
timeText += DateFormat.getTimeInstance(DateFormat.SHORT).format(c.getTime());
mTextView.setText(timeText);
}
private void startAlarm(Calendar c) {
AlarmManager alarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getActivity(), AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), 1, intent, 0);
if (c.before(Calendar.getInstance())) {
c.add(Calendar.DATE, 1);
}
alarmManager.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
}
private void cancelAlarm() {
AlarmManager alarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getActivity(), AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), 1, intent, 0);
alarmManager.cancel(pendingIntent);
mTextView.setText("Wir werden nicht stören!");
}
I want a background service that keeps running always in a background? It is running on some phone but not running on customised OS phones like VIVO, OPPO MIUI etc? Service is Killed on these customised OS phone.
My Code is given below --
public class MyService extends Service
{
private static final String TAG = "MyService";
#Override
public void onStart(Intent intent, int startId)
{
// TODO Auto-generated method stub
super.onStart(intent, startId);
}
#Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
#Override
public void onCreate()
{
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
//call to onTaskRemoved
onTaskRemoved(intent);
//return super.onStartCommand(intent, flags, startId);
Toast.makeText(this, "Service Started!", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onDestroy()
{
super.onDestroy();
int i = 1;
Intent intent = new Intent(this, MyBroadCastReceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 5);
if (alarmManager != null)
{
alarmManager.setRepeating(
AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
60000,
pendingIntent);
}
}
#Override public void onTaskRemoved(Intent rootIntent)
{
Log.e("onTaskRemoved", "Called!");
int i = 1;
Intent intent = new Intent(this, MyBroadCastReceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 5);
if (alarmManager != null)
{
alarmManager.setRepeating(
AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
AlarmManager.INTERVAL_FIFTEEN_MINUTES,
pendingIntent);
}
super.onTaskRemoved(rootIntent);
}}
I have written a Broadcast Receiver that wake ups my service for every second but it is not working. My Broadcast Receiver as follows-
public class MyBroadCastReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Log.e("MyBroadCastReceiver", "onReceive");
//if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction()))
{
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O)
{
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));
Job myJob = dispatcher.newJobBuilder()
.setService(MyJobService.class)
.setTag("myFCMJob")
.build();
dispatcher.mustSchedule(myJob);
}
else
{
Intent service = new Intent(context, MyService.class);
context.startService(service);
}
}
}}
I have started my service using Alarm Manager and have set the Alarm for every 5 seconds, my MainActivity.java file code is as below ---
public class MainActivity extends AppCompatActivity
{
Button btnStopService;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStopService = findViewById(R.id.btnStopService);
//get FirebaseToken
getToken();
//start Service
startService();
//setReceiver();
btnStopService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MyService.class);
stopService(intent);
}
});
}
private void getToken()
{
FirebaseId firebaseId=new FirebaseId();
String token_firebase=firebaseId.getFireBaseToken();
}
private void startService()
{
Intent myIntent = new Intent(this, MyService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
Log.e("TAG", "++++++++++222222++++++++");
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
//Calendar calendar = Calendar.getInstance();
// calendar.setTimeInMillis(System.currentTimeMillis());
//calendar.add(Calendar.SECOND, 10);
Calendar alarmStartTime = Calendar.getInstance();
Calendar now = Calendar.getInstance();
alarmStartTime.set(Calendar.HOUR_OF_DAY, 0);
alarmStartTime.set(Calendar.MINUTE, 0);
alarmStartTime.set(Calendar.SECOND, 5);
if (now.after(alarmStartTime)) {
Log.d("Hey","Added a day");
//alarmStartTime.add(Calendar.DATE, 1);
}
if (alarmManager != null) {
alarmManager.set(
AlarmManager.RTC_WAKEUP,
alarmStartTime.getTimeInMillis(),
pendingIntent);
}
Toast.makeText(this, "Start Alarm", Toast.LENGTH_LONG).show();
}}
Thanks in Advance.
To keep your service and all your application running even if the phone goes into sleep mode, your service has to call startForeground() and show a non dismissable notification.
It is also convenient to acquire a partial WAKE LOCK.
on your onStartCommand()
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, Constants.CHANNEL_NOTIFY_ID)
.setContentTitle("the content title")
.setContentText("the content text")
.setSmallIcon(R.drawable.myicon)
.setOngoing(true);
// you can add other options Builder has
startForeground(1234, mBuilder.build());
I have a problem while passing String to a Service from Activity. What I am trying to do is to pass different Strings each time I call Service. I use Intent (putExtra() method each time). The problem is that each time it shows the first String that I passed. Is there a way to implement that?
Here is my Activity, Broadcast Receiver, Service
public class MainActivity extends Activity implements View.OnClickListener{
private PendingIntent pendingIntent;
private EditText event;
private Button submit, date, time;
private static final int DIALOG_DATE = 1;
private static final int DIALOG_TIME = 2;
private int myYear = 2014;
private int myMonth = 8;
private int myDay = 16;
private int myHour = 6;
private int myMinute = 30;
private List<String> events;
private List<Calendar> dateTimes;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
event = (EditText)findViewById(R.id.event);
submit = (Button)findViewById(R.id.submit);
submit.setOnClickListener(this);
date = (Button)findViewById(R.id.date);
date.setOnClickListener(this);
time = (Button)findViewById(R.id.time);
time.setOnClickListener(this);
events = new ArrayList<String>();
dateTimes = new ArrayList<Calendar>();
//List<Calendar> events = new ArrayList<Calendar>();
}
#Override
protected Dialog onCreateDialog(int id) {
if(id == DIALOG_DATE) {
DatePickerDialog datePickerDialog = new DatePickerDialog(this, myCallBack, myYear, myMonth, myDay);
return datePickerDialog;
}else {
TimePickerDialog timePickerDialog = new TimePickerDialog(this, myCallBack1, myHour, myMinute, true);
return timePickerDialog;
}
}
DatePickerDialog.OnDateSetListener myCallBack = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
myYear = year;
myMonth = month;
myDay = day;
}
};
TimePickerDialog.OnTimeSetListener myCallBack1 = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int hour, int minute) {
myHour = hour;
myMinute = minute;
}
};
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.date:
showDialog(DIALOG_DATE);
break;
case R.id.time:
showDialog(DIALOG_TIME);
break;
case R.id.submit:
String eventS = event.getText().toString();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, myMonth);
calendar.set(Calendar.YEAR, myYear);
calendar.set(Calendar.DAY_OF_MONTH, myDay);
calendar.set(Calendar.HOUR_OF_DAY, myHour);
calendar.set(Calendar.MINUTE, myMinute);
calendar.set(Calendar.SECOND, 0);
// calendar.set(Calendar.AM_PM, Calendar.PM);
Intent myIntent = new Intent(MainActivity.this, BR.class);
myIntent.putExtra("event", eventS);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
event.setText("");
break;
}
}
public class BR extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, MyService.class);
intent.getExtras().getString("event");
myIntent.putExtra("event", intent.getStringExtra("event"));
context.startService(myIntent);
Log.i("myLogs", "BR started");
}
}
public class MyService extends Service {
private NotificationManager mManager;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
#SuppressWarnings("static-access")
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);
String event = intent.getExtras().getString("event");
Notification notification = new Notification(R.drawable.ic_launcher, "This is a test message!", System.currentTimeMillis());
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(this.getApplicationContext(), event, event, pendingNotificationIntent);
mManager.notify(0, notification);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
A service can't be stopped until it's finish. You have to wait that your current service finish to send other data. You can collect all your strings and send them all together or wait until your background service finish