When I use Intent outside of onStartCommand() of service, to show notification on a specific event, it shows getApplicationContext on the null object reference.
Service only allow to use getApplcationContext/this/context inside the onStartCommand() method.
How can I use it outside of onStartCommand() method?
Below is my Service. Can someone help me out with this?
public class ForegroundService extends Service {
#Nullable
private static TransferUtility transferUtility;
private static ArrayList<HashMap<String, Object>> transferRecordMaps;
private static ArrayList<HashMap<String, Object>> transferRecordMaps1;
private Utils utils = new Utils();
private static final int INDEX_NOT_CHECKED = -1;
public static int totalcount, totalAssetCount;
private int checkedIndex;
private static List<TransferObserver> observers;
private static int REQUEST_CAMERA = 0, navigate = 0,counter=0,failedcounter=0;
private static final String LOG_TAG = "ForegroundService";
UploadMediaToAssetFragment uploadMediaToAssetFragment;
private int progress;
Context context;
private long currentbyte, totalbyte;
private Notification notification;
#Override
public void onCreate() {
super.onCreate();
transferUtility = Util.getTransferUtility(getApplicationContext());
checkedIndex = INDEX_NOT_CHECKED;
transferRecordMaps = new ArrayList<HashMap<String, Object>>();
transferRecordMaps1 = new ArrayList<HashMap<String, Object>>();
uploadMediaToAssetFragment = new UploadMediaToAssetFragment();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
Log.i(LOG_TAG, "Received Start Foreground Intent ");
Intent notificationIntent = new Intent(this, UploadMediaToAssetFragment.class);
notificationIntent.setAction(Constants.ACTION.MAIN_ACTION);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
Log.d(LOG_TAG,"bytes"+UploadMediaToAssetFragment.totalAssetCount+ " total"+UploadMediaToAssetFragment.totalcount);
uploadAsset();
initData();
updateList();
// AlertDialog.Builder builder = new AlertDialog.Builder(this);
// builder.setTitle("Test dialog");
// builder.setIcon(R.drawable.icon);
// builder.setMessage("Content");
//
// AlertDialog alert = builder.create();
// alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
// alert.show();
// startActivity(notificationIntent);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Intent previousIntent = new Intent(this, ForegroundService.class);
previousIntent.setAction(Constants.ACTION.PREV_ACTION);
PendingIntent ppreviousIntent = PendingIntent.getService(this, 0,
previousIntent, 0);
Intent playIntent = new Intent(this, ForegroundService.class);
playIntent.setAction(Constants.ACTION.PLAY_ACTION);
PendingIntent pplayIntent = PendingIntent.getService(this, 0,
playIntent, 0);
Intent nextIntent = new Intent(this, ForegroundService.class);
nextIntent.setAction(Constants.ACTION.NEXT_ACTION);
PendingIntent pnextIntent = PendingIntent.getService(this, 0,
nextIntent, 0);
Bitmap icon = BitmapFactory.decodeResource(getResources(),
R.drawable.logo);
notification = new NotificationCompat.Builder(this)
.setContentTitle("Visibly")
.setTicker("asset uplaoding")
.setContentText("uploading")
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(
Bitmap.createScaledBitmap(icon, 128, 128, false))
.setContentIntent(pendingIntent)
.setOngoing(true)
.setProgress(100,progress,false)
.addAction(android.R.drawable.ic_menu_close_clear_cancel,
"cancel", ppreviousIntent).build();
startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE,
notification);
// if(UploadMediaToAssetFragment.totalAssetCount>=UploadMediaToAssetFragment.totalcount)
// {
// onDestroy();
// stopForeground(true);
// stopSelf();
// }
} else if (intent.getAction().equals(Constants.ACTION.PREV_ACTION)) {
Log.i(LOG_TAG, "Clicked Previous");
} else if (intent.getAction().equals(Constants.ACTION.PLAY_ACTION)) {
Log.i(LOG_TAG, "Clicked Play");
} else if (intent.getAction().equals(Constants.ACTION.NEXT_ACTION)) {
Log.i(LOG_TAG, "Clicked Next");
} else if (intent.getAction().equals(
Constants.ACTION.STOPFOREGROUND_ACTION)) {
Log.i(LOG_TAG, "Received Stop Foreground Intent");
stopForeground(true);
stopSelf();
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(LOG_TAG, "In onDestroy");
}
public IBinder onBind(Intent intent) {
return null;
}
public class ForegroundServiceBInder extends Binder {
ForegroundService getService() {
// Return this instance of LocalService so clients can call public methods
return ForegroundService.this;
}
}
public void uploadAsset()
{
Log.d("upload asset service","method called");
for(int i=0;i<AddMediaAssetActivity.galleryDTOArrayList1.size();i++)
{
Handler handler1 = new Handler();
try {
if(AddMediaAssetActivity.galleryDTOArrayList1.get(i)!=null)
{
String path;
Uri uri = Uri.fromFile(new File(AddMediaAssetActivity.galleryDTOArrayList1.get(i).getMediaName()));
path = Utility.getPath(uri, getApplicationContext());
Uri uriThumb = Uri.fromFile(new File(AddMediaAssetActivity.galleryDTOArrayList1.get(i).getThumbnail()));
String pathThum = null;
if (uriThumb != null)
pathThum = Utility.getPath(uriThumb, getApplicationContext());
path = Utility.getPath(uri, getApplicationContext());
if(GlobalVariables.isNetworkAvailable(getApplicationContext())) {
beginUpload1(pathThum, pathThum);
beginUpload(path, AddMediaAssetActivity.galleryDTOArrayList1.get(i).getDescription(), pathThum,AddMediaAssetActivity.galleryDTOArrayList1.get(i).getCreateTagPostDTOList());
}else
{
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(getApplicationContext(),android.R.style.Theme_Material_Light_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(getApplicationContext());
}
builder.setMessage(getResources().getString(R.string.network_connectivity))
.setTitle("");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
//getApplicationContext().finish();
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.setCanceledOnTouchOutside(true);
dialog.show();
dialog.getButton(dialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.clear_blue));
}
}
}catch (Exception e)
{
}
}
}
/*
* Begins to upload the file specified by the file path.
*/
private void beginUpload(String filePath, String title, String pathThum, List<TagDTO> createTagPostDTOList)
{
Log.d("beginUpload","method called "+filePath+" title "+title+" pathnum "+pathThum+" list tagdto"+createTagPostDTOList);
if (filePath == null) {
Toast.makeText(getApplicationContext(), "Could not find the filepath of the selected file",
Toast.LENGTH_LONG).show();
return;
}
File file = new File(filePath);
TransferObserver observer = transferUtility.upload(Constants.BUCKET_NAME, Constants.FOLDERNAME_NAME+"/"+ file.getName(),
file, CannedAccessControlList.PublicRead);
File file1 = new File(pathThum);
AssetMediaDTO assetMediaDTO=new AssetMediaDTO();
if(GlobalVariables.isCampaignAsset)
{
if (GlobalVariables.campaignFeedDTO.getCampaign_category() != null && GlobalVariables.campaignFeedDTO.getCampaign_category().length() > 0 && !(GlobalVariables.campaignFeedDTO.getCampaign_category().equalsIgnoreCase("null"))) {
assetMediaDTO.setCategory_id(GlobalVariables.campaignFeedDTO.getCampaign_category());
} else {
assetMediaDTO.setCategory_id("rpPDp");
}
if (GlobalVariables.campaignFeedDTO.getCampaign_folder() != null && GlobalVariables.campaignFeedDTO.getCampaign_folder().length() > 0 && !(GlobalVariables.campaignFeedDTO.getCampaign_folder().equalsIgnoreCase("null"))) {
if(GlobalVariables.campaignFeedDTO.getCampaign_folder().equalsIgnoreCase("General"))
{
assetMediaDTO.setFolder_id("");
}else
{
assetMediaDTO.setFolder_id(GlobalVariables.campaignFeedDTO.getCampaign_folder());
}
} else
{
assetMediaDTO.setFolder_id("");
}
}else
{
if (AssetFolderActivity.folderDTO.getCategoryID() != null && AssetFolderActivity.folderDTO.getCategoryID().length() > 0 && !(AssetFolderActivity.folderDTO.getCategoryID().equalsIgnoreCase("null"))) {
assetMediaDTO.setCategory_id(AssetFolderActivity.folderDTO.getCategoryID());
} else {
assetMediaDTO.setCategory_id("rpPDp");
}
if (AssetFolderActivity.folderDTO.getFolderIdentity() != null && AssetFolderActivity.folderDTO.getFolderIdentity().length() > 0 && !(AssetFolderActivity.folderDTO.getFolderIdentity().equalsIgnoreCase("null"))) {
if(AssetFolderActivity.folderDTO.getFoldername()!=null&&AssetFolderActivity.folderDTO.getFoldername().equalsIgnoreCase("general"))
{
assetMediaDTO.setFolder_id("");
}else {
assetMediaDTO.setFolder_id(AssetFolderActivity.folderDTO.getFolderIdentity());
}
} else {
assetMediaDTO.setFolder_id("");
}
}
assetMediaDTO.setMedia_url(GlobalVariables.s3Path+Constants.FOLDERNAME_NAME+"/"+file.getName());
assetMediaDTO.setThumbnail_url(GlobalVariables.s3Path+Constants.FOLDERNAME_NAME+"/"+file1.getName());
try {
assetMediaDTO.setMediaSize(""+file.length());
}catch (Exception e)
{
}
assetMediaDTO.setDetail(title);
String result = file.getName().substring(0, file.getName().lastIndexOf("."));
assetMediaDTO.setTitle(result);
assetMediaDTO.setTagDTOList(createTagPostDTOList);
GlobalVariables.assetMediaDTOList.add(assetMediaDTO);
}
/*
* Begins to upload the file specified by the file path.
*/
private void beginUpload1(String filePath, String pathThum) {
Log.d("beginUpload1","method called");
if (filePath == null) {
Toast.makeText(getApplicationContext(), "Could not find the filepath of the selected file",
Toast.LENGTH_LONG).show();
return;
}
File file = new File(filePath);
TransferObserver observer = transferUtility.upload(Constants.BUCKET_NAME, Constants.FOLDERNAME_NAME+"/"+ file.getName(),
file,CannedAccessControlList.PublicRead);
// temp1=file.getName();
}
//To delete assets from list
public void deleteMediaUpload(final int position)
{
final int position1=position+1;
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(GlobalVariables.mActivity, android.R.style.Theme_Material_Light_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(GlobalVariables.mActivity);
}
builder.setMessage("Do you want to delete this media?")
.setTitle("");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
dialog.dismiss();
if (position >= 0 && position1 < observers.size())
{
try {
transferUtility.deleteTransferRecord(observers.get(position).getId());
transferUtility.deleteTransferRecord(observers.get(position1).getId());
observers.remove(position1);
transferRecordMaps.remove(position1);
observers.remove(position);
transferRecordMaps.remove(position);
AddMediaAssetActivity.galleryDTOArrayList1.remove(position);
}catch (Exception e)
{
}
updateList();
try {
GlobalVariables.assetMediaDTOList.remove(position);
}catch (Exception e)
{
}
}
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.setCanceledOnTouchOutside(false);
dialog.show();
dialog.getButton(dialog.BUTTON_NEGATIVE).setTextColor(GlobalVariables.mActivity.getResources().getColor(R.color.clear_blue));
dialog.getButton(dialog.BUTTON_POSITIVE).setTextColor(GlobalVariables.mActivity.getResources().getColor(R.color.clear_blue));
}
// /**
// * Gets all relevant transfers from the Transfer Service for populating the
// * UI
// */
// private void initData() {
// counter=0;
// failedcounter=0;
// navigate=0;
// transferRecordMaps.clear();
// transferRecordMaps1.clear();
// // Use TransferUtility to get all upload transfers.
// observers = transferUtility.getTransfersWithType(TransferType.UPLOAD);
// TransferListener listener = new UploadMediaToAssetFragment.UploadListener();
// for (TransferObserver observer : observers) {
//
// // For each transfer we will will create an entry in
// // transferRecordMaps which will display
// // as a single row in the UI
// HashMap<String, Object> map = new HashMap<String, Object>();
// Util.fillMap(map, observer, false);
//
// transferRecordMaps.add(map);
//
// // Sets listeners to in progress transfers
// if (TransferState.WAITING.equals(observer.getState())
// || TransferState.WAITING_FOR_NETWORK.equals(observer.getState())
// || TransferState.IN_PROGRESS.equals(observer.getState())) {
// observer.setTransferListener(listener);
// }
// }
// transferRecordMaps1.clear();
// for(int i=0;i<transferRecordMaps.size();i++)
// {
// File file = new File((String) transferRecordMaps.get(i).get("fileName"));
// if(file.getName().substring(0,2).equalsIgnoreCase("0!"))
// {
// }
// else
// {
// transferRecordMaps1.add(transferRecordMaps.get(i));
//
// }
//
// }
// assetListAdapter.notifyDataSetChanged();
// }
/*
* A TransferListener class that can listen to a upload task and be notified
* when the status changes.
*/
public class UploadListener implements TransferListener {
// Simply updates the UI list when notified.
#Override
public void onError(int id, Exception e)
{
failedcounter++;
updateList();
}
#Override
public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
updateList();
currentbyte =bytesCurrent;
totalbyte =bytesTotal;
Log.d("onprogresschnaged","method bytes"+bytesCurrent+" bytestotoal"+bytesTotal);
}
#Override
public void onStateChanged(int id, TransferState newState)
{
if (newState.equals(TransferState.COMPLETED))
{
counter++;
updateList();
} else if (newState.equals(TransferState.FAILED))
{
failedcounter++;
updateList();
}
}
}
/*
* Updates the ListView according to the observers.
*/
/*
* Updates the ListView according to the observers.
*/
public void updateList()
{
if(transferRecordMaps!=null&&transferRecordMaps.size()>0)
{
TransferObserver observer = null;
HashMap<String, Object> map = null;
for (int i = 0; i < observers.size(); i++) {
observer = observers.get(i);
map = transferRecordMaps.get(i);
progress = (int) ((double) observer.getBytesTransferred() * 100 / observer
.getBytesTotal());
Log.d("progressuploadingData"," map"+progress);
Util.fillMap(map, observer, i == checkedIndex);
Log.d("uploadingData"," map"+map+" observer"+observer);
}
transferRecordMaps1.clear();
for (int i = 0; i < transferRecordMaps.size(); i++)
{
File file = new File((String) transferRecordMaps.get(i).get("fileName"));
if (file.getName().substring(0, 2).equalsIgnoreCase("0!")) {
} else
{
transferRecordMaps1.add(transferRecordMaps.get(i));
}
totalcount=transferRecordMaps.size();
totalAssetCount=counter+failedcounter;
Log.d("totalcount","count"+totalcount+"toatlassetcount"+totalAssetCount);
if(counter>1&&totalAssetCount>=totalcount&&GlobalVariables.assetMediaDTOList.size()>0)
{
Log.d("myservice asset","complete");
navigate=1;
Intent intent = new Intent(this, DialogeActivity.class);
context.getApplicationContext().startActivity(intent);
// Toast.makeText(this,"Your asset uploaded successfully",Toast.LENGTH_LONG).show();
// Intent notificationIntent = new Intent(this, DialogeActivity.class);
// notificationIntent.setAction(Constants.ACTION.MAIN_ACTION);
// notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
// | Intent.FLAG_ACTIVITY_CLEAR_TASK);
// startActivity(notificationIntent);
// Notification notification = new NotificationCompat.Builder(this)
// .setContentTitle("Visibly")
// .setTicker("asset uploaded")
// .setContentText("asset uploaded successfully")
// .setSmallIcon(R.drawable.ic_launcher)
// .build();
// AlertDialog.Builder builder = new AlertDialog.Builder(this);
// builder.setTitle("Test dialog");
// builder.setIcon(R.drawable.icon);
// builder.setMessage("Content");
// builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int whichButton) {
// //Do something
// dialog.dismiss();
// });
//
// AlertDialog alert = builder.create();
// alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
// alert.show();
// AlertDialog alertDialog = new AlertDialog.Builder(this)
// .setTitle("Title")
// .setMessage("Are you sure?")
// .create();
//
// alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
// alertDialog.show();
// button_Done.setVisibility(View.VISIBLE);
// button_Done.setText("Done");
// button_Done.setEnabled(true);
// button_Done.setClickable(true);
}else if(failedcounter>=totalcount)
{
navigate=0;
// button_Done.setVisibility(View.VISIBLE);
// button_Done.setText("Back");
// button_Done.setEnabled(true);
// button_Done.setClickable(true);
}else
{
// button_Done.setVisibility(View.VISIBLE);
// button_Done.setText("Please wait.");
// button_Done.setEnabled(false);
// button_Done.setClickable(false);
}
}
// assetListAdapter.notifyDataSetChanged();
}else
{
// Intent intent=null;
// if( AssetFolderActivity.folderDTO!=null&&AssetFolderActivity.folderDTO.getFolderIdentity()!=null&& AssetFolderActivity.folderDTO.getFolderIdentity().length()>0&&!AssetFolderActivity.folderDTO.getFolderIdentity().equalsIgnoreCase("")) {
// intent = new Intent(activity, AssetFolderActivity.class);
// }else
// {
// intent = new Intent(activity, DashboardActivity.class);
// }
// intent.putExtra("folderDTO", AssetFolderActivity.folderDTO);
// activity.startActivity(intent);
// activity.finish();
}
}
private void initData() {
counter=0;
failedcounter=0;
navigate=0;
transferRecordMaps.clear();
transferRecordMaps1.clear();
// Use TransferUtility to get all upload transfers.
observers = transferUtility.getTransfersWithType(TransferType.UPLOAD);
TransferListener listener = new ForegroundService().new UploadListener();
for (TransferObserver observer : observers) {
// For each transfer we will will create an entry in
// transferRecordMaps which will display
// as a single row in the UI
HashMap<String, Object> map = new HashMap<String, Object>();
Util.fillMap(map, observer, false);
transferRecordMaps.add(map);
// Sets listeners to in progress transfers
if (TransferState.WAITING.equals(observer.getState())
|| TransferState.WAITING_FOR_NETWORK.equals(observer.getState())
|| TransferState.IN_PROGRESS.equals(observer.getState())) {
observer.setTransferListener(listener);
}
}
transferRecordMaps1.clear();
for(int i=0;i<transferRecordMaps.size();i++)
{
File file = new File((String) transferRecordMaps.get(i).get("fileName"));
if(file.getName().substring(0,2).equalsIgnoreCase("0!"))
{
}
else
{
transferRecordMaps1.add(transferRecordMaps.get(i));
}
}
// assetListAdapter.notifyDataSetChanged();
}
}
Service only allow to use getApplcationContext/this/context inside the onStartCommand() method
There is no such restriction. You can use it from other methods on your Service, so long as onCreate() has already been called on that Service.
So, to show a Notification from some background thread that your Service forks from onStartCommand(), for example, use this.
Service is child of Context class, that would provide you context when you need. It behaves like an activity (child of context too.)
So same like Activity, you can call this or yourService.this(in anonymus class) keyword as a context.
In updateList() you do this:
context.getApplicationContext().startActivity(intent);
context is a member variable of your Service. However, you never initialize this variable to anything. Therefore it is null, which will cause the error you describe.
Sevices has his own context. There is easy way to have an globl context.
private Context context;
#Override
public int onStartCommand(#Nullable Intent intent, int flags, int startId) {
context = this;
}
That's all. Should work, if not let search an problem in other place.
#Edit
For clarity, your problem causes this line, because your context is not assigned, and it's null.
context.getApplicationContext().startActivity(intent);
Related
I am using recyclerview, in my list item I have button. On that button click I am hiding and showing imageview, now if user click on list item and open imageview and then scrolldown and scrollup, the item in which user opened imageview is getting closed. This is my adapter code:
public class NotiDetailsListAdapter extends RecyclerView.Adapter<NotiDetailsListAdapter.ViewHolder> {
Context context;
private List<NotificationListData> adaBankDetailsList;
String bnkName = "", bnkAccNum = "", userName = "", bankIfscCode = "", bankType = "";
private int selectedPosition = -1;
boolean flag = true;
private NotiDetailsListAdapter(Context conytext, List<NotificationListData> bankDetails) {
this.context = conytext;
this.adaBankDetailsList = bankDetails;
}
#NonNull
#Override
public NotiDetailsListAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflator = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view;
view = inflator.inflate(R.layout.notification_list_item_layout, parent, false);
return new NotiDetailsListAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final NotiDetailsListAdapter.ViewHolder holder, int pos) {
bnkResponse = adaBankDetailsList.get(pos);
try {
holder.notification_main_text.setText(bnkResponse.getNotificationTitle());
holder.notification_sub_text.setText(bnkResponse.getNotificationMessage());
String mydates=bnkResponse.getNotificationSendTime();
String[] str_array1 = mydates.split("-");
if(str_array1[0] != null && str_array1[0].length() > 0 && str_array1[1] != null && str_array1[1].length() > 0) {
stringa1 = str_array1[0];
stringb1 = str_array1[1];
}
else
{
stringa1 = str_array1[0];
stringb1 = "";
}
String[] timearray = stringb1.split(":");
if(timearray[0] != null && timearray[0].length() > 0 && timearray[1] != null && timearray[1].length() > 0) {
stringt1 = timearray[0];
stringt2 = timearray[1];
}
else
{
stringt1 = timearray[0];
stringt2 = "";
}
if(mydates.contains("PM"))
{
stringampm="PM";
}
else if(mydates.contains("AM"))
{
stringampm="AM";
}
System.out.println("Dates "+stringampm+" "+stringt2);
holder.notification_date.setText(stringa1);
holder.notification_time.setText(stringt1+":"+stringt2+" "+stringampm);
holder.notification_iv.setVisibility(View.GONE);
holder.notification_main_text.setSingleLine(false);
holder.notification_main_text.setEllipsize(TextUtils.TruncateAt.END);
int n1 = 1; // the exact number of lines you want to display
holder.notification_main_text.setLines(n1);
holder.notification_main_text.setMaxEms(12);
holder.notification_sub_text.setSingleLine(false);
holder.notification_sub_text.setEllipsize(TextUtils.TruncateAt.END);
int n = 1; // the exact number of lines you want to display
holder.notification_sub_text.setLines(n);
holder.iv_arrow.setImageResource(R.mipmap.down);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return adaBankDetailsList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView notification_main_text, notification_sub_text, notification_date, notification_time;
ImageView iv_arrow,notification_iv;
RelativeLayout parentRL,notification_rl;
LinearLayout arrow_click;
public ViewHolder(View itemView) {
super(itemView);
notification_main_text = itemView.findViewById(R.id.notification_main_text);
notification_sub_text = itemView.findViewById(R.id.notification_sub_text);
notification_date = itemView.findViewById(R.id.notification_date);
notification_time = itemView.findViewById(R.id.notification_time);
iv_arrow = itemView.findViewById(R.id.iv_arrow);
notification_iv = itemView.findViewById(R.id.notification_iv);
parentRL = itemView.findViewById(R.id.parentRL);
notification_rl = itemView.findViewById(R.id.notification_rl);
arrow_click = itemView.findViewById(R.id.arrow_click);
// Store the context
// Attach a click listener to the entire row view
parentRL.setOnClickListener(this);
iv_arrow.setOnClickListener(this);
/* itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});*/
}
#Override
public void onClick(View view) {
int position = getAdapterPosition();
switch (view.getId()){
case R.id.parentRL:
try {
if (adaBankDetailsList.get(position).getNotificationLevel().equalsIgnoreCase("promotion")) {
Intent notificationIntent = new Intent(NotificationListActivity.this, InviteEarnWebViewActivity.class);
notificationIntent.putExtra("notificationClick","true");
//notificationIntent.putExtra("notifId",(bnkResponse.getLevelId()));
notificationIntent.putExtra("searchQuery", adaBankDetailsList.get(position).getCustomPageUrl());
notificationIntent.putExtra("headerName", adaBankDetailsList.get(position).getCustomPageTitle());
notificationIntent.putExtra("showShareEarn","N");
startActivity(notificationIntent);
}else if (adaBankDetailsList.get(position).getNotificationLevel().equalsIgnoreCase("update")) {
Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
notificationIntent.setData(Uri.parse("market://details?id=com.milmila.android.milmila_home"));
startActivity(notificationIntent);
}else if (adaBankDetailsList.get(position).getNotificationLevel().equalsIgnoreCase("home")) {
Intent notificationIntent = new Intent(NotificationListActivity.this, BottomNavigationActivity.class);
notificationIntent.putExtra("notificationClick","true");
//notificationIntent.putExtra("notifId",(bnkResponse.getLevelId()));
startActivity(notificationIntent);
}else if (adaBankDetailsList.get(position).getNotificationLevel().equalsIgnoreCase("invite")) {
Intent notificationIntent = new Intent(NotificationListActivity.this, InviteEarnWebViewActivity.class);
notificationIntent.putExtra("notificationClick","true");
// notificationIntent.putExtra("notifId",(bnkResponse.getLevelId()));
notificationIntent.putExtra("searchQuery", Constants.BASE_URL+"customerInvite/inviteEarn.html?customerId=#sharedPreferenceUserId#");
notificationIntent.putExtra("headerName","Invite & Earn");
notificationIntent.putExtra("showShareEarn","Y");
startActivity(notificationIntent);
}else if (adaBankDetailsList.get(position).getNotificationLevel().equalsIgnoreCase("share_earn")) {
Intent notificationIntent = new Intent(NotificationListActivity.this, InviteEarnWebViewActivity.class);
notificationIntent.putExtra("notificationClick","true");
// notificationIntent.putExtra("notifId",(bnkResponse.getLevelId()));
notificationIntent.putExtra("searchQuery",Constants.BASE_URL+"double-dhamaka.html?customerId=#sharedPreferenceUserId#");
notificationIntent.putExtra("headerName","Gift your friend 100");
notificationIntent.putExtra("showShareEarn","Y");
startActivity(notificationIntent);
} else if (adaBankDetailsList.get(position).getNotificationLevel().equalsIgnoreCase("product")) {
Intent notificationIntent = new Intent(NotificationListActivity.this, ProductDetailsActivity.class);
notificationIntent.putExtra("notificationClick","true");
notificationIntent.putExtra(STRING_IMAGE_PRODUCTID,(adaBankDetailsList.get(position).getLevelId()));
// notificationIntent.putExtra(STRING_IMAGE_PRODUCTID, levelId);
// notificationIntent.putExtra(STRING_IMAGE_PRODUCT_URL, "");
startActivity(notificationIntent);
}else if (adaBankDetailsList.get(position).getNotificationLevel().equalsIgnoreCase("Earnings")) {
Intent notificationIntent = new Intent(NotificationListActivity.this, BottomNavigationActivity.class);
notificationIntent.putExtra("notificationClick","true");
// notificationIntent.putExtra("notifId",(bnkResponse.getLevelId()));
notificationIntent.putExtra("mmcash", "Y");
startActivity(notificationIntent);
} else if (adaBankDetailsList.get(position).getNotificationLevel().equalsIgnoreCase("group")) {
Intent notificationIntent = new Intent(NotificationListActivity.this, GroupProductListActivity.class);
notificationIntent.putExtra("notificationClick","true");
notificationIntent.putExtra("categoryID",(adaBankDetailsList.get(position).getLevelId()));
// notificationIntent.putExtra("categoryID", levelId);
notificationIntent.putExtra("categoryName", adaBankDetailsList.get(position).getGroupName());
notificationIntent.putExtra("limit", 10);
// notificationIntent.putExtra("headerImage", promotionUrl);
startActivity(notificationIntent);
}else if (adaBankDetailsList.get(position).getNotificationLevel().equalsIgnoreCase("reseller")) {
Intent notificationIntent = new Intent(NotificationListActivity.this, BottomNavigationActivity.class);
notificationIntent.putExtra("notificationClick","true");
// notificationIntent.putExtra("notifId",(bnkResponse.getLevelId()));
notificationIntent.putExtra("resell", "Y");
startActivity(notificationIntent);
} else if (adaBankDetailsList.get(position).getNotificationLevel().equalsIgnoreCase("normal")) {
Intent notificationIntent = new Intent(NotificationListActivity.this, MyOrdersActivity.class);
notificationIntent.putExtra("notificationClick","true");
// notificationIntent.putExtra("notifId",(bnkResponse.getLevelId()));
startActivity(notificationIntent);
} else {
Intent notificationIntent = new Intent(NotificationListActivity.this, BottomNavigationActivity.class);
notificationIntent.putExtra("notificationClick","true");
// notificationIntent.putExtra("notifId",(bnkResponse.getLevelId()));
startActivity(notificationIntent);
}
} catch (Exception e) {
Intent notificationIntent = new Intent(NotificationListActivity.this, BottomNavigationActivity.class);
startActivity(notificationIntent);
}
break;
case R.id.iv_arrow:
Glide.with(getApplicationContext())
.load(adaBankDetailsList.get(position).getNotificationImage())
.apply(new RequestOptions()
.placeholder(R.drawable.no_image))
.into(notification_iv);
if(flag==true)
{
notification_main_text.setSingleLine(true);
notification_main_text.setEllipsize(TextUtils.TruncateAt.END);
int n1 = 1; // the exact number of lines you want to display
notification_main_text.setLines(n1);
notification_main_text.setMaxEms(12);
iv_arrow.setImageResource(R.mipmap.down);
notification_iv.setVisibility(View.GONE);
notification_sub_text.setSingleLine(true);
notification_sub_text.setEllipsize(TextUtils.TruncateAt.END);
int n = 1; // the exact number of lines you want to display
notification_sub_text.setLines(n);
flag = false;
}
else if(flag==false)
{
notification_main_text.setSingleLine(false);
int n1 = 2; // the exact number of lines you want to display
notification_main_text.setLines(n1);
notification_main_text.setMaxEms(10);
notification_main_text.setVisibility(View.VISIBLE);
iv_arrow.setImageResource(R.mipmap.up);
notification_sub_text.setVisibility(View.VISIBLE);
if(adaBankDetailsList.get(position).getNotificationImage().equals("null"))
{
notification_iv.setVisibility(View.GONE);
}
else
{
notification_iv.setVisibility(View.VISIBLE);
}
notification_sub_text.setSingleLine(false);
int n = 2; // the exact number of lines you want to display
notification_sub_text.setLines(n);
flag = true;
}
break;
}
}
}
}
Sometime Adapter might cause position issue while scrolling the Recyclerview. You can achieve the same by tag your ImageView into the Button.
holder.your_button.setTag(holder.your_imageview);
holder.your_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final ImageView selImageView = (ImageView) v.getTag();
if(selImageView.getVisibility() == View.VISIBLE) {
selImageView.setVisibility(View.INVISIBLE)
} else {
selImageView.setVisibility(View.VISIBLE)
}
}
});
Above will only trigger your view of the same position. Because we have set that ImageView to your Buttons tag and targeting only that view.
I have an alarm clock application, and I've just added code to exit the program when using the Back button from the main activity. However, when I do so, the last action the user took is undone. For example, if the user creates three alarms, then presses the back button, only two alarms will show up.
This is the Back button code, from Main Activity:
#Override
public void onBackPressed() {
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
And just in case, here's all the code from both activities I'm testing:
MainActivity.java (The only activity that has this Back button functionality, deliberately)
public class MainActivity extends AppCompatActivity {
ListView alarmListView;
ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
AlarmAdapter alarmAdapter;
String filename = "alarmList";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
alarmListView = findViewById(R.id.alarmListView);
// Credit to Mitch Woodbright for helping with this section, and other try/catch blocks.
try
{
ArrayList<Alarm> alarm = (ArrayList<Alarm>) getIntent().getSerializableExtra("alarmList");
for(Alarm elements : alarm){
alarmList.add(elements);
}
writeAlarmList(alarmList);
}
catch (NullPointerException e){
System.out.println("AlarmList is empty.");
}
try {
alarmList = readAlarmList();
}
catch (NullPointerException e) {
}
alarmAdapter = new AlarmAdapter(MainActivity.this, alarmList){
#Override
public void onUpdateClick(int position, ArrayList<Alarm> alarmList) {
super.onUpdateClick(position, alarmList);
Intent updateAlarmIntent = new Intent(MainActivity.this,
CreateAlarmActivity.class);
updateAlarmIntent.putExtra("alarmList", alarmList);
updateAlarmIntent.putExtra("position", position);
startActivity(updateAlarmIntent);
}
};
alarmListView.setAdapter(alarmAdapter);
alarmAdapter.notifyDataSetChanged();
alarmListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent updateAlarmIntent = new Intent(MainActivity.this, CreateAlarmActivity.class);
updateAlarmIntent.putExtra("alarmList", alarmList);
updateAlarmIntent.putExtra("position", position);
startActivity(updateAlarmIntent);
}
});
// writeAlarmList(alarmList);
}
protected void onStart() {
super.onStart();
alarmList = readAlarmList();
}
protected void onResume() {
super.onResume();
alarmList = readAlarmList();
}
protected void onPause() {
super.onPause();
writeAlarmList(alarmList);
}
protected void onStop() {
super.onStop();
writeAlarmList(alarmList);
}
#Override
public void onBackPressed() {
// Thanks to Mitch for this line.
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
// Create alarm when user presses FAB on activity_main.xml.
public void createNewAlarm(View view) {
Intent createAlarmIntent = new Intent(this, CreateAlarmActivity.class);
createAlarmIntent.putExtra("alarmList", alarmList);
startActivity(createAlarmIntent);
}
public void testAlarmActivated(View view){
//Intent activateAlarmIntent = new Intent(this, AlarmActivatedActivity.class);
//startActivity(activateAlarmIntent);
while(alarmList.size() > 0){
alarmList.remove(0);
}
Intent deleteEverythingIntent = new Intent(MainActivity.this, MainActivity.class);
deleteEverythingIntent.putExtra("alarmList", alarmList);
startActivity(deleteEverythingIntent);
}
public void writeAlarmList(ArrayList<Alarm> alarmList){
try {
FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(alarmList);
oos.close();
}
catch (FileNotFoundException e){
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
public ArrayList<Alarm> readAlarmList(){
try {
FileInputStream fis = openFileInput(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
ArrayList<Alarm> alarmList = (ArrayList<Alarm>) ois.readObject();
ois.close();
return alarmList;
}
catch (FileNotFoundException e) {
ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
System.out.println("File not found. Making empty list.");
return alarmList;
}
catch (IOException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (NullPointerException e) {
ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
System.out.println("Null pointer exception. Making empty list.");
return alarmList;
}
ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
return alarmList;
}
}
CreateAlarmActivity.java (The activity which does the creating/updating/deleting of alarms)
public class CreateAlarmActivity extends AppCompatActivity {
// If the alarm is being created, position = -1.
int position = -1;
int alarmHour;
int alarmMinute;
boolean isPm;
int snoozeTimer;
int[] daysActive;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_alarm);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
alarmList = (ArrayList<Alarm>)getIntent().getSerializableExtra("alarmList");
try {
// If we're updating an alarm, return the position of the alarm to update.
position = (int)getIntent().getSerializableExtra("position");
}
// Else, keep going.
catch (NullPointerException e){
}
Button hourButton = findViewById(R.id.buttonHours);
Button minuteButton = findViewById(R.id.buttonMinutes);
Button isPmButton = findViewById(R.id.buttonAmPm);
Button snoozeTimerButton = findViewById(R.id.buttonSnoozeTimer);
Button sundayButton = findViewById(R.id.buttonSunday);
Button mondayButton = findViewById(R.id.buttonMonday);
Button tuesdayButton = findViewById(R.id.buttonTuesday);
Button wednesdayButton = findViewById(R.id.buttonWednesday);
Button thursdayButton = findViewById(R.id.buttonThursday);
Button fridayButton = findViewById(R.id.buttonFriday);
Button saturdayButton = findViewById(R.id.buttonSaturday);
// If creating a new alarm, initialise data as default.
if (position == -1){
alarmHour = 6;
alarmMinute = 0;
isPm = false;
snoozeTimer = 10;
daysActive = new int[] {0, 0, 0, 0, 0, 0, 0};
}
// If updating an alarm, grab the defaults we already had.
else {
Alarm tempAlarm = alarmList.get(position);
alarmHour = tempAlarm.hour;
alarmMinute = tempAlarm.minute;
isPm = tempAlarm.isPm;
snoozeTimer = tempAlarm.snoozeTimer;
daysActive = tempAlarm.daysActive;
}
// Set buttons to what they should be.
hourButton.setText(Integer.toString(alarmHour));
snoozeTimerButton.setText(Integer.toString(snoozeTimer));
if (alarmMinute < 10){
minuteButton.setText("0" + Integer.toString(alarmMinute));
}
else {
minuteButton.setText(Integer.toString(alarmMinute));
}
if (!isPm){
isPmButton.setText("am");
}
else {
isPmButton.setText("pm");
}
setDayColor(sundayButton, daysActive[0]);
setDayColor(mondayButton, daysActive[1]);
setDayColor(tuesdayButton, daysActive[2]);
setDayColor(wednesdayButton, daysActive[3]);
setDayColor(thursdayButton, daysActive[4]);
setDayColor(fridayButton, daysActive[5]);
setDayColor(saturdayButton, daysActive[6]);
}
ArrayList<Alarm> alarmList = new ArrayList<Alarm>();
// Add one to the hour of the alarm.
public void changeHour(View view) {
Button btn = findViewById(R.id.buttonHours);
if (alarmHour == 12){
alarmHour = 0;
}
else {
alarmHour++;
}
btn.setText(Integer.toString(alarmHour));
}
// Add one to the minute of the alarm.
public void changeMinute(View view) {
Button btn = findViewById(R.id.buttonMinutes);
if (alarmMinute == 59) {
alarmMinute = 0;
}
else {
alarmMinute++;
}
if (alarmMinute < 10) {
// Ensure minute 1 becomes 01, e.g, 6:01 am.
btn.setText("0" + Integer.toString(alarmMinute));
}
else {
btn.setText(Integer.toString(alarmMinute));
}
}
public void changeAmPm(View view) {
Button btn = findViewById(R.id.buttonAmPm);
if (isPm == true) {
isPm = false;
btn.setText("am");
}
else {
isPm = true;
btn.setText("pm");
}
}
public void changeSnoozeTimer(View view) {
Button btn = findViewById(R.id.buttonSnoozeTimer);
if (snoozeTimer == 15){
snoozeTimer = 1;
}
else {
snoozeTimer++;
}
btn.setText(Integer.toString(snoozeTimer));
}
public void finishAlarm(View view){
EditText alarmName = findViewById(R.id.alarmName);
String name = alarmName.getText().toString();
Alarm alarm = new Alarm(name, alarmHour, alarmMinute, isPm, daysActive, snoozeTimer);
// If we're creating an alarm.
if (position == -1) {
try {
alarmList.add(alarm);
} catch (Exception e) {
}
}
// Else, we're updating one.
else {
try {
// Set the alarm we're updating to the new alarm.
alarmList.set(position, alarm);
} catch (Exception e) {
}
}
Intent finishAlarmIntent = new Intent(this, MainActivity.class);
finishAlarmIntent.putExtra("alarmList", alarmList);
startActivity(finishAlarmIntent);
}
public void cancelAlarm(View view){
Intent cancelAlarmIntent = new Intent(this, MainActivity.class);
cancelAlarmIntent.putExtra("alarmList", alarmList);
startActivity(cancelAlarmIntent);
}
public void deleteAlarm(View view) {
// If creating a new alarm, deleting is the same as cancelling.
if (position == -1) {
Intent cancelAlarmIntent = new Intent(this, MainActivity.class);
cancelAlarmIntent.putExtra("alarmList", alarmList);
startActivity(cancelAlarmIntent);
}
else {
// Remove the alarm.
alarmList.remove(position);
Intent cancelAlarmIntent = new Intent(this, MainActivity.class);
cancelAlarmIntent.putExtra("alarmList", alarmList);
startActivity(cancelAlarmIntent);
}
}
public void changeSunday(View view) {
Button btn = findViewById(R.id.buttonSunday);
daysActive[0] = switchDay(daysActive[0]);
setDayColor(btn, daysActive[0]);
}
public void changeMonday(View view) {
Button btn = findViewById(R.id.buttonMonday);
daysActive[1] = switchDay(daysActive[1]);
setDayColor(btn, daysActive[1]);
}
public void changeTuesday(View view) {
Button btn = findViewById(R.id.buttonTuesday);
daysActive[2] = switchDay(daysActive[2]);
setDayColor(btn, daysActive[2]);
}
public void changeWednesday(View view) {
Button btn = findViewById(R.id.buttonWednesday);
daysActive[3] = switchDay(daysActive[3]);
setDayColor(btn, daysActive[3]);
}
public void changeThursday(View view) {
Button btn = findViewById(R.id.buttonThursday);
daysActive[4] = switchDay(daysActive[4]);
setDayColor(btn, daysActive[4]);
}
public void changeFriday(View view) {
Button btn = findViewById(R.id.buttonFriday);
daysActive[5] = switchDay(daysActive[5]);
setDayColor(btn, daysActive[5]);
}
public void changeSaturday(View view) {
Button btn = findViewById(R.id.buttonSaturday);
daysActive[6] = switchDay(daysActive[6]);
setDayColor(btn, daysActive[6]);
}
// Helper method to switch the daysActive from 0 to 1 or from 1 to 0.
public int switchDay(int day) {
if (day == 0){
return 1;
}
return 0;
}
// Helper method to set the color of a daysActive button when updating the alarm.
public void setDayColor(Button btn, int day) {
if (day == 1) {
// Source: https://stackoverflow.com/questions/2173936/how-to-set-background-color-of-a-view
// Credit goes to EddieB for the below line.
btn.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);
} else {
// Source: https://stackoverflow.com/questions/14802354/how-to-reset-a-buttons-background-color-to-default
// Credit goes to Ivo for the below line.
btn.getBackground().clearColorFilter();
}
}
}
For people from the future:
I ended up solving this by using the following:
#Override
public void onBackPressed() {
this.finishAffinity();
}
Source: How to quit android application programmatically
I am building a simple downloader app, with a pause/resume button. When I click on pause button and kill the app the download progress isn't shown anymore, after I open the app again. I want to save the download progress state even if the app is killed. Can anyone help me with this? I'm building the app using download manager pro library from github.
here's the code:
Activity Class:
public class MainActivity extends AppCompatActivity {
String[] permissions = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 100;
EditText edt_url;
Button btn_download;
TextView fileNametv, ProgressbarTv;
private MyDownloadService mService;
ProgressBar progressBar;
String filename, url;
/* UrlFileNameListener listener;*/
Integer progress;
MyReceiver receiver;
public static MainActivity instance;
/* RecyclerView recyclerView;
List<Model> downloadList;
LinearLayoutManager manager;
DownloadAdapter adapter;
// ImageView pausebtn;
int position;*/
File myDirectory;
Boolean mBound = false;
Button pause_btn;
int tasktoken;
/* Model model;
Parcelable mListState;
private final String KEY_RECYCLER_STATE = "recycler_state";
private final String KEY_LIST_STATE = "list_state";*/
private ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
mBound = true;
MyDownloadService.LocalBinder localBinder = (MyDownloadService.LocalBinder) iBinder;
mService = localBinder.getService();
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mBound = false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* if(savedInstanceState!=null){
mListState = savedInstanceState.getParcelable(KEY_RECYCLER_STATE);
downloadList =savedInstanceState.getParcelableArrayList(KEY_LIST_STATE);
} */
setContentView(R.layout.activity_main);
edt_url = findViewById(R.id.edt_url);
btn_download = findViewById(R.id.btn_download);
pause_btn = findViewById(R.id.pause_resume);
/*recyclerView = findViewById(R.id.recycler_view);
downloadList = new ArrayList<>();
manager = new LinearLayoutManager(this);
adapter = new DownloadAdapter(downloadList, this);
recyclerView.setLayoutManager(manager);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
manager.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);
recyclerView.setAdapter(adapter);*/
fileNametv = findViewById(R.id.download_file_name);
ProgressbarTv = findViewById(R.id.progress_tv);
progressBar = findViewById(R.id.download_progress);
// pausebtn = findViewById(R.id.pause_resume);
instance = this;
/* if (progress!= null && filename != null) {
savedInstanceState.putInt("progress", progress);
savedInstanceState.putString("filename",filename);
// savedInstanceState.putString("filename", model.getFileName());
// savedInstanceState.putParcelable("list",mListState);
}*/
receiver = new MyReceiver();
btn_download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getDownloadProcess();
}
});
pause_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mService.pauseDownload(tasktoken);
}
});
LocalBroadcastManager.getInstance(this)
.registerReceiver(receiver,
new IntentFilter("download"));
if (checkAndRequestPermissions()) {
myDirectory = new File(Environment.getExternalStorageDirectory() + "/" + "RITSDownloads2");
if (!myDirectory.exists()) {
myDirectory.mkdir();
}
}
}
#Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this,MyDownloadService.class);
bindService(intent,mServiceConnection,Context.BIND_AUTO_CREATE);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("progress", progress);
outState.putString("filename",filename);
/* mListState = manager.onSaveInstanceState();
outState.putParcelable(KEY_RECYCLER_STATE,mListState);
outState.putParcelableArrayList(KEY_LIST_STATE, (ArrayList<? extends Parcelable>) adapter.getDownloadList());*/
}
#Override
protected void onPause() {
super.onPause();
//mListState = manager.onSaveInstanceState();
}
#Override
protected void onResume() {
super.onResume();
// manager.onRestoreInstanceState(mListState);
}
#Override
public void onBackPressed() {
progress = progressBar.getProgress();
super.onBackPressed();
}
/* #Override
public void onRestoreInstanceState(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onRestoreInstanceState(savedInstanceState, persistentState);
manager.onRestoreInstanceState(mListState);
savedInstanceState.getParcelable(KEY_RECYCLER_STATE);
savedInstanceState.getParcelableArrayList(KEY_LIST_STATE);
}
*/
private void getDownloadProcess() {
url = edt_url.getText().toString();
filename = URLUtil.guessFileName(url, null, null);
//listener.setUrl(url,filename);
edt_url.setText("");
/* model = new Model();
model.setFileName(filename);
downloadList.add(model);
adapter.notifyDataSetChanged();*/
fileNametv.setText(filename);
Intent intent = new Intent(MainActivity.this, MyDownloadService.class);
intent.putExtra("filename", filename);
intent.putExtra("url", url);
intent.setAction(DownloadActions.ACTION.Download_ACTION);
startService(intent);
}
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
progress = intent.getIntExtra("progress", 1);
ReportStructure reportStructure = MyDownloadService.downloadManagerPro.singleDownloadStatus(intent.getIntExtra("tasktoken",1));
tasktoken = intent.getIntExtra("tasktoken",1);
// model.setProgress(progress);
/*int position = downloadList.indexOf(model);
DownloadAdapter.DownloadHolder holder = getDownloadHolder(position);
holder.progressBar.setProgress(progress);*/
progressBar.setProgress(progress);
}
}
/* public DownloadAdapter.DownloadHolder getDownloadHolder(int position) {
return (DownloadAdapter.DownloadHolder) recyclerView.findViewHolderForLayoutPosition(position);
}
*/
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
savedInstanceState.getInt("progress");
savedInstanceState.getString("filename");
/* Log.d("savedInstancestate",savedInstanceState.toString());
//savedInstanceState.getInt("position");
if(savedInstanceState!=null){
List<Model> downloadList = savedInstanceState.getParcelableArrayList(KEY_LIST_STATE);
adapter = new DownloadAdapter(downloadList,this);
}
*/
}
private boolean checkAndRequestPermissions() {
if (ContextCompat.checkSelfPermission(this, permissions[0]) != PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this, permissions[1]) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, permissions, REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String permissions[], #NonNull int[] grantResults) {
String TAG = "LOG_PERMISSION";
Log.d(TAG, "Permission callback called-------");
switch (requestCode) {
case REQUEST_ID_MULTIPLE_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<>();
// Initialize the map with both permissions
perms.put(this.permissions[0], PackageManager.PERMISSION_GRANTED);
perms.put(this.permissions[1], PackageManager.PERMISSION_GRANTED);
// Fill with actual results from user
if (grantResults.length > 0) {
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
// Check for both permissions
if (perms.get(this.permissions[0]) == PackageManager.PERMISSION_GRANTED
&& perms.get(this.permissions[1]) == PackageManager.PERMISSION_GRANTED
) {
Log.d(TAG, "Phone state and storage permissions granted");
// process the normal flow
//else any one or both the permissions are not granted
//TODO Do your stuff here after permissions granted
} else {
Log.d(TAG, "Some permissions are not granted ask again ");
//permissions is denied (this is the first time, when "never ask again" is not checked) so ask again explaining the usage of permissions
// //shouldShowRequestPermissionRationale will return true
//show the dialog or snackbar saying its necessary and try again otherwise proceed with setup.
if (ActivityCompat.shouldShowRequestPermissionRationale(this, this.permissions[0]) ||
ActivityCompat.shouldShowRequestPermissionRationale(this, this.permissions[1])) {
showDialogOK("Phone state and storage permissions required for this app",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
checkAndRequestPermissions();
break;
case DialogInterface.BUTTON_NEGATIVE:
// proceed with logic by disabling the related features or quit the app.
break;
}
}
});
}
//permissions is denied (and never ask again is checked)
//shouldShowRequestPermissionRationale will return false
else {
Toast.makeText(this, "Go to settings and enable permissions", Toast.LENGTH_LONG)
.show();
//proceed with logic by disabling the related features or quit the app.
}
}
}
}
}
}
private void showDialogOK(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", okListener)
.create()
.show();
}
}
Service Class:
public class MyDownloadService extends Service implements DownloadManagerListener {
private static final String LOG_TAG = "tag";
public static DownloadManagerPro downloadManagerPro;
File myDirectory;
int taskToken;
String name;
Intent notificationIntent;
Notification notification;
PendingIntent pendingIntent;
private IBinder binder = new LocalBinder();
#Nullable
#Override
public IBinder onBind(Intent intent) {
return binder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals(DownloadActions.ACTION.Download_ACTION)) {
Log.d(LOG_TAG, "Received Start Foreground Intent");
}
name = intent.getStringExtra("filename");
final String url = intent.getStringExtra("url");
Log.d(LOG_TAG, name);
Log.d(LOG_TAG, url);
downloadManagerPro = new DownloadManagerPro(this.getApplicationContext());
downloadManagerPro.init("RITSDownloads2/", 16, this);
myDirectory = new File(Environment.getExternalStorageDirectory() + "/" + "RITSDownloads2");
if (!myDirectory.exists()) {
myDirectory.mkdir();
}
taskToken = downloadManagerPro.addTask(name, url, 16, true, true);
Log.d(LOG_TAG, String.valueOf(taskToken));
try {
downloadManagerPro.startDownload(taskToken);
notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setAction(DownloadActions.ACTION.Download_ACTION);
pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notification = new NotificationCompat.Builder(this)
.setContentTitle("Downloading")
.setTicker("Rits Download")
.setContentText(name)
.setSmallIcon(android.R.drawable.stat_sys_download)
.setContentIntent(pendingIntent)
.setOngoing(true)
.build();
startForeground(DownloadActions.NOTIFICATION_ID.FOREGROUND_SERVICE,
notification);
// stopForeground(true);
// stopSelf();
} catch (IOException e) {
e.printStackTrace();
}
return START_STICKY;
}
#Override
public void OnDownloadStarted(long taskId) {
Log.d(LOG_TAG, "DownloadStarted");
}
#Override
public void OnDownloadPaused(long taskId) {
}
#Override
public void onDownloadProcess(long taskId, double percent, long downloadedLength) {
final int progress = (int) percent;
final int taskToken = (int) taskId;
// int position = positions.get(taskToken);
notification = new NotificationCompat.Builder(this)
.setContentTitle("Downloading")
.setTicker("Rits Download")
.setContentText(name)
.setSmallIcon(android.R.drawable.stat_sys_download)
.setContentIntent(pendingIntent)
.setOngoing(true)
.setColor(ContextCompat.getColor(this, R.color.colorPrimary))
.setProgress(100, progress, false)
.build();
startForeground(DownloadActions.NOTIFICATION_ID.FOREGROUND_SERVICE,
notification);
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("progress", progress);
intent.setAction("download");
intent.putExtra("tasktoken",taskToken);
ReportStructure structure = downloadManagerPro.singleDownloadStatus(taskToken);
String name =structure.name;
intent.putExtra("name",name);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}
#Override
public void OnDownloadFinished(long taskId) {
}
#Override
public void OnDownloadRebuildStart(long taskId) {
}
#Override
public void OnDownloadRebuildFinished(long taskId) {
}
public void pauseDownload(int taskToken){
ReportStructure reportStructure = downloadManagerPro.singleDownloadStatus(taskToken);
if(reportStructure.state == TaskStates.DOWNLOADING){
downloadManagerPro.pauseDownload(taskToken);
} else if(reportStructure.state == TaskStates.PAUSED){
try {
downloadManagerPro.startDownload(taskToken);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void OnDownloadCompleted(long taskId) {
Log.d(LOG_TAG, "Download Complete");
/* MainActivity.instance.pausebtn.post(new Runnable() {
#Override
public void run() {
MainActivity.instance.pausebtn.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_done));
}
});*/
notification = new NotificationCompat.Builder(this)
.setContentTitle("Download Complete")
.setTicker("Rits Download")
.setContentText(name)
.setSmallIcon(R.drawable.ic_action_done)
.setContentIntent(pendingIntent)
.setOngoing(true)
.setColor(ContextCompat.getColor(this, R.color.colorPrimary))
.build();
startForeground(DownloadActions.NOTIFICATION_ID.FOREGROUND_SERVICE,
notification);
}
#Override
public void connectionLost(long taskId) {
}
#Override
public void onTaskRemoved(Intent rootIntent) {
/* Intent restartService = new Intent(getApplicationContext(),this.getClass());
restartService.setPackage(getPackageName());
PendingIntent restartPendingIntent =PendingIntent.getService(getApplicationContext(), 1,restartService, PendingIntent.FLAG_ONE_SHOT);
AlarmManager myAlarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
myAlarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartPendingIntent);*/
}
public class LocalBinder extends Binder{
public MyDownloadService getService(){
return MyDownloadService.this;
}
}
}
I don't know how you want to save the state but I do know that an activity has a onStop() method that you can override.
The onStop() method runs when the app is killed so I would imagine you would want to do your "saving" in this method.
As for saving something I believe you would want to use the SharedPreferences class. You can find more information about that here.
You can find the lifecycle of an activity here
hope this helps
Save the progress on SharedPreferences onDestroy() and retrieve it from there when activity is created.
Cache:
#Override
protected void onDestroy() {
super.onDestroy();
SharedPreferences sharedPreferences = getSharedPreferences("space_name", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("progress", progress).apply();
}
And retrieve:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPreferences = getSharedPreferences("space_name", MODE_PRIVATE);
progress = sharedPreferences.getInt("progress", 0); // 0 default value in case is empty
}
I created an Android app that can downloading file.
I used Groundy library to support the service. And I created the NotiThread from this (but I edited it for support my requirement)..
Here is my Activity code ...
public class PacksActivity extends Activity {
private Context context;
private RelativeLayout download;
private ProgressBar progressBar;
private NotiThread notification;
private String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.packs);
context = this;
url = getIntent().getStringExtra("URL");
progressBar = (ProgressBar)findViewById(R.id.progress);
progressBar.setIndeterminate(false);
progressBar.setMax(100);
download = (RelativeLayout) findViewById(R.id.label_circle);
download.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
File dest = new File(context.getFilesDir(), new File(url).getName());
if(!dest.exists()){
progressBar.setVisibility(View.VISIBLE);
notification = new NotiThread(context);
notification.run();
Bundle extras = new Bundler().add(DownloadTemplate.PARAM_URL, url).build();
Groundy.create(context, DownloadTemplate.class)
.receiver(mReceiver)
.params(extras)
.queue();
}
}
});
}
private ResultReceiver mReceiver = new ResultReceiver(new Handler()) {
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
switch (resultCode) {
case Groundy.STATUS_PROGRESS:
int progress = resultData.getInt(Groundy.KEY_PROGRESS);
progressBar.setProgress(progress);
if((progress % 10) == 0)notification.progressUpdate(progress);
break;
case Groundy.STATUS_FINISHED:
Toast.makeText(context, "Success Download file", Toast.LENGTH_LONG);
progressBar.setVisibility(View.GONE);
notification.completed();
break;
case Groundy.STATUS_ERROR:
Toast.makeText(context, resultData.getString(Groundy.KEY_ERROR), Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
notification.completed();
break;
}
}
};
}
This is my NotiThread class
public class NotiThread extends Thread {
private NotificationManager mNoti = null;
private final Context mContext;
private final int mUnique;
private Notification noti;
public NotiThread(Context context) {
super("NotiThread");
mContext = context;
mNoti = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mUnique = 1;
}
#Override
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
noti = new Notification(R.drawable.icon1024, "title", System.currentTimeMillis());
noti.flags |= Notification.FLAG_ONGOING_EVENT;
RemoteViews contentView = new RemoteViews(mContext.getPackageName(), R.layout.custom_notification);
contentView.setTextViewText(R.id.noti_title, "title");
contentView.setProgressBar(R.id.noti_progress, 100, 0, false);
contentView.setTextViewText(R.id.noti_text, "0%");
noti.contentView = contentView;
noti.contentIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext, mContext.getClass()), PendingIntent.FLAG_ONE_SHOT);
mNoti.notify(mUnique, noti);
}
public void progressUpdate(int percentageComplete) {
noti.contentView.setProgressBar(R.id.noti_progress, 100, percentageComplete, false);
noti.contentView.setTextViewText(R.id.noti_text, percentageComplete + "%");
mNoti.notify(mUnique, noti);
}
public void completed() {
mNoti.cancel(mUnique);
}
}
And this is GroundyTask class
public class DownloadTemplate extends GroundyTask {
public static final String PARAM_URL = "com.app.service.PARAM_URL";
#Override
protected boolean doInBackground() {
try {
String url = getParameters().getString(PARAM_URL);
File dest = new File(getContext().getFilesDir(), new File(url).getName());
DownloadUtils.downloadFile(getContext(), url, dest, DownloadUtils.getDownloadListenerForTask(this));
return true;
} catch (Exception e) {
return false;
}
}
}
I want to ask, how to resume activity to update the ProgressBar from the current running service when enter to the activity and from notification?
You can check if the service is still running when coming back to your activity. How I do it is I use a singleton Network class. Here I define the callback object that is used in the Groundy create function. This singleton also keeps track of the state of the task (running, or not running when cancelled, finished or failed). When the activity is created again, this singleton class still exists so the progress callback is still being fired. The only thing you need to make sure is to re-register your listeners from the new activity to the existing singleton. Here's a simple example..
Singleton class:
public static SingletonClass getInstance(Object o) {
if (instance == null) {
instance = new SingletonClass();
}
if (o instanceof OnProgressListener) {
progressListener = (OnProgressListener) o;
}
...
return instance;
}
Callback object:
public Object callbackObject = new Object() {
#OnProgress(YourGroundyTask.class)
public void onProgress(#Param(Groundy.PROGRESS) int progress) {
if (progressListener != null){
progressListener.onDownloadProgress(progress);
}
}
...
I have a some thread that opens progress dialog and downloads a file. While thread downloads the file, it update progress bar. But if progress dialog was hidden, thread creates a notification and updating progress bar in the notification. I wanna make this: when user click on the notification, Android opens Activity and showing progress dialog.
How can I do this?
That is my method that downloading a file:
public void downloadAction(int id) {
if(id<0 || id>data.length) { IO.showNotify(MusicActivity.this, getResources().getStringArray(R.array.errors)[4]); return; }
final int itemId = id;
AsyncTask<Void, Integer, Boolean> downloadTask = new AsyncTask<Void, Integer, Boolean>() {
ProgressDialog progressDialog = new ProgressDialog(MusicActivity.this);
String error = null;
int nId = -1;
int progressPercent = 0;
boolean notificated = false;
int urlFileLength;
String FILE_NAME = fileName(data.getName(itemId));
#Override
protected void onPreExecute() {
progressDialog.setTitle(data.getName(itemId));
progressDialog.setIndeterminate(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(true);
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
cancel(true);
}
});
progressDialog.setButton(Dialog.BUTTON_POSITIVE, getResources().getString(R.string.hide), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
progressDialog.hide();
}
});
progressDialog.setButton(Dialog.BUTTON_NEGATIVE, getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if(progressDialog.isShowing()) { cancel(true); progressDialog.dismiss();}
}
});
progressDialog.show();
progressDialog.setProgressNumberFormat("");
}
#Override
protected Boolean doInBackground(Void... params) {
int localFileLength, len;
int fullProgress = 0;
byte[] bytes = new byte[1024];
File rootDir = new File(PATH);
if(!rootDir.isDirectory()) rootDir.mkdir();
try {
URLConnection urlConnection = new URL(data.getUrl(itemId)).openConnection();
urlConnection.setConnectTimeout(20000);
urlConnection.setReadTimeout(60000);
localFileLength = (int) new File(FILE_NAME).length();
urlFileLength = urlConnection.getContentLength();
if (urlFileLength == 169 || urlFileLength == 0 || urlFileLength == -1) {
error = getResources().getStringArray(R.array.errors)[5];
return false;
}
if (urlFileLength == localFileLength) {
error = getResources().getString(R.string.file_exist);
return false;
} else {
publishProgress(0, urlFileLength);
InputStream in = urlConnection.getInputStream();
OutputStream out = new FileOutputStream(FILE_NAME);
while((len=in.read(bytes))!=-1) {
if(!isCancelled()) {
out.write(bytes, 0, len);
fullProgress += len;
publishProgress(fullProgress);
} else {
new File(FILE_NAME).delete();
error = getResources().getString(R.string.stopped);
return false;
}
}
}
} catch (MalformedURLException e) {
new File(FILE_NAME).delete();
error = getResources().getStringArray(R.array.errors)[2];
} catch (IOException e) {
new File(FILE_NAME).delete();
error = getResources().getStringArray(R.array.errors)[3];
}
return true;
}
#Override
protected void onProgressUpdate(Integer ... progress) {
int tmp;
if (progress.length==2) {
progressDialog.setProgress(progress[0]);
progressDialog.setMax(progress[1]);
} else if(progress.length==1) {
if(!progressDialog.isShowing()) {
if(!notificated) {
nId = NotificationUtils.getInstace(MusicActivity.this).createDownloadNotification(data.getName(itemId));
notificated = true;
} else {
tmp = (int) (progress[0]/(urlFileLength*0.01));
if(progressPercent!=tmp) {
progressPercent = tmp;
NotificationUtils.getInstace(MusicActivity.this).updateProgress(nId, progressPercent);
}
}
} else {
progressDialog.setProgress(progress[0]);
}
}
}
#Override
protected void onPostExecute(Boolean result) {
if(result==true && error == null) {
if(progressDialog.isShowing()) {
IO.showNotify(MusicActivity.this, getResources().getString(R.string.downloaded) + " " + PATH);
progressDialog.dismiss();
} else if (nId!=-1) {
NotificationUtils.getInstace(MusicActivity.this).cancelNotification(nId);
NotificationUtils.getInstace(MusicActivity.this).createMessageNotification(data.getName(itemId) + " " + getResources().getString(R.string.finished));
}
} else {
if(progressDialog.isShowing()) {
IO.showNotify(MusicActivity.this, error);
progressDialog.dismiss();
} else if (nId!=-1){
NotificationUtils.getInstace(MusicActivity.this).cancelNotification(nId);
NotificationUtils.getInstace(MusicActivity.this).createMessageNotification(getResources().getString(R.string.error) + "! " + error);
}
}
}
#Override
protected void onCancelled() {
IO.showNotify(MusicActivity.this, getResources().getString(R.string.stopped));
}
};
if(downloadTask.getStatus().equals(AsyncTask.Status.PENDING) || downloadTask.getStatus().equals(AsyncTask.Status.FINISHED))
downloadTask.execute();
}
And that is two methods thats creating notification:
public int createDownloadNotification(String fileName) {
String text = context.getString(R.string.notification_downloading).concat(" ").concat(fileName);
RemoteViews contentView = createProgressNotification(text, text);
contentView.setImageViewResource(R.id.notification_download_layout_image, android.R.drawable.stat_sys_download);
return lastId++;
}
private RemoteViews createProgressNotification(String text, String topMessage) {
Notification notification = new Notification(android.R.drawable.stat_sys_download, topMessage, System.currentTimeMillis());
RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.notification_download_layout);
contentView.setProgressBar(R.id.notification_download_layout_progressbar, 100, 0, false);
contentView.setTextViewText(R.id.notification_download_layout_title, text);
notification.contentView = contentView;
notification.flags = Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT | Notification.FLAG_ONLY_ALERT_ONCE;
Intent notificationIntent = new Intent(context, NotificationUtils.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.contentIntent = contentIntent;
manager.notify(lastId, notification);
notifications.put(lastId, notification);
return contentView;
}
Help me please...
I am not sure, but in my code of notification I have no notification.contentIntent = contentIntent; and you seem to be missing this before the manager.notify(lastId, notification); line:
notification.setLatestEventInfo(context, MyNotifyTitle, MyNotifiyText, contentIntent );
MyNotifyTitle is the Title of the Notification, MyNotifyText is the text. Add them before the contentIntent as
MyIntent.putExtra("extendedTitle", notificationIntent );
MyIntent.putExtra("extendedText" , notificationIntent );
Hope this helps.