How to display Song Name And Artist Name In Notification Bar - java

I have created a stream music player that streams the song from Firebase. Now I have created a custom Notification to display song details on notification bar. The song Detail should display Inside the app, but does not display the detail to the notification bar. And how i can put action to play , stop the music . Can any one tell me how I can fix my existing solution.
Here is my code for notification bar.
public class NotificationService extends Service {
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals(NConstants.ACTION.STARTFOREGROUND_ACTION)) {
showNotification();
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
} else if (intent.getAction().equals(NConstants.ACTION.PREV_ACTION)) {
Toast.makeText(this, "Clicked Previous", Toast.LENGTH_SHORT).show();
Log.i(LOG_TAG, "Clicked Previous");
} else if (intent.getAction().equals(NConstants.ACTION.PLAY_ACTION)) {
Toast.makeText(this, "Clicked Play", Toast.LENGTH_SHORT).show();
Log.i(LOG_TAG, "Clicked Play");
} else if (intent.getAction().equals(NConstants.ACTION.NEXT_ACTION)) {
Toast.makeText(this, "Clicked Next", Toast.LENGTH_SHORT).show();
Log.i(LOG_TAG, "Clicked Next");
} else if (intent.getAction().equals(
NConstants.ACTION.STOPFOREGROUND_ACTION)) {
Log.i(LOG_TAG, "Received Stop Foreground Intent");
// Toast.makeText(this, "Service Stoped", Toast.LENGTH_SHORT).show();
stopForeground(true);
stopSelf();
}
return START_STICKY;
}
Notification status;
private final String LOG_TAG = "NotificationService";
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
private void showNotification() {
// Using RemoteViews to bind custom layouts into Notification
RemoteViews views = new RemoteViews(getPackageName(),
R.layout.status_bar);
RemoteViews bigViews = new RemoteViews(getPackageName(),
R.layout.status_bar_expanded);
// showing default album image
views.setViewVisibility(R.id.status_bar_icon, View.VISIBLE);
views.setViewVisibility(R.id.status_bar_album_art, View.GONE);
bigViews.setImageViewBitmap(R.id.status_bar_album_art,
NConstants.getDefaultAlbumArt(this));
Intent notificationIntent = new Intent(this, ViewUploadsActivity.class);
notificationIntent.setAction(NConstants.ACTION.MAIN_ACTION);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Intent previousIntent = new Intent(this, NotificationService.class);
previousIntent.setAction(NConstants.ACTION.PREV_ACTION);
PendingIntent ppreviousIntent = PendingIntent.getService(this, 0,
previousIntent, 0);
Intent playIntent = new Intent(this, NotificationService.class);
playIntent.setAction(NConstants.ACTION.PLAY_ACTION);
PendingIntent pplayIntent = PendingIntent.getService(this, 0,
playIntent, 0);
Intent nextIntent = new Intent(this, NotificationService.class);
nextIntent.setAction(NConstants.ACTION.NEXT_ACTION);
PendingIntent pnextIntent = PendingIntent.getService(this, 0,
nextIntent, 0);
Intent closeIntent = new Intent(this, NotificationService.class);
closeIntent.setAction(NConstants.ACTION.STOPFOREGROUND_ACTION);
PendingIntent pcloseIntent = PendingIntent.getService(this, 0,
closeIntent, 0);
views.setOnClickPendingIntent(R.id.status_bar_play, pplayIntent);
bigViews.setOnClickPendingIntent(R.id.status_bar_play, pplayIntent);
views.setOnClickPendingIntent(R.id.status_bar_next, pnextIntent);
bigViews.setOnClickPendingIntent(R.id.status_bar_next, pnextIntent);
views.setOnClickPendingIntent(R.id.status_bar_prev, ppreviousIntent);
bigViews.setOnClickPendingIntent(R.id.status_bar_prev, ppreviousIntent);
views.setOnClickPendingIntent(R.id.status_bar_collapse, pcloseIntent);
bigViews.setOnClickPendingIntent(R.id.status_bar_collapse, pcloseIntent);
views.setImageViewResource(R.id.status_bar_play,
R.drawable.ic_pause);
bigViews.setImageViewResource(R.id.status_bar_play,
R.drawable.ic_play);
views.setTextViewText(R.id.status_bar_track_name,"Name"); // How i can
displpay the song name here
bigViews.setTextViewText(R.id.status_bar_track_name,"Name");
views.setTextViewText(R.id.status_bar_artist_name, "Artist");
bigViews.setTextViewText(R.id.status_bar_artist_name,"Artist");
status = new Notification.Builder(this).build();
status.contentView = views;
status.bigContentView = bigViews;
status.flags = Notification.FLAG_ONGOING_EVENT;
status.icon = R.drawable.images;
status.contentIntent = pendingIntent;
startForeground(NConstants.NOTIFICATION_ID.FOREGROUND_SERVICE, status);
}
}
here is my that Class that fetch the song url and detail
This is a another class that fetch the data.
public void get()
{
seekBarProgress.setMax(99); // It means 100% .0-99
seekBarProgress.setOnTouchListener(this);
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#SuppressLint("RestrictedApi")
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//getting the upload
Upload upload = uploadList.get(i);
mSelectedTrackTitle.setText(upload.getName());
selected_track_ar.setText(upload.getAr());
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
mMediaPlayer.reset();
seekBarProgress.setProgress(0);
}
try {
mMediaPlayer.setDataSource(upload.getUrl());
mMediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if(v.getId() == R.id.length){
/** Seekbar onTouch event handler. Method which seeks MediaPlayer to seekBar primary progress position*/
if(mMediaPlayer.isPlaying()){
SeekBar sb = (SeekBar)v;
int playPositionInMillisecconds = (mediaFileLengthInMilliseconds / 100) * sb.getProgress();
mMediaPlayer.seekTo(playPositionInMillisecconds);
}
}
return false;
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
seekBarProgress.setSecondaryProgress(percent);
}
#Override
public void onCompletion(MediaPlayer mp) {
}
As You see the song detail should be display inside the app but does not display in the notification bar:

What you need to do is, when you are setting the custom view to your notification you need to populate the data at the same time, like this.
RemoteViews customView = new RemoteViews(getPackageName(), R.layout.custom_layout);
customView.setTextViewText(R.id.track_name, "My fav music");
customView.setTextViewText(R.id.artist_name, "My fav artist");
Notification notification = new NotificationCompat.Builder(this).setContent(customView).allOtherMethods().build();
notificationManager.notify(1, notification);

Related

How to use JobIntentService for android +9, I want to do that listen screen if screen on app run

I try to app runs in background and service listens if screen on app launch on lock screen, we can do android 9 and 9- but we cant achieve android 9+, We use JobIntentService for android 9+ it runs sometimes how can we do that??
YourService.java extend JobIntentService
public class YourService extends JobIntentService {
public static final int JOB_ID = 1;
public static void enqueueWork(Context context, Intent work) {
enqueueWork(context, YourService.class, JOB_ID, work);
}
#Override
protected void onHandleWork(#NonNull Intent intent) {
Log.e("çalıştı","çalıştı job");
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Haydi Kurtuluşa")
//.setContentText(input)
.setSmallIcon(R.drawable.more)
.setContentIntent(pendingIntent)
.setNumber(0)
.build();
Log.e("Myservice","myservice jobbbbb");
startForeground(1, notification);
}
}
MyReceiver.java
public class MyReceiver extends BroadcastReceiver {
public static boolean wasScreenOn = true;
//#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onReceive(Context context, Intent intent) {
Log.e("ekran", "açıldı");
if(intent.getAction().equals("android.intent.action.SCREEN_ON") ){
wasScreenOn = true;
Log.e("evet screen on","evet screen on");
Intent i = new Intent(context, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent =
PendingIntent.getActivity(context, 0, i, 0);
try {
pendingIntent.send();
Log.e("pendingIntent","pendingIntent");
} catch (PendingIntent.CanceledException e) {
e.printStackTrace();
Log.e("printStackTrace","printStackTrace");
}
}
Intent startServiceIntent = new Intent(context, MyService.class);
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O) {
context.startForegroundService(startServiceIntent);
Log.e("Myservice","myservice receicer en alt");
}
else {
context.startService(startServiceIntent);
Log.e("Myservice","myservice receicer en dahaaaa alt");
}
YourService.enqueueWork(context, new Intent());
}
}
MyService.java
public class MyService extends Service {
MainActivity mainActivity = new MainActivity();
MyReceiver myReceiver = new MyReceiver();
public MyService() {
}
#Override
public void onCreate() {
super.onCreate();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
// do your jobs here
// startForeground();
//return super.onStartCommand(intent, flags, startId);
String input = intent.getStringExtra("inputExtra");
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Haydi Kurtuluşa")
//.setContentText(input)
.setSmallIcon(R.drawable.more)
.setContentIntent(pendingIntent)
.setNumber(0) // bildirim simgesinin 1 diye gösterilip gösterilmemesini sağlar
.build();
Log.e("Myservice","myservice onstartcommand");
startForeground(1, notification);
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
Log.e("service destroy","service destroy");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("ilkk", true);
editor.commit();
super.onDestroy();
}
}
This code is in MainActivity
final Window win= getWindow();
win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
// win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
setTurnScreenOn(true);
setShowWhenLocked(true);
}
// REVEIRVER
// bu dinliyor eğer ekran açılırsa tak MyReceiver classa gönderiyor.
IntentFilter screenStateFilter = new IntentFilter();
screenStateFilter.addAction(Intent.ACTION_SCREEN_ON);
screenStateFilter.addAction(Intent.ACTION_SCREEN_OFF);
myReceiver =new MyReceiver();
registerReceiver(myReceiver,screenStateFilter);
Log.e("geldi3","geldi3");
Log.e("burada ","geldi");

Action button on Notification if not clicked on certain time will do something else

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.

Android send data to broadcast receiver

I am creating an Android app that notify the users when they received a SMS from selected numbers using Foreground Service. The program only notify the user when the Service is running. My Main Activity has 3 buttons: Start Service, Stop Service and Setting which lead to another Activity that let the user change their information such as password and selected number. Currently the application can read and write data to JSON fine and the data get pass to other activities through Intent, also the Broadcast Receiver for detecting SMS also work when a message in received, and since I want it to work with Foreground Service, I register it in onStartCommand and unregister it in onDestroy in the Service and not register it in Manifest. My problem is on how to pass the user data to the Broadcast Receiver, since it is register to listen to android.provider.Telephony.SMS_RECEIVED and when I try to pass Intent to it through sentBroadcast() in my Service, it does not receive any value of the user. I tried to settle in making the user public static and it worked, but not sure if this the right way to do it. Here is my current code:
MainActivity.java
Button btnStartService, btnStopService;
TextView lblStatus;
JSONHandler jsonHandler;//for handling JSON file and data
public static User user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStartService = findViewById(R.id.buttonStartService);
btnStopService = findViewById(R.id.buttonStopService);
jsonHandler = new JSONHandler(this);
boolean isFilePresent = isFilePresent(this, "user.json");
if(isFilePresent) {
try {
user = jsonHandler.readFromFile();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
user = new User();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestSmsPermission();
requestPermissions(new String[]{WRITE_EXTERNAL_STORAGE,READ_EXTERNAL_STORAGE}, 1);
}
else {
startService();
}
}
public boolean isFilePresent(Context context, String fileName) {
String path = context.getFilesDir().getAbsolutePath() + "/" + fileName;
File file = new File(path);
return file.exists();
}
public void setBtnStartService(View view)
{
startService();
}
public void setBtnStopService(View view)
{
stopService();
}
public void startService() {
Intent serviceIntent = new Intent(this, ForegroundService.class);
serviceIntent.putExtra("inputExtra", "Message Service is running");
serviceIntent.putExtra("user", user);
ContextCompat.startForegroundService(this, serviceIntent);
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
}
public void stopService() {
Intent serviceIntent = new Intent(this, ForegroundService.class);
stopService(serviceIntent);
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
public void setBtnSetting(View view) {
Intent intent = new Intent(this, AuthenticateActivity.class);
intent.putExtra("user", user);
intent.putExtra("action", "setting");
startActivity(intent);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
startService();
}
}
private void requestSmsPermission() {
String permission = Manifest.permission.RECEIVE_SMS;
int grant = ContextCompat.checkSelfPermission(this, permission);
if ( grant != PackageManager.PERMISSION_GRANTED) {
String[] permission_list = new String[1];
permission_list[0] = permission;
ActivityCompat.requestPermissions(this, permission_list, 1);
}
}
ForegroundService.java
public class ForegroundService extends Service {
public static final String CHANNEL_ID = "ForegroundServiceChannel";
SMSReceiver smsListener;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("inputExtra");
User user = (User) intent.getSerializableExtra("user");
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service")
.setContentText(input)
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
//do heavy work on a background thread
if(smsListener == null)
{
smsListener = new SMSReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
Intent i = new Intent(this, SMSReceiver.class);
i.putExtra("user", user);
sendBroadcast(i);
registerReceiver(smsListener, intentFilter);
}
//stopSelf();
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
if(null!=smsListener)
{
unregisterReceiver(smsListener);
smsListener = null;
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
}
SMSReceiver.java
public class SMSReceiver extends BroadcastReceiver {
private String msgBody;
private String text = "";
private SharedPreferences preferences;
private String sender = "";
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// User user = (User) intent.getExtras().getSerializable("user"); not working
User user = MainActivity.user;
ArrayList<String> banks = user.getBankList();
if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
Toast.makeText(context, "message received", Toast.LENGTH_SHORT).show();
Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage smsMessage;
for (int i = 0; i < pdus.length; i++) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
smsMessage = SmsMessage.createFromPdu((byte[]) pdus[i], bundle.getString("format"));
else smsMessage = SmsMessage.createFromPdu((byte[]) pdus[i]);
msgBody = smsMessage.getMessageBody();
sender = smsMessage.getOriginatingAddress();
if(banks.contains(sender)) {
if (msgBody.contains(user.getPattern())) {
String[] tokens = msgBody.split(" ");
for (int j = 0; j < tokens.length; j++) {
if (tokens[j].contains("API")) {
text = tokens[j];
break;
}
}
}
}
}
//MainActivity.message = msgBody;
if(!text.isEmpty()) {
Toast.makeText(context, "message is: " + text, Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
Log.d("Exception caught", e.getMessage());
}
}
else {
Log.i("cs.fsu", "smsReceiver : NULL");
}
}
}
Is this the right way to maintain user data throughout the application lifecycle? By making public static for every class accessible? Or is there away to pass it through Intent? Please help me out

How to send notification with background service in Android Studio?

I want to send push notifications in my app but after few minutes android kill my background service and notifications not showing. How to make background service which android will not close?
BackroundService.class
public Context context = this;
public android.os.Handler handler = new Handler();
public static Runnable runnable = null;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Log.e("Service", "Service crated!");
runnable = new Runnable() {
public void run() {
Log.e("Service", "Service is still running!");
Toast.makeText(context, "Service is still running", Toast.LENGTH_SHORT).show();
handler.postDelayed(runnable, 50000);
}
};
handler.postDelayed(runnable, 15000);
}
#Override
public void onDestroy() {
}
#Override
public void onStart(Intent intent, int startid) {
Log.e("Service", "Service started by user!");
}
AlarmReceiver.class
#Override
public void onReceive(Context context, Intent intent) {
int notificationId = intent.getIntExtra("ID", 0);
String message = intent.getStringExtra("TEXT");
String tittle = intent.getStringExtra("TITTLE");
Intent mainIntent = new Intent(context, BackgroundService.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, mainIntent, 0);
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(context);
builder.setSmallIcon(R.drawable.finance43)
.setContentTitle(tittle)
.setContentText(message)
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentIntent(contentIntent)
.setPriority(Notification.PRIORITY_HIGH)
.setCategory(Notification.CATEGORY_MESSAGE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = "REMINDERS";
NotificationChannel channel = new NotificationChannel(channelId,
"Reminder",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
builder.setChannelId(channelId);
}
notificationManager.notify(notificationId, builder.build());
}
When I start app i see "Service is still running!" for about 1 hour.

Can not connect button click action Intent in Main activity to a Pending Intent in Service class to get action in notification using .getAction()

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);

Categories