package com.example.twapp.Observer;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.widget.Button;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import com.example.twapp.Notify;
import com.example.twapp.R;
import com.example.twapp.testReceiver;
public class ConcreteObserverA extends AppCompatActivity implements Observer {
NotificationManager notificationManager;
NotificationChannel channel;
Context context = this;
private String observerState;
private ConcreteSubject concreteSubject; // 持有指向 ConcreteSubject 物件的 reference
public ConcreteObserverA(ConcreteSubject concreteSubject) {
this.concreteSubject = concreteSubject;
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void update() {
setContentView(R.layout.activity_notify);
notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
channel=new NotificationChannel("ID","com.example.twapp",NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
Intent intent = new Intent(context,testReceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,1,intent,PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(context);
builder.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("訊息")
.setContentText("跌倒啦~")
.setChannelId("ID");
Notification notification=builder.build();
notificationManager.notify(1,notification);
}
}
I use the Observer pattern to implement notifications, but I have problems when my concreateObserver wants to print notifications.
When I delete this method. Simple print is feasible.Because I can't think of a way. So come to ask everyone android studio master.
Related
I'm trying to make a service that works 24/7 and it's been working until I updated to Android 12. I've checked the new foreground restrictions but still don't understand why it isn't working since I'm starting it from an activity.
ACTIVITY
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class TestActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
startForegroundService(new Intent(TestActivity.this, TestService.class));
}
}
SERVICE
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.media.MediaBrowserCompat;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.media.MediaBrowserServiceCompat;
import java.util.List;
public class TestService extends MediaBrowserServiceCompat {
#Override
public BrowserRoot onGetRoot(#NonNull String clientPackageName, int clientUid, #Nullable Bundle rootHints) { return null; }
#Override
public void onLoadChildren(#NonNull String parentId, #NonNull Result<List<MediaBrowserCompat.MediaItem>> result) { result.sendResult(null); }
#Override
public int onStartCommand(Intent ii, int flags, int startId) {
//CREATE NOTI CHANNEL
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
"test", "Test Notifications",
NotificationManager.IMPORTANCE_HIGH);
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
}
//CREATE NOTI
Notification notification = new NotificationCompat.Builder(this, "test")
.setSmallIcon(R.drawable.icon)
.setContentTitle("title")
.setContentText("test")
.setChannelId("test")
.setOngoing(true)
.setSilent(true)
.build();
//START FOREGROUND
startForeground(101, notification);
return START_STICKY;
}
}
I tried creating a new app with just these lines of code and it works fine so it must be something else making the service close after a minute.
Turns out samsung put my app on deep sleep which caused it to close itself if not used for a minute. Also thanks to the people who took their time to try and help.
Even though you are correct in wanting a foreground Service here, it seems as if you want it to stay alive whenever you app in the background, or not running at all, as you don't intend your app to be running 24/7, do you?
Since it seems as if you're trying to use a MediaBrowserServiceCompat in your example, I would suggest you do so using a companion instance of a MediaSessionCompat in order to have the media session control the lifecycle of your Service on it's own.
Implementing a media Service is not the most straightforward task in Android; they're still trying to fix some of its prevailing issues with the latest release of Android 13. Therefore, I would also suggest you follow this official Android guide if you're attempting to create an audio app with a media foreground Service.
I have been trying to make an alarm application. I have been struggling with making a full screen notification. I finally did manage to do it, but it only works when the app is running in the background.
It also needs to work when you have closed the app. I don't understand what I am supposed to do to achieve this. I know it is possible because my alarm clock app I use every day is able to do this.
Mainactivity.java
package com.example.wekkerapp;
import java.util.Calendar;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import android.app.AlarmManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final String CHANNEL_ID = "my_channel";
static final String FULL_SCREEN_ACTION = "full_screen_action";
static final int NOTIFICATION_ID = 1;
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Alarm";
String description = "Het alarm gaat";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("2", name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = (NotificationManager) getSystemService(this.NOTIFICATION_SERVICE);
notificationManager.createNotificationChannel(channel);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
createNotificationChannel(this);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TimePicker klok = findViewById(R.id.timePicker1);
klok.setIs24HourView(true);
final Button getTimeBtn = findViewById(R.id.getTimeBtn);
final TextView showText = findViewById(R.id.showText);
final AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
getTimeBtn.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View view) {
Intent intent = new Intent(FULL_SCREEN_ACTION, null, getApplicationContext(), WekkerService.class);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
int uur = klok.getHour();
int minuut = klok.getMinute();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, uur);
cal.set(Calendar.MINUTE, minuut);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Toast.makeText(getApplication().getApplicationContext(), "Alarm gaat om " + uur + ":" + minuut,Toast.LENGTH_LONG).show();
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
showText.setText(Integer.toString(uur) + ':' + Integer.toString(minuut));
NotificationManagerCompat.from(getApplicationContext()).cancel(NOTIFICATION_ID);
}
});
}
static void CreateFullScreenNotification(Context context) {
Intent intent = new Intent(context, MainActivity2.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentTitle("Alarm")
.setContentText("Het alarm gaat")
.setPriority(NotificationCompat.PRIORITY_MAX)
.setCategory(NotificationCompat.CATEGORY_ALARM)
.setContentIntent(pendingIntent)
.setFullScreenIntent(pendingIntent, true);
NotificationManagerCompat.from(context).notify(NOTIFICATION_ID, notificationBuilder.build());
}
private static void createNotificationChannel(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
if (notificationManager.getNotificationChannel(CHANNEL_ID) == null) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "channel_name", NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("channel_description");
notificationManager.createNotificationChannel(channel);
}
}
}
}
Wekkerservice.java
package com.example.wekkerapp;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.util.Log;
import androidx.annotation.Nullable;
public class WekkerService extends IntentService {
public static MediaPlayer mediaPlayer;
public WekkerService() {
super("WekkerService");
}
#Override
public void onCreate() {
super.onCreate(); // if you override onCreate(), make sure to call super().
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
Log.d("test", "onHandleIntent: ");
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.alarmpie);
if (MainActivity.FULL_SCREEN_ACTION.equals(intent.getAction()))
mediaPlayer.setLooping(true);
mediaPlayer.start(); // no need to call prepare(); create() does that for you
MainActivity.CreateFullScreenNotification(getApplicationContext());
}
}
Mainactivity2.java
package com.example.wekkerapp;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.NotificationCompat;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
public class MainActivity2 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Button stopbutton = findViewById(R.id.button2);
stopbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
WekkerService.mediaPlayer.stop();
}
});
}
}
I would suggest you use a BroadcastReceiver and then start the service from its onReceive method.
So in your MainActivity's onClick listener you should change the following pending intent
as follows:
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
to
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
and the intent you pass in should launch a BroadcastReceiver.
Immediately after the BroadcastReceiver is launched by the alarm manager, you should start the service from its onReceive method.
Remember that due to the recent changes the OS won't just let you start a service or background service just whenever and however you want!
If the app is closed and you want to start the service, you SHOULD start it as a ForgroundService and show a notification(you have 5 seconds to make this call) otherwise it will throw RemoteServiceException and that's why the code in your service will not run.
I highly encourage you to take a look at this answer:
https://stackoverflow.com/a/56471104/9023032
Here is also another useful answer which might become handy:
https://stackoverflow.com/a/54035247/9023032
This question already has an answer here:
How to play sound when a notification pops up?
(1 answer)
Closed 2 years ago.
I'm developing an app that sends notifications to the user with a message and a sound. There are two switches, 1 to turn on and off the notifications and the second to turn on and off the notification sound. I wrote the code for the notification sound but it doesn't seem to work.
Do you have any idea about how to make the notification sound to play when a notification pops up?
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Switch;
import java.util.Set;
import androidx.annotation.RequiresApi;
import static android.app.PendingIntent.getActivity;
import static android.content.Context.NOTIFICATION_SERVICE;
import static com.example.myevents.R.drawable.notification;
public class Settings extends AppCompatActivity {
Switch simpleswitch1;
Switch simpleswitch2;
private Notification notification;
NotificationManager manager;
Notification myNotication;
boolean enableSound = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
simpleswitch1 = (Switch) findViewById(R.id.simpleswitch1);
simpleswitch2 = (Switch) findViewById(R.id.simpleswitch2);
simpleswitch1.setChecked(false);
simpleswitch2.setChecked(false);
simpleswitch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#TargetApi(Build.VERSION_CODES.O)
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
int notifyID = 1;
String CHANNEL_ID = "my_channel_01";// The id of the channel.
CharSequence name = "channel 1";// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
Intent intent = new Intent(Settings.this, Visitor.class);
intent.putExtra("yourpackage.notifyId", notifyID);
PendingIntent pIntent = PendingIntent.getActivity(Settings.this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
// Create a notification and set the notification channel.
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(Settings.this, CHANNEL_ID);
notificationBuilder.setSmallIcon(R.drawable.notification);
notificationBuilder.setContentTitle("Title");
notificationBuilder.setContentText("New notification");
notificationBuilder.setContentIntent(pIntent);
notificationBuilder.setChannelId(CHANNEL_ID).build();
if (enableSound){
notificationBuilder.setSound(android.provider.Settings.System.DEFAULT_NOTIFICATION_URI);
notificationBuilder.setVibrate(new long[]{1000,100});
}
Notification notification = notificationBuilder.build();
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.createNotificationChannel(mChannel);
// Issue the notification.
mNotificationManager.notify(notifyID , notification);
}
simpleswitch2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
enableSound = isChecked;
}
});
}});}}
UPDATED
Once you have setdefault on a notificationbuilder, it will ignore subsequent calls like setsound and setvibrate.
You have to set sound and vibration in setdefault method always.
if (shouldSound && !shouldVibrate) {
builder.setDefaults(Notification.DEFAULT_SOUND)
.setVibrate(new long[]{0L});
}
if (shouldVibrate && !shouldSound) {
builder.setDefaults(Notification.DEFAULT_VIBRATE)
.setSound(null);
}
if (shouldSound && shouldVibrate) {
builder.setDefaults(Notification.DEFAULT_ALL);
}
For a simple working example of Notifications on all versions, you can consult the following repo https://github.com/usman14/Notification
I have an issue with my app that i cant solve. The app takes the input(reminder) from a user and then sets it as a notification. The user can create as many notifications as he/she likes. I want the user to click the notification and get taken to a new activity(Reminder), so he/she can see the reminder in a TextView. So i have an activity(SetReminder), which let the user put his data in a text editor.Then i save his data in a hashMap. The int is the id of user's string data. Then i have a class (AlarmReceiver) which extends BroacastReceiver and generates the notification.In this class i have an id for each notification,which matches the hashMap's int from the SetReminder activity. That way i was expecting that the user would see the data of each notification.But that's doesn't happen. I have multiple Notifications(i want that), but the user sees the data of the last notification, no matter which notifications selects. I am posting the code from the three activities.
Thanks in advance.
SetReminder.class
package demo.push_not_demo;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.SystemClock;
import android.widget.EditText;
import com.kunzisoft.switchdatetime.SwitchDateTimeDialogFragment;
import java.util.HashMap;
public class SetReminder extends AppCompatActivity {
private SwitchDateTimeDialogFragment dateTimeFragment;
Button b1,b2,b3;
EditText editText;
public static int counter=0;
public static HashMap<Integer,String> hashMap;
private static final String TAG_DATETIME_FRAGMENT = "TAG_DATETIME_FRAGMENT";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.set_reminder);
hashMap= new HashMap<Integer, String>();
b1=(Button) findViewById(R.id.set_date_time);
b2=(Button) findViewById(R.id.cancel);
b3=(Button) findViewById(R.id.save);
b1.setOnTouchListener(touch);
b2.setOnTouchListener(touch);
b3.setOnTouchListener(touch);
editText=(EditText) findViewById(R.id.reminder_edit);
}
View.OnTouchListener touch= new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (v.getId()){
case R.id.set_date_time:
if (event.getAction()==MotionEvent.ACTION_DOWN){
v.getBackground().setColorFilter(0x77000000, PorterDuff.Mode.SRC_ATOP);
v.invalidate();
}
else if (event.getAction()== MotionEvent.ACTION_UP){
v.getBackground().clearColorFilter();
v.invalidate();
// Construct SwitchDateTimePicker
dateTimeFragment = (SwitchDateTimeDialogFragment) getSupportFragmentManager().findFragmentByTag(TAG_DATETIME_FRAGMENT);
if(dateTimeFragment == null) {
dateTimeFragment = SwitchDateTimeDialogFragment.newInstance(
getString(R.string.label_datetime_dialog),
getString(R.string.positive_button_datetime_picker),
getString(R.string.negative_button_datetime_picker)
);
}
dateTimeFragment.show(getSupportFragmentManager(), TAG_DATETIME_FRAGMENT);
}
break;
case R.id.cancel:
if (event.getAction()==MotionEvent.ACTION_DOWN){
v.getBackground().setColorFilter(0x77000000, PorterDuff.Mode.SRC_ATOP);
v.invalidate();
cancelalarm();
}
else if (event.getAction()== MotionEvent.ACTION_UP){
v.getBackground().clearColorFilter();
v.invalidate();
Intent intent = new Intent(SetReminder.this,HomeScreen.class);
startActivity(intent);
}
break;
case R.id.save:
if (event.getAction()==MotionEvent.ACTION_DOWN){
v.getBackground().setColorFilter(0x77000000, PorterDuff.Mode.SRC_ATOP);
v.invalidate();
}
else if (event.getAction()== MotionEvent.ACTION_UP){
v.getBackground().clearColorFilter();
v.invalidate();
counter++;
hashMap.put(counter,editText.getText().toString());
alarmservice();
}
break;
}
return false;
}
};
public void alarmservice(){
Intent intent = new Intent(this,AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(alarmManager.ELAPSED_REALTIME_WAKEUP,SystemClock.elapsedRealtime()+ 5000,pendingIntent);
}
public void cancelalarm(){
Intent intent = new Intent(this,AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
}
}
AlertReceiver.class
package demo.push_not_demo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.widget.EditText;
import java.util.HashMap;
import static android.support.v4.app.NotificationCompat.DEFAULT_SOUND;
import static android.support.v4.app.NotificationCompat.PRIORITY_HIGH;
import static android.support.v4.app.NotificationCompat.VISIBILITY_PUBLIC;
public class AlertReceiver extends BroadcastReceiver {
public static int id=0;
#Override
public void onReceive(Context context, Intent intent) {
id++;
createNotification(context);
}
private void createNotification(Context context) {
NotificationCompat.Builder notification = new NotificationCompat.Builder(context)
.setAutoCancel(true)
.setSmallIcon(R.drawable.offer1)
.setContentTitle("Notification Title")
.setContentText("Tap to see your reminder")
.setPriority(PRIORITY_HIGH)
.setVibrate(new long[] { 50, 1000, 500, 1000, 1000 })
.setDefaults(DEFAULT_SOUND)
.setVisibility(VISIBILITY_PUBLIC);
Intent intent = new Intent(context,Reminder.class);
PendingIntent pendingintent = PendingIntent.getActivity(context,id,intent,PendingIntent.FLAG_ONE_SHOT);
notification.setContentIntent(pendingintent);
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification ntfc = notification.build();
nm.notify(id,ntfc);
}
}
Reminder.class
package demo.push_not_demo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import static demo.push_not_demo.AlertReceiver.id;
import static demo.push_not_demo.SetReminder.hashMap;
public class Reminder extends AppCompatActivity{
TextView txtv;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reminder);
txtv=(TextView) findViewById(R.id.reminder_textView);
txtv.setText(hashMap.get(id));
}
}
dont use static id,in your code id is always 0. you can check it using Log!
use another way for produce different ids.
when you add notification with same id, the new notification will replace with last notification. use random integer for id
I need to create Service in my application for showing notifications. I have the code for service:
package com.bba.droid;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
public class AlertsMonitorService extends Service{
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onStart(Intent intent, int id) {
NotificationManager notifyMngr=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification=new Notification(R.drawable.icon_back, "Downloading...", System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this.getApplicationContext(), 0, null, 0);
notification.setLatestEventInfo(this.getApplicationContext(), "YoutubeDownloader", "The video is downloading...", contentIntent);
notifyMngr.notify(0, notification);
}
}
And I have code for main Activity:
package com.bba.droid;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
public class DroidTestActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent service=new Intent();
service.setClass(this, AlertsMonitorService.class);
this.startService(service);
}
}
But service doesn't create a notification in status bar. Where have I made mistake?
I don't know if this is the only problem, but you are specifying null for the activity in your intent:
PendingIntent contentIntent = PendingIntent.getActivity(this.getApplicationContext(), 0, null, 0);
You want to specify an intent that will launch your activity:
Intent intent = new Intent(this, DroidTestActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this.getApplicationContext(), 0, intent, 0);