How to get notification on Button Click? - java

I want notification on Button Click event in fragment.
I tried a a lot it is not giving me any error but its not showing me notification.
main.java
public class OneTimeTask extends Fragment implements View.OnClickListener {
public OneTimeTask() {
}
;
String addtask, adddetail, adddate;
static final int TIME_DIALOG_ID = 999;
View view;
EditText taskname, taskdetail, taskdate;
Button taskadd;
ProgressDialog mProgressDialog;
SessionManager session;
JSONObject jsonobject;
private DatePickerDialog fromDatePickerDialog;
private DatePickerDialog toDatePickerDialog;
private SimpleDateFormat dateFormatter;
String uid;
Intent intent;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_daily__task, container, false);
getActivity().setTitle("Task");
taskname = (EditText) view.findViewById(R.id.taskname);
taskdetail = (EditText) view.findViewById(R.id.taskdetail);
taskdate = (EditText) view.findViewById(R.id.taskdate);
taskadd = (Button) view.findViewById(R.id.taskaddtask);
GetCurrentGPSLocation gps = new GetCurrentGPSLocation(getActivity());
if (gps.canGetLocation()) {
// \n is for new line
}else {
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
session = new SessionManager(getActivity());
HashMap<String, String> user = session.getUserDetails();
uid = user.get(SessionManager.KEY_ID);
setDateTimeField();
return view;
}
private void setDateTimeField() {
taskadd.setOnClickListener(this);
Calendar newCalendar = Calendar.getInstance();
fromDatePickerDialog = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
taskadd.setText(dateFormatter.format(newDate.getTime()));
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
}
// #Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getActivity().getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onClick(View view) {
if(view == taskadd) {
fromDatePickerDialog.show();
}
taskadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addtask=taskname.getText().toString();
adddetail=taskdetail.getText().toString();
adddate= taskdate.getText().toString();
InsertData();
Notification();
}
});
}
public void Notification() {
// Set Notification Title
String strtitle = getString(R.string.notificationtitle);
// Set Notification Text
String strtext = getString(R.string.notificationtext);
// Open NotificationView Class on Notification Click
/*
FragmentTransaction t = getActivity().getSupportFragmentManager().beginTransaction();
TabFragment mFrag = new TabFragment();
t.replace(com.Weal.sachin.omcom.R.id.framelayout, mFrag);
t.commit();
*/
Intent intent = new Intent(getActivity(), NotificationView.class);
// Send data to NotificationView Class
intent.putExtra("title", strtitle);
intent.putExtra("text", strtext);
// Open NotificationView.java Activity
PendingIntent pIntent = PendingIntent.getActivity(getContext(), 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
//Create Notification using NotificationCompat.Builder
NotificationCompat.Builder builder = new NotificationCompat.Builder(getContext())
// Set Icon
.setSmallIcon(R.drawable.icon)
// Set Ticker Message
.setTicker(getString(R.string.notificationticker))
// Set Title
.setContentTitle(getString(R.string.notificationtitle))
// Set Text
.setContentText(getString(R.string.notificationtext))
// Add an Action Button below Notification
.addAction(R.drawable.ic_audiotrack, "Action Button", pIntent)
// Set PendingIntent into Notification
.setContentIntent(pIntent)
// Dismiss Notification
.setAutoCancel(true);
// Create Notification Manager
// Create Notification Manager
NotificationManager notificationmanager = (NotificationManager) getContext().getSystemService(NOTIFICATION_SERVICE);
// Build Notification with Notification Manager
notificationmanager.notify(0, builder.build());
}
Here my noficationview.class
package com.Weal.sachin.omcom;
/**
* Created by sachin on 1/23/2017.
*/
import android.app.Activity;
import android.app.NotificationManager;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class NotificationView extends Activity {
String title;
String text;
TextView txttitle;
TextView txttext;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notificationview);
// Create Notification Manager
NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Dismiss Notification
notificationmanager.cancel(0);
// Retrive the data from MainActivity.java
Intent i = getIntent();
title = i.getStringExtra("title");
text = i.getStringExtra("text");
// Locate the TextView
txttitle = (TextView) findViewById(R.id.title);
txttext = (TextView) findViewById(R.id.text);
// Set the data into TextView
txttitle.setText(title);
txttext.setText(text);
}
}
I tried this way and this code is not displaying the notification on Button Click...

May be that's because you are trying to add
taskadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addtask=taskname.getText().toString();
adddetail=taskdetail.getText().toString();
adddate= taskdate.getText().toString();
InsertData();
Notification();
}
});
inside onClick() of your fragment. Since you are already inside onClick() you will not be requiring taskadd.setOnClickListener().
Instead replace your onClick() method with this.
if(view == taskadd) {
fromDatePickerDialog.show();
}
addtask=taskname.getText().toString();
adddetail=taskdetail.getText().toString();
adddate= taskdate.getText().toString();
InsertData();
Notification();

try this code to generate small and big notifications
full source code source
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), PushNotificationDemo.class);
final PendingIntent pending = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
NotificationManager notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
Notification n;
switch (v.getId()) {
case R.id.nd_smallnotification:
if (heading.getText().length() <= 0) {
heading.setError("Please provide push notification title");
} else {
heading.setError(null);
heading_text = heading.getText().toString();
n = new NotificationCompat.Builder(this)
.setContentTitle(heading_text)
.setContentText(message.getText().toString())
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pending)
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true)
.setWhen(System.currentTimeMillis())
.addAction(android.R.drawable.ic_menu_manage, "Close", pending)
.build();
n.flags |= Notification.FLAG_AUTO_CANCEL | Intent.FLAG_ACTIVITY_SINGLE_TOP;
notificationManager.notify(0, n);
}
break;
case R.id.nd_bignotification:
if (heading.getText().length() <= 0) {
heading.setError("Please provide push notification title");
} else {
heading.setError(null);
heading_text = heading.getText().toString();
NotificationCompat.InboxStyle nc =
new NotificationCompat.InboxStyle();
nc.setBigContentTitle(heading_text);
String[] text = new String[5];
for (int i = 0; i < 5; i++) {
text[i] = i + ". say hello...";
nc.addLine(text[i]);
}
n = new NotificationCompat.Builder(this)
.setStyle(nc)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pending)
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true)
.setWhen(System.currentTimeMillis())
.build();
n.flags |= Notification.FLAG_AUTO_CANCEL | Intent.FLAG_ACTIVITY_SINGLE_TOP;
notificationManager.notify(100, n);
}
break;
}
}

Init. your onClick inside onCreate():
taskname = (EditText) view.findViewById(R.id.taskname);
taskdetail = (EditText) view.findViewById(R.id.taskdetail);
taskdate = (EditText) view.findViewById(R.id.taskdate);
taskadd = (Button) view.findViewById(R.id.taskaddtask);
taskadd.setOnClickListener(getActivity); //<----here
Use properly onClick, don't init. the view twice:
public void onClick(View view) {
if(view == taskadd) {
fromDatePickerDialog.show(); //use this properly
addtask=taskname.getText().toString();
adddetail=taskdetail.getText().toString();
adddate= taskdate.getText().toString();
InsertData();
Notification();
}
}
Also to get the context of fragment. Remove getContext() from Notification:
Remove this:
getContext();
With this:
getActivity();

Related

How do i keep a window running on the foreground when the app is removed from Recent Tabs

How do I keep a window running in the foreground to continue running even when the app is removed from the recent tabs.
I have a window that gets called when a specific time reaches and covers the entire screen but when I remove the app from recent tabs it dies along with it.
The Window Class
public class Window {
// declaring required variables
private Context context;
private View mView;
private TheFloatingWindowAppsAdapter theFloatingWindowAppsAdapter;
private WindowManager.LayoutParams mParams;
private WindowManager mWindowManager;
private LayoutInflater layoutInflater;
public Window(Context context) {
this.context = context;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// set the layout parameters of the window
mParams = new WindowManager.LayoutParams(
// Shrink the window to wrap the content rather
// than filling the screen
WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT,
// Display it on top of other application windows
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
// Don't let it grab the input focus
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
// Make the underlying application window visible
// through any transparent parts
PixelFormat.TRANSLUCENT);
}
// getting a LayoutInflater
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// inflating the view with the custom layout we created
mView = layoutInflater.inflate(R.layout.theheartlayout, null);
mView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
);
String thepassingDate = new SimpleDateFormat("EEE MMM dd, yyyy", Locale.getDefault()).format(new Date());
TextClock time = mView.findViewById(R.id.hourText);
TextView theDateText = mView.findViewById(R.id.theDateText);
RecyclerView upnext_tasksID = mView.findViewById(R.id.upnext_tasksID);
RecyclerView app_listID = mView.findViewById(R.id.app_listID);
List<AppDetails> appDetailsList = new ArrayList<>();
TheFloatingWindowAppsAdapter theFloatingWindowAppsAdapter = new TheFloatingWindowAppsAdapter(appDetailsList, context);
app_listID.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
app_listID.setLayoutManager(layoutManager);
app_listID.setAdapter(theFloatingWindowAppsAdapter);
theDateText.setText(thepassingDate);
displayItems(appDetailsList, theFloatingWindowAppsAdapter);
// Define the position of the
// window within the screen
mParams.gravity = Gravity.CENTER;
mWindowManager = (WindowManager) context.getSystemService(WINDOW_SERVICE);
}
public void open() {
try {
// check if the view is already
// inflated or present in the window
if (mView.getWindowToken() == null) {
if (mView.getParent() == null) {
mWindowManager.addView(mView, mParams);
}
}
} catch (Exception e) {
Log.d("Error1", e.toString());
}
}
public void close() {
try {
// remove the view from the window
((WindowManager) context.getSystemService(WINDOW_SERVICE)).removeView(mView);
// invalidate the view
mView.invalidate();
// remove all views
((ViewGroup) mView.getParent()).removeAllViews();
// the above steps are necessary when you are adding and removing
// the view simultaneously, it might give some exceptions
} catch (Exception e) {
Log.d("Error2", e.toString());
}
}
private void displayItems(List<AppDetails> appDetailsList, TheFloatingWindowAppsAdapter adapter) {
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Selected Apps")
.child(firebaseUser.getUid());
reference.keepSynced(true);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
appDetailsList.clear();
for (DataSnapshot sn : snapshot.getChildren()) {
AppDetails appDetails = sn.getValue(AppDetails.class);
if (appDetails.getAppid() != null) {
appDetailsList.add(appDetails);
}
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
This is the ForegroundService Class that extends service
public class ForegroundServices extends Service {
public ForegroundServices() {
}
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
super.onCreate();
// create the custom or default notification
// based on the android version
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
startMyOwnForeground();
else
startForeground(1, new Notification());
// create an instance of Window class
// and display the content on screen
Window window = new Window(this);
window.open();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
// for android version >=O we need to create
// custom notification stating
// foreground service is running
#RequiresApi(Build.VERSION_CODES.O)
private void startMyOwnForeground() {
String NOTIFICATION_CHANNEL_ID = "example.permanence";
String channelName = "Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_MIN);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setContentTitle("Service running")
.setContentText("Displaying over other apps")
// this is important, otherwise the notification will show the way
// you want i.e. it will show some default notification
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(2, notification);
}
}
This is how I call it in the MainActivity inside to onCreate() method
startForegroundService(new Intent(this, Foreground.class);

Cant find a way to work with Alarm manager in taskAdapter

My question is simple, I have made a bit of a mess in my TaskAdapter and now I am facing a problem with an onCreate method because I dont have it in my TaskAdapter (obviously).
Now if You could give Me some ideas on how to implement my alarmManager and link the ALARM_SERVICE so the code would work.
Heres my BaseAdapter:
'public class TaskAdapter extends BaseAdapter {
//transfer context
Context context;
//transfer user to use for shared preferences
String userName;
//create a list of tasks.....
List<taskItem> myTasks;
Calendar calendar = Calendar.getInstance();
AlarmManager alarmManager;
PendingIntent pendingIntent;
//constructor, for creating the adapter we need from the user context and userName
public TaskAdapter(Context context, String userName) {
this.context = context;
this.userName = userName;
//go to user shared preferences and fill the list
getData();
notifyDataSetChanged();
}
//how many item to display
#Override
public int getCount() {
//return the myTasks size....
return myTasks.size();
}
//return a specific item by index
#Override
public Object getItem(int i) {
return myTasks.get(i);
}
//return index number
#Override
public long getItemId(int i) {
return 0;
}
//create our view
#Override
public View getView(final int index, final View view, ViewGroup viewGroup) {
//inflate the view inside view object -> viewInflated
final View viewInflated = LayoutInflater.from(context).inflate(R.layout.task_item, null, false);
//set our inflated view behavior
//set pointer for our inflated view
//set pointer for task name....
final TextView txtTaskName = (TextView) viewInflated.findViewById(R.id.taskName);
//set pointer for taskInfo
final TextView txtTaskInfo = (TextView) viewInflated.findViewById(R.id.taskInfo);
//set pointer for task status....
final Switch swTask = (Switch) viewInflated.findViewById(taskDone);
//set task name, by the index of my myTasks collection
txtTaskName.setText(myTasks.get(index).taskName);
//set task info, by index of myTasks collection
txtTaskInfo.setText(myTasks.get(index).taskInfo);
//set task status , switch is getting true/false
swTask.setChecked(myTasks.get(index).taskStatus);
//show date and time dialog
final ImageView dtPicker = (ImageView) viewInflated.findViewById(R.id.imgTime);
dtPicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final AlertDialog.Builder ad = new AlertDialog.Builder(context);
final AlertDialog aDialog = ad.create();
final LinearLayout adLayout = new LinearLayout(context);
adLayout.setOrientation(LinearLayout.VERTICAL);
TextView txtTime = new TextView(context);
txtTime.setText("Choose time");
adLayout.addView(txtTime);
final TimePicker tp = new TimePicker(context);
adLayout.addView(tp);
final DatePicker dp = new DatePicker(context);
tp.setVisibility(View.GONE);
adLayout.addView(dp);
final Button btnNext = new Button(context);
btnNext.setText("Next>");
adLayout.addView(btnNext);
btnNext.setGravity(1);
Button btnCancel = new Button(context);
btnCancel.setText("Cancel");
adLayout.addView(btnCancel);
btnCancel.setGravity(1);
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
aDialog.cancel();
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final int hour = tp.getHour();
final int min = tp.getMinute();
final String myHour = String.valueOf(hour);
final String myMin = String.valueOf(min);
calendar.set(Calendar.MONTH, dp.getMonth());
calendar.set(Calendar.YEAR, dp.getYear());
calendar.set(Calendar.DAY_OF_MONTH, dp.getDayOfMonth());
dp.setVisibility(View.GONE);
tp.setVisibility(View.VISIBLE);
btnNext.setText("Finish");
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calendar.set(Calendar.HOUR_OF_DAY, tp.getHour());
calendar.set(Calendar.MINUTE, tp.getMinute());
Intent my_intent = new Intent(context, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(context, 0, my_intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
if(hour > 12){
String myHour = String.valueOf(hour - 12);
}
if(min < 10)
{
String myMin = "0"+String.valueOf(min);
}
Toast.makeText(context, "Set for- "+myHour+":"+myMin , Toast.LENGTH_LONG).show();
aDialog.cancel();
}
});
}
});
aDialog.setView(adLayout);
aDialog.show();
}
});
//create listener event, when switch is pressed
swTask.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//we using utlShared to update task status
//create instance of utlShared
utlShared myShared = new utlShared(context);
//calling method of task, and giving userName(shared preferences, taskName, taskStatus)
myShared.task(userName, txtTaskName.getText().toString(), txtTaskInfo.getText().toString(), swTask.isChecked());
//we sending a message to the user, and inform him/her about the change
Toast.makeText(context, swTask.isChecked() ? "Task done" : "Task undone", Toast.LENGTH_SHORT).show();
}
});
//return the view with the behavior.....
return viewInflated;
}
private void getData() {
//go to specific shared preferences by user name.....
SharedPreferences taskPref = context.getSharedPreferences(userName, context.MODE_PRIVATE);
//create instance of our myTasks list
myTasks = new ArrayList<>();
//get all tasks from shared preferances
//the shared preferences is by key and value, therefor we will use Map collection
//we know that the key is String, but we don't know what type of value we will get. <K,?>
Map<String, ?> tasks = taskPref.getAll();
// transfer the data from map collection to list collection , single item is like the defination of the tasks <String,?>
//Entry -> record , enterSet -> set of records
for (Map.Entry<String, ?> oneTask : tasks.entrySet()) {
//insert task to list by Key and Value, we check if value is equal to 1, becuase 1=true 0=false
String[] str = oneTask.getValue().toString().split(",");
myTasks.add(new taskItem(str[0], str[1], str[2].equals("1")));
}
}
}'
I cant find a way to start
"alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE)" because I dont really know how to start it in an other way if there is a way.
Any help would be much appreciated!
Here is my AlarmReceiver:
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.e("Didnt start alarm", "Too bad...");
Intent service_intent = new Intent(context, RingtonePlayingService.class);
context.startService(service_intent);
}
}
And here is the RingtoneService:
public class RingtonePlayingService extends Service {
MediaPlayer someMedia;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.i("Local Services", "Received start id "+ startId+": "+intent);
someMedia = MediaPlayer.create(this, R.raw.skyrim);
someMedia.start();
return START_NOT_STICKY;
}
#Override
public void onDestroy()
{
Toast.makeText(this, "On destroy called!", Toast.LENGTH_SHORT).show();
}
}
Cheers.
It looks like your alarmManager field isn't being initialized.
Add this line to your TaskAdapter constructor:
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Also, you can directly call your service, no need for the BroadcastReceiver in the middle:
Intent my_intent = new Intent(context, RingtonePlayingService.class);
pendingIntent = PendingIntent.getService(context, 0, my_intent, PendingIntent.FLAG_UPDATE_CURRENT);
UPDATE
A service should be declared with the service tag in the manifest.
See: https://developer.android.com/guide/topics/manifest/service-element.html
<service android:name=".RingtonePlayingService" android:enabled="true"/>

Send notification to user when new news article appears

I have a news article app that has a gridview of all articles then you can select the full article. I want the user to receive a notification when a new news article has been posted. It just has to be really simple, the app logo and some text 'new article posted!' and then when they click on the notification the app is opened. Here is my code below, i'm not sure what you need to see though so let me know if you need anything else.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private List<NewsRecord> newsListData = new ArrayList<NewsRecord>();
private GridView newsListView;
private NewsListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView newsListView = (GridView) findViewById(R.id.newsFeedList);
adapter = new NewsListAdapter(this, R.layout.adapter_news_list, newsListData, this);
newsListView.setAdapter(adapter);
newsListView.setOnItemClickListener(itemClicked);
nextStart = 0;
updateListData(nextStart, 20);
}
public int nextStart = 0;
public void updateListData(int StartPoint, int count){
String url = "http://www.efstratiou.info/projects/newsfeed/getList.php?start=" + StartPoint + "&count=" + count;
EDANewsApp app = EDANewsApp.getInstance();
JsonArrayRequest jsonRequest = new JsonArrayRequest(url, listener, errorListener);
app.requestQueue.add(jsonRequest);
nextStart +=count;
}
#Override
public boolean onCreateOptionsMenu (Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case R.id.action_about:
Intent intent = new Intent(this, AboutActivity.class);
startActivity(intent);
return true;
case R.id.action_search:
return true;
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
AdapterView.OnItemClickListener itemClicked = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, NewsItemActivity.class);
intent.putExtra("newsItemId", newsListData.get(position).recordId);
startActivity(intent);
}
};
//Listeners
Response.Listener<JSONArray> listener = new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//we successfully received the JSONArray
//Here we will extract the data and use it in our app
//Clear the dataset before loading new data
// newsListData.clear();
//Go through all the JSON objects
for (int i = 0; i < response.length(); i++) {
try {
//Get one JSON object
JSONObject jsonObj = response.getJSONObject(i);
//Put JSON data in a Java object
NewsRecord record = new NewsRecord();
record.recordId = jsonObj.getInt("record_id");
record.title = jsonObj.getString("title");
record.date = jsonObj.getString("date");
record.shortInfo = jsonObj.getString("short_info");
record.imageUrl = jsonObj.getString("image_url");
newsListData.add(record);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
};
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//There was an error in the communication
//We can notify the user about it
}
};
}
I am not 100% sure about when new article is posted.
If I am right, after adapter.notifyDataSetChanged() notify user with notificatoins by below code:
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!");
// Replace ResultActivity.class to your result notification class.
Intent resultIntent = new Intent(this, ResultActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(ResultActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// first element (0) allows you to update the notification later on.
mNotificationManager.notify(0, mBuilder.build());

how to make same instance as new instance to top of the stack when same instance is running in android

Here the group chat activity is running currently. Group chat activity means chat window. in that chat window i retrieved the message from sqlite and showed by list view adpater. Here i am doing group chat for one event when new message is arrived for other event the notification issued. When i click the notification my group chat activity is not executed again even if i passed the intent from other class or activity.
This is my groupchatActivity code
#Override
protected void onStart() {
super.onStart();
if (activeEventMO != null) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("APPSTATUS", 1);
editor.putLong("eventId", activeEventMO.getEventId());
editor.commit();
Log.i("App", "start");
AppActivityStatus.setActivityStarted();
AppActivityStatus.setActivityContext(context);
}
}
#Override
protected void onPause() {
super.onPause();
AppActivityStatus.setActivityStoped();
}
protected void onNewIntent(Intent intent){
super.onNewIntent(intent);
processExtraData();
}
private void processExtraData() {
activeEventMO = (EventMO) getIntent().getParcelableExtra("eventMo");
}
#Override
protected void onResume() {
super.onPause();
AppActivityStatus.setActivityStarted();
}
#Override
protected void onStop() {
super.onStop();
Log.i("App", "stop");
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("APPSTATUS", 2);
editor.commit();
AppActivityStatus.setActivityStoped();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.image_upload, menu);
return true;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final List<ChatMO> chatMOs1 = new ArrayList<>();
setContentView(R.layout.chat_main);
EventMO eventMO = new EventMO();
context = getApplicationContext();
DatabaseHelper dbHelper = new DatabaseHelper(context);
listChatMessageObjectses = chatMOs1;
inputMsg = (EditText) findViewById(R.id.inputMsg);
listViewMessages = (ListView) findViewById(R.id.list_view_messages);
//this activeEventMO is a static object
processExtraData();
// activeEventMO = (EventMO) getIntent().getParcelableExtra("eventMo");
List<ChatMO> chatMOs = dbHelper.getGroupChatMessageForEvent(activeEventMO.getEventId());
//this for loop is for avoiding the notification coz notification also stores groupchat table in sqlite
for (ChatMO chatMO1 : chatMOs) {
chatMO1.getMessage();
chatMO1.getEvent_id();
chatMO1.getFromName();
int messageType = chatMO1.getMessage_type();
chatMO1.getDate();
chatMO1.isSelf();
if (messageType == 0) {
chatMOs1.add(chatMO1);
}
}
adapter = new MessagesListAdapter(context, chatMOs1);
//adapter functionality added for show the previous chat list of event/invite
listViewMessages.setAdapter(adapter);
sharedpreferences = getSharedPreferences(Constants.SHARED_PREFERENCE_NAME, context.MODE_PRIVATE);
// by default first primary user is current user in sql lite
// user table
userMO = dbHelper.getUserData(1);
/* if (!sharedpreferences.getString("MessageMO", "null").equals("null")) {
MessageMO messageMO1 = (MessageMO) gson.fromJson(sharedpreferences.getString("MessageMO", "null"), new TypeToken<MessageMO>() {
}.getType());
eventMO.setEventId(messageMO1.getEventId());
Log.e("shared","eventID"+messageMO1.getEventId());
Log.e("shared","eventID"+eventMO.getEventId());
eventMO.setText(messageMO1.getEventTitle());
Log.i("message values", messageMO1.toString());
ChatMO chatMO = new ChatMO();
//chatMessageObjects.setMessage(messageMO1.getMessage());
chatMO.setSelf(0);
chatMO.setFromName(messageMO1.getfromUserName());
listChatMessageObjectses.add(chatMO);
//listViewMessages.setAdapter(adapter);
adapter.notifyDataSetChanged();
}*/
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... arg0) {
return userDelegate.getUsersForEvent(activeEventMO.getEventId());
}
#Override
protected void onPostExecute(String eventLists) {
eventUserMOs = gson.fromJson(eventLists, new TypeToken<ArrayList<UserMO>>() {
}.getType());
Toast.makeText(getApplicationContext(), "event users " + eventUserMOs.size(), Toast.LENGTH_LONG).show();
}
}.execute(null, null, null);
Button sendButton = (Button) findViewById(R.id.btnSend);
This gcmIntent here i am passing the intent from this gcmIntent
Intent groupChatActFrag = new Intent(getApplicationContext(), GroupChatActivity.class);
EventMO eventMO = new EventMO();
//here messageMO having the details of received message here i am setting eventId from messageMO to eventMO
// Inorder to passs gropchatActivity
eventMO.setEventId(messageMO.getEventId());
groupChatActFrag.putExtra("eventMo", eventMO);
groupChatActFrag.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("MessageMO", gson.toJson(messageMO));
editor.commit();
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, groupChatActFrag, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_dialog_info).setContentTitle(messageMO.getEventTitle())
.setStyle(new NotificationCompat.BigTextStyle().bigText(messageMO.getfromUserName())).setContentText(messageMO.getMessage()).setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
mBuilder.setContentIntent(contentIntent);
mBuilder.setAutoCancel(true);
mNotificationManager.notify((int) (long) messageMO.getEventId(), mBuilder.build());
You need to do couple of things to achieve the result.
Set launch mode of groupchatactivity to SingleTask
Override onNewIntent() method in groupchatactivity
Call setIntent(intent) for new received intent in onNewIntent()
Reflect as appropriate on above answer.

Lock Screen Player Controls and Meta Data

I'm trying to use MediaSessionCompat in order to add lock screen player controls and meta data for my app. Everything I tried doesn't work. The lock screen doesn't show any controls or meta data while playing. Please see my current code below and any help is appreciated.
StreamService.java:
public class StreamService extends Service implements MediaPlayer.OnCuePointReceivedListener, MediaPlayer.OnStateChangedListener,
MediaPlayer.OnInfoListener, AudioManager.OnAudioFocusChangeListener {
private WifiManager.WifiLock wifiLock;
private static String LOG_TAG = "StreamService";
public static final String BROADCAST_PLAYER_STATE = "com.test.BROADCAST_PLAYER_STATE";
public static final String BROADCAST_PLAYER_META = "com.test.BROADCAST_PLAYER_META";
public static final String BROADCAST_PLAYER_ALBUM = "com.test.BROADCAST_PLAYER_ALBUM";
public static final int NOTIFICATION_ID = 999999;
private MediaSessionCompat mediaSession;
private boolean audioInterrupted = false;
public StreamService() {
}
#Override
public void onCreate(){
super.onCreate();
setupMediaPlayer();
setupMediaSession();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public boolean onUnbind(Intent intent){
releasePlayer();
return false;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
private void setupMediaPlayer() {
// Recreate player
Bundle playerSettings = (BrandedApplication.getContext().getmTritonPlayer() == null) ? null : BrandedApplication.getContext().getmTritonPlayer().getSettings();
Bundle inputSettings = createPlayerSettings();
if (!Utility.bundleEquals(inputSettings, playerSettings)) {
releasePlayer();
createPlayer(inputSettings);
}
// Start the playback
play();
}
private void setupMediaSession() {
ComponentName receiver = new ComponentName(getPackageName(), RemoteReceiver.class.getName());
mediaSession = new MediaSessionCompat(this, "StreamService", receiver, null);
mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS |
MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
mediaSession.setPlaybackState(new PlaybackStateCompat.Builder()
.setState(PlaybackStateCompat.STATE_PAUSED, 0, 0)
.setActions(PlaybackStateCompat.ACTION_PLAY_PAUSE | PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE)
.build());
mediaSession.setMetadata(new MediaMetadataCompat.Builder()
.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, "Test Artist")
.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, "Test Album")
.putString(MediaMetadataCompat.METADATA_KEY_TITLE, "Test Track Name")
.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, 10000)
.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART,
BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
//.putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE, "Test Artist")
.build());
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.requestAudioFocus(new AudioManager.OnAudioFocusChangeListener() {
#Override
public void onAudioFocusChange(int focusChange) {
// Ignore
}
}, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
mediaSession.setActive(true);
}
synchronized private void play() {
audioInterrupted = false;
BrandedApplication.getContext().getmTritonPlayer().play();
if(wifiLock != null) {
wifiLock.acquire();
}
if(mediaSession != null) {
mediaSession.setPlaybackState(new PlaybackStateCompat.Builder()
.setState(PlaybackStateCompat.STATE_PLAYING, 0, 1.0f)
.setActions(PlaybackStateCompat.ACTION_PLAY_PAUSE).build());
}
}
synchronized private void stop() {
BrandedApplication.getContext().getmTritonPlayer().stop();
if(wifiLock != null) {
wifiLock.release();
}
if(mediaSession != null) {
mediaSession.setPlaybackState(new PlaybackStateCompat.Builder()
.setState(PlaybackStateCompat.STATE_PAUSED, 0, 0.0f)
.setActions(PlaybackStateCompat.ACTION_PLAY_PAUSE).build());
}
}
private void createPlayer(Bundle settings)
{
BrandedApplication.getContext().setmTritonPlayer(new TritonPlayer(this, settings));
wifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
.createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
BrandedApplication.getContext().getmTritonPlayer().setOnCuePointReceivedListener(this);
BrandedApplication.getContext().getmTritonPlayer().setOnInfoListener(this);
BrandedApplication.getContext().getmTritonPlayer().setOnStateChangedListener(this);
}
protected void releasePlayer() {
if (BrandedApplication.getContext().getmTritonPlayer() != null) {
if(BrandedApplication.getContext().isPlaying()) {
stop();
}
BrandedApplication.getContext().getmTritonPlayer().release();
BrandedApplication.getContext().setmTritonPlayer(null);
}
stopForeground(true);
}
protected Bundle createPlayerSettings() {
// Player Settings
Bundle settings = new Bundle();
// AAC
settings.putString(TritonPlayer.SETTINGS_STATION_MOUNT, getResources().getString(R.string.station_stream_mount) + "AAC");
// MP3
//settings.putString(TritonPlayer.SETTINGS_STATION_MOUNT, mountID);
settings.putString(TritonPlayer.SETTINGS_STATION_BROADCASTER, getResources().getString(R.string.app_name));
settings.putString(TritonPlayer.SETTINGS_STATION_NAME, getResources().getString(R.string.app_name));
return settings;
}
#Override
public void onCuePointReceived(MediaPlayer mediaPlayer, Bundle bundle) {
//System.out.println("TRITON PLAYER BUNDLE " + bundle);
String trackName = "";
String artistName = "";
if(bundle != null) {
if(bundle.containsKey("cue_title") && bundle.containsKey("track_artist_name")) {
if (!bundle.getString("cue_title").isEmpty()) {
trackName = bundle.getString("cue_title");
}
if (!bundle.getString("track_artist_name").isEmpty()) {
artistName = bundle.getString("track_artist_name");
}
}
}
// broadcast out the meta data
Intent i = new Intent(BROADCAST_PLAYER_META);
i.putExtra("trackName", trackName);
i.putExtra("artistName", artistName);
sendBroadcast(i);
// send notification and start as foreground service
PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(getApplicationContext(), MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
Bitmap icon = BitmapFactory.decodeResource(getResources(),
R.drawable.logo);
String tickerString = "";
String contentString = "Playing";
if(!artistName.isEmpty() && !trackName.isEmpty()) {
tickerString = artistName + " - " + trackName;
contentString += ": " + artistName + " - " + trackName;
}
Intent pauseIntent = new Intent(BROADCAST_PLAYER_PAUSE);
PendingIntent pausePendingIntent = PendingIntent.getBroadcast(this, 0, pauseIntent, 0);
NotificationCompat.Builder notification = new NotificationCompat.Builder(this)
.setContentTitle(getResources().getString(R.string.app_name))
.setTicker(tickerString)
.setContentText(contentString)
.setSmallIcon(R.drawable.ic_launcher)
//.setAutoCancel(true)
//.setLargeIcon(
// Bitmap.createScaledBitmap(icon, 128, 128, false))
.addAction(R.drawable.ic_media_pause, "Pause", pausePendingIntent)
.setContentIntent(pi)
.setStyle(new android.support.v7.app.NotificationCompat.MediaStyle()
//.setShowActionsInCompactView(0)
.setMediaSession(mediaSession.getSessionToken()))
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setOngoing(true);
//notification.setPriority(Notification.PRIORITY_MIN);
notification.setPriority(Notification.PRIORITY_DEFAULT);
startForeground(NOTIFICATION_ID, notification.build());
}
#Override
public void onInfo(MediaPlayer mediaPlayer, int i, int i1) {
}
#Override
public void onStateChanged(MediaPlayer mediaPlayer, int state) {
Log.i(LOG_TAG, "onStateChanged: " + TritonPlayer.debugStateToStr(state));
// broadcast out the player state
Intent i = new Intent(BROADCAST_PLAYER_STATE);
i.putExtra("state", state);
sendBroadcast(i);
}
#Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_GAIN:
// resume playback
System.out.println("AUDIO FOCUS GAIN");
if(audioInterrupted) {
audioInterrupted = false;
if (BrandedApplication.getContext().getmTritonPlayer() == null) {
setupMediaPlayer();
} else if (!BrandedApplication.getContext().isPlaying()) {
setupMediaPlayer();
}
}
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
case AudioManager.AUDIOFOCUS_LOSS:
System.out.println("AUDIO FOCUS LOSS");
// Lost focus for an unbounded amount of time: stop playback and release media player
if (BrandedApplication.getContext().isPlaying()) {
audioInterrupted = true;
releasePlayer();
}
break;
}
}
#Override
public void onDestroy() {
System.out.println("SERVICE STOPPED");
releasePlayer();
mediaSession.release();
}
}
And here's RemoteReceiver.java:
public class RemoteReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
final KeyEvent event = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event != null && event.getAction() == KeyEvent.ACTION_DOWN) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
context.startService(new Intent(context, StreamService.class));
break;
}
}
}
}
}
Okay, from the additional information you provided, I believe I know what the issue is. In Android 5.0 Lock Screen Controls were removed. They are now implemented via the Notification API. So try adding the following to your notification builder.
notification.setStyle(new NotificationCompat.MediaStyle()
.setShowActionsInCompactView(0)
.setMediaSession(mediaSession));
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
That should place it on your lock screen. I would also suggest changing the Notification.PRIORITY_DEFAULT as well as include an action to your notification otherwise you won't be able to control the playback.
I know this post is late but if anyone is still facing the issue.This will show up in your lock screen also.
Here is the code for notification builder class-
import android.annotation.SuppressLint;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.media.session.MediaSessionManager;
import android.os.Build;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationCompat;
import android.support.v4.media.session.MediaControllerCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.util.Log;
import org.json.JSONException;
public class MediaPlayerService extends Service {
private static final String CHANNEL_ID = "my_channel_01";
public static final String ACTION_PLAY = "action_play";
public static final String ACTION_PAUSE = "action_pause";
public static final String ACTION_NEXT = "action_next";
public static final String ACTION_PREVIOUS = "action_previous";
public static final String ACTION_STOP = "action_stop";
public static final String ACTION_NOTHING = "action_previous";
private NotificationManager notificationManager;
NotificationManager mNotificationManager;
private MediaPlayer mMediaPlayer;
private MediaSessionManager mManager;
private MediaSessionCompat mSession;
private MediaControllerCompat mController;
private MediaPlayerService mService;
String title = null;
String description = null;
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void handleIntent(Intent intent) {
if (intent == null || intent.getAction() == null)
return;
String action = intent.getAction();
if (action.equalsIgnoreCase(ACTION_PLAY)) {
mController.getTransportControls().play();
} else if (action.equalsIgnoreCase(ACTION_PAUSE)) {
mController.getTransportControls().pause();
} else if (action.equalsIgnoreCase(ACTION_PREVIOUS)) {
mController.getTransportControls().skipToPrevious();
} else if (action.equalsIgnoreCase(ACTION_NEXT)) {
mController.getTransportControls().skipToNext();
} else if (action.equalsIgnoreCase(ACTION_STOP)) {
mController.getTransportControls().stop();
}
}
private NotificationCompat.Action generateAction(int icon, String title, String intentAction) {
Intent intent = new Intent(getApplicationContext(), MediaPlayerService.class);
intent.setAction(intentAction);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 1, intent, 0);
return new NotificationCompat.Action.Builder(icon, title, pendingIntent).build();
}
#SuppressLint("ServiceCast")
private void buildNotification(NotificationCompat.Action action) {
title = ""; // add variable to get current playing song title here
description =""; // add variable to get current playing song description here
Intent notificationIntent = new Intent(getApplicationContext(), HomeActivity.class); //specify which activity should be opened when widget is clicked (other than buttons)
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Notification channels are only supported on Android O+.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
//method to create channel if android version is android. Descrition below
createNotificationChannel();
}
Intent intent = new Intent(getApplicationContext(), MediaPlayerService.class);
intent.setAction(ACTION_STOP);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 1, intent, 0);
final NotificationCompat.Builder builder;
//condition to check if music is playing
//if music is playing widget cant be dismissed on swipe
if(<add your method to check play status here>)
{
builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.logo2b)
.setLargeIcon(BitmapFactory.decodeResource(getApplication().getResources(), R.mipmap.ic_launcher))
.setContentTitle(title)
.setContentText(description)
.setDeleteIntent(pendingIntent)
.setContentIntent(contentIntent)
.setChannelId(CHANNEL_ID)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setOnlyAlertOnce(true)
.setColor(getResources().getColor(R.color.colorPrimary))
.setOngoing(true) //set this to true if music is playing widget cant be dismissed on swipe
.setStyle(new android.support.v4.media.app.NotificationCompat.MediaStyle()
// show only play/pause in compact view
.setShowActionsInCompactView(0, 1, 2));
}
//else if music is not playing widget can be dismissed on swipe
else
{
builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.logo2b)
.setLargeIcon(BitmapFactory.decodeResource(getApplication().getResources(), R.mipmap.ic_launcher))
.setContentTitle(title)
.setContentText(description)
.setDeleteIntent(pendingIntent)
.setContentIntent(contentIntent)
.setChannelId(CHANNEL_ID)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setOnlyAlertOnce(true)
.setColor(getResources().getColor(R.color.colorPrimary))
.setStyle(new android.support.v4.media.app.NotificationCompat.MediaStyle()
// show only play/pause in compact view
.setShowActionsInCompactView(0, 1, 2));
}
builder.addAction(generateAction(R.drawable.ic_skip_previous_white_24dp, "Previous", ACTION_PREVIOUS));
builder.addAction(action);
builder.addAction(generateAction(R.drawable.ic_skip_next_white_24dp, "Next", ACTION_NEXT));
//style.setShowActionsInCompactView(0,1,2);
// builder.setColor(getResources().getColor(R.color.app_orange_color));
notificationManager.notify(1, builder.build());
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (mManager == null) {
try {
initMediaSessions();
} catch (RemoteException e) {
e.printStackTrace();
}
}
handleIntent(intent);
return super.onStartCommand(intent, flags, startId);
}
private void initMediaSessions() throws RemoteException {
mMediaPlayer = new MediaPlayer();
mSession = new MediaSessionCompat(getApplicationContext(), "simple player session");
mController = new MediaControllerCompat(getApplicationContext(), mSession.getSessionToken());
mSession.setCallback(new MediaSessionCompat.Callback() {
#Override
public void onPlay() {
super.onPlay();
//add you code for play button click here
//replace your drawable id that shows pauseicon buildNotification(generateAction(R.drawable.uamp_ic_pause_white_24dp, "Pause", ACTION_PAUSE));
}
#Override
public void onPause() {
super.onPause();
//add you code for pause button click here
//replace your drawable id that shows play icon buildNotification(generateAction(R.drawable.uamp_ic_play_arrow_white_24dp, "Play", ACTION_PLAY));
}
#Override
public void onSkipToNext() {
super.onSkipToNext();
//add you code for next button click here
buildNotification(generateAction(R.drawable.uamp_ic_pause_white_24dp, "Pause", ACTION_PAUSE));
}
#Override
public void onSkipToPrevious() {
super.onSkipToPrevious();
//add you code for previous button click here
buildNotification(generateAction(R.drawable.uamp_ic_pause_white_24dp, "Pause", ACTION_PAUSE));
}
#Override
public void onStop() {
super.onStop();
Log.e("MediaPlayerService", "onStop");
//Stop media player and dismiss widget here
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(1);
Intent intent = new Intent(getApplicationContext(), MediaPlayerService.class);
stopService(intent);
}
#Override
public void onSeekTo(long pos) {
super.onSeekTo(pos);
}
}
);
}
#Override
public boolean onUnbind(Intent intent) {
mSession.release();
return super.onUnbind(intent);
}
//method to create notification channel on android Oreo and above
#RequiresApi(Build.VERSION_CODES.O)
private void createNotificationChannel() {
int notifyID = 1;
CharSequence name = "Player Widget";// The user-visible name of the channel. This channel name will be shown in settings.
if (notificationManager.getNotificationChannel(CHANNEL_ID) == null) {
NotificationChannel notificationChannel =
new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_LOW);
notificationManager.createNotificationChannel(notificationChannel);
}
}
}
And fire these intents for actions to update widget when play status is changed from within the app:
Play-
//to change widgets current action button to play
Intent intent = new Intent(getApplicationContext(), MediaPlayerService.class);
intent.setAction(MediaPlayerService.ACTION_PAUSE);
startService(intent);
Pause-
//to change widgets current action button to pause
Intent intent = new Intent(getApplicationContext(), MediaPlayerService.class);
intent.setAction(MediaPlayerService.ACTION_PLAY);
startService(intent);
Excuse me if there are any unwanted import.All the best.

Categories

Resources