Chip (s) are compact elements that represent an attribute, text, entity, or action. They allow users to enter information, select a choice, filter content, or trigger an action.
Chip manages its own start (app:chipIcon) and end (app:closeIcon) drawables. Picasso allows for hassle-free image loading . Normal case picasso load images and that image is converted to drawable for Icon. Which works only if image is already cached. Otherwise the resulting icon is placeholder image or error image.By using trigger a callback is created which will get the image and place it.It only works by using setTag, With out “setTag” trigger get garbage collected.
A ChipGroup is used to hold multiple Chips. By default, the chips are reflowed across multiple lines. Set the app:singleLine attribute to constrain the chips to a single horizontal line. If you do so, you’ll usually want to wrap this ChipGroup in a HorizontalScrollView.
ChipGroup also supports a multiple-exclusion scope for a set of chips. When you set the app:singleSelection attribute, checking one chip that belongs to a chip-group unchecks any previously checked chip within the same group. The behavior mirrors that of RadioGroup.
MainActivity
public class MainActivity extends AppCompatActivity {
private LinkedHashMap<String, Target> chipRecordHash;
private ChipGroup chipGroup;
private String [] nameList={"Google","Android","Windows","Chrome","Git hub","Facebook"};
private String [] iconList={"https://cdn2.iconfinder.com/data/icons/social-icons-33/128/Google-512.png",
"https://cdn2.iconfinder.com/data/icons/social-icons-33/128/Android-512.png",
"https://cdn1.iconfinder.com/data/icons/logotypes/32/windows-512.png",
"https://cdn1.iconfinder.com/data/icons/smallicons-logotypes/32/chrome-512.png",
"https://cdn0.iconfinder.com/data/icons/octicons/1024/mark-github-512.png",
"https://cdn1.iconfinder.com/data/icons/logotypes/32/square-facebook-512.png"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
chipGroup=findViewById(R.id.chipGroup);
intChips();
MaterialButton remove=findViewById(R.id.remove);
remove.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
removeChip("Facebook");
}
});
}
private void intChips(){
chipRecordHash=new LinkedHashMap<>();
for (int i=0;i<nameList.length;i++) {
final Chip chip = new Chip(this, null, R.style.Widget_MaterialComponents_Chip_Action);
chip.setText(nameList[i]);
chip.setCloseIconVisible(true);
chipGroup.addView(chip);
final int finalI = i;
chip.setOnCloseIconClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
chipGroup.removeView(chip);
chipRecordHash.remove(nameList[finalI]);
}
});
Target target=getTargetOfPicasso(chip);
String linkOfIcon=iconList[i];
Picasso.get().load(linkOfIcon).error(R.drawable.icon_no_image).
placeholder(R.drawable.icon_place_holder).
transform(new CircleTransform()).resize(30,30).into(target);
chip.setTag(target);
// --- setting target as tag is in-case the images is not loaded the target get garbage collected
// setTaging the target prevent it from garbage collecting
chipRecordHash.put(nameList[i],target);
//If you want to remove some chips threw another ways like button click etc
}
}
private Target getTargetOfPicasso(final Chip targetChip){
return new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
Drawable d = new BitmapDrawable(getResources(), bitmap);
targetChip.setChipIcon(d);
}
@Override
public void onBitmapFailed(Exception e, Drawable errorDrawable) {
targetChip.setChipIcon(errorDrawable);
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
targetChip.setChipIcon(placeHolderDrawable);
}
};
}
private void removeChip(String chipName){
Chip chip=chipGroup.findViewWithTag(chipRecordHash.get(chipName));
if (chip!=null) {
chipGroup.removeView(chip);
chipRecordHash.remove(chipName);
}else {
Toast.makeText(this,"Not available",Toast.LENGTH_SHORT).show();
}
}
}
Bottom App Bar is introduced in material theme-2( check usage in material.io). The main advantage of bottom bar is it’s positioning bottom of the screen.You can use it with the default drawer-layout or with bottom sheet(You can check here). Both work flawlessly with bottom bar. In order to make the look and feel great of the app we are using bottom sheet.
Adding Bottom App Bar
First step is to add the Bottom App Bar to the layout in order to use this App Bar. The project must be converted to AndroidX (Option for this is available in Refactor menu in Android Studio. Add below code to your xml.
Normally added option menus are not visible on the bottom bar, You need to set it by making the bottom bar as the default toolbar.Below code will help you achieve that.
Creating custom PDF using iText, iText Software is a global specialist in PDF. As a PDF library, it can be embedded into document solution workflows in industries such as; Legal, Finance, Governance, IT, Operations and more.We are using iText 5 here you can check there examples here.
The output is something like the image shown below.
Conversion from array-list to PDF document took place in MainActivity. The array-list are provided by Const.java class Footer is created using HeaderFooter.java class. First we need to provide the location of the file in order to save it, run-time permission is required for accessing the storage of the device. This example shows a list of objects and the goal is to make PDF out of that list. We used table ( PdfPTable ) to arrange the contents to ensure the correct look and feel there are lot of other objects available for arranging contents to choose from. Different types of paper sizes are available also in the library, here it’s A4 because it’s the most common size used for billing . You can also include custom fonts to make the PDF more appealing to the user. In this example we used custom fonts and images to change the look and feel of the PDF.
screenshots
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerMoney;
private ListAdapter listAdapter;
private ArrayList listItems;
private SwipeRefreshLayout swipeMoney;
private MaterialButton buttonPdf;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
swipeMoney=findViewById(R.id.swipeMoney);
recyclerMoney=findViewById(R.id.recyclerMoney);
buttonPdf=findViewById(R.id.buttonPdf);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
recyclerMoney.setHasFixedSize(true);
recyclerMoney.setLayoutManager(new LinearLayoutManager(this));
swipeMoney.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
swipeMoney.setRefreshing(true);
loadItems();
}
});
swipeMoney.setRefreshing(true);
loadItems();
buttonPdf.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AsyncMakePdf asyncMakePdf=new AsyncMakePdf();
asyncMakePdf.execute(tempList());
}
});
}
public void loadItems(){
listItems=new ArrayList();
listItems=tempList();
listAdapter=new ListAdapter(this,listItems);
recyclerMoney.setAdapter(listAdapter);
swipeMoney.setRefreshing(false);
}
public class AsyncMakePdf extends AsyncTask,String ,Integer>{
AlertDialog dialogToShow;
LayoutInflater inflater = getLayoutInflater();
View view=inflater.inflate(R.layout.preloader_dialog,null);
PlayGifView imgGif=view.findViewById(R.id.imgGif);
TextView txtUpdate=view.findViewById(R.id.txtUpdate);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
String path=FOLDER_PDF+File.separator+"Report.pdf";
PdfWriter writer;
@Override
protected Integer doInBackground(ArrayList... arrayLists) {
/**
* Creating Document for report
*/
BaseFont baseFont = null;
try {
baseFont = BaseFont.createFont("res/font/montserratregular.ttf", "UTF-8",BaseFont.EMBEDDED);
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
Font regularHead = new Font(baseFont, 15,Font.BOLD,BaseColor.WHITE);
Font regularReport = new Font(baseFont, 30,Font.BOLD,printAccent);
Font regularName = new Font(baseFont, 25,Font.BOLD,BaseColor.BLACK);
Font regularAddress = new Font(baseFont, 15,Font.BOLD,BaseColor.BLACK);
Font regularSub = new Font(baseFont, 12);
Font regularTotal = new Font(baseFont, 16,Font.NORMAL,BaseColor.BLACK);
Font regularTotalBold = new Font(baseFont, 16,Font.BOLD,BaseColor.BLACK);
Font footerN = new Font(baseFont, 15,Font.BOLD,printAccent);
Font footerE = new Font(baseFont, 12,Font.NORMAL,BaseColor.BLACK);
// Document document = new Document(PageSize.A4);
Document document = new Document(PageSize.A4, 36, 36, 36, 72);
document.addCreationDate();
document.addAuthor("Akhil");
document.addCreator("logicchip.com");
//document.setMargins(0,0,0,0);
// Location to save
try {
writer =PdfWriter.getInstance(document, new FileOutputStream(path));
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
PdfPTable tableFooter = new PdfPTable(1);
tableFooter.setTotalWidth(523);
PdfPCell footerName = new PdfPCell(new Phrase("LOGICCHIP",footerN));
PdfPCell footerEmail = new PdfPCell(new Phrase("info@logicchip.com",footerE));
PdfPCell footerEmpty = new PdfPCell(new Phrase(""));
footerName.setBorder(Rectangle.NO_BORDER);
footerEmpty.setBorder(Rectangle.NO_BORDER);
footerEmail.setBorder(Rectangle.NO_BORDER);
PdfPCell preBorderBlue = new PdfPCell(new Phrase(""));
preBorderBlue.setMinimumHeight(5f);
preBorderBlue.setUseVariableBorders(true);
preBorderBlue.setBorder(Rectangle.TOP);
preBorderBlue.setBorderColorTop(printPrimary);
preBorderBlue.setBorderWidthTop(3);
tableFooter.addCell(preBorderBlue);
tableFooter.addCell(footerName);
tableFooter.addCell(footerEmail);
HeaderFooter event = new HeaderFooter(tableFooter);
writer.setPageEvent(event);
document.open();
onProgressUpdate("Please wait...");
PdfPCell preReport = new PdfPCell(new Phrase("REPORT",regularReport));
preReport.setHorizontalAlignment(Element.ALIGN_RIGHT);
preReport.setVerticalAlignment(Element.ALIGN_BOTTOM);
preReport.setBorder(Rectangle.NO_BORDER);
PdfPTable tableHeader = new PdfPTable(2);
try {
tableHeader.setWidths(new float[] { 1,3});
} catch (DocumentException e) {
e.printStackTrace();
}
try {
Drawable d = getResources().getDrawable(R.drawable.logo);
BitmapDrawable bitDw = ((BitmapDrawable) d);
Bitmap bmp = bitDw.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
Image image = Image.getInstance(stream.toByteArray());
// image.scaleToFit(50, 50);
PdfPCell preImage = new PdfPCell(image, true);
preImage.setBorder(Rectangle.NO_BORDER);
tableHeader.addCell(preImage);
tableHeader.addCell(preReport);
document.add(tableHeader);
} catch (BadElementException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
PdfPTable tableHeading = new PdfPTable(2);
tableHeading.setSpacingBefore(50);
Date c = Calendar.getInstance().getTime();
System.out.println("Current time => " + c);
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String formattedDate = df.format(c);
String theName="",theAddress="";
theName="Name of person";
theAddress="Address of person";
PdfPCell preName = new PdfPCell(new Phrase(theName,regularName));
PdfPCell preAddress = new PdfPCell(new Phrase(theAddress,regularAddress));
PdfPCell preDate = new PdfPCell(new Phrase("DATE: "+formattedDate,regularAddress));
PdfPCell preBill=new PdfPCell(new Phrase("No : 0001",regularAddress));
preBill.setVerticalAlignment(Element.ALIGN_BOTTOM);
preBill.setHorizontalAlignment(Element.ALIGN_RIGHT);
preDate.setVerticalAlignment(Element.ALIGN_BOTTOM);
preDate.setHorizontalAlignment(Element.ALIGN_RIGHT);
preName.setBorder(Rectangle.NO_BORDER);
preAddress.setBorder(Rectangle.NO_BORDER);
preDate.setBorder(Rectangle.NO_BORDER);
preBill.setBorder(Rectangle.NO_BORDER);
try {
tableHeading.addCell(preName);
tableHeading.addCell(preBill);
tableHeading.addCell(preAddress);
tableHeading.addCell(preDate);
document.add(tableHeading);
} catch (DocumentException e) {
e.printStackTrace();
}
PdfPTable table = new PdfPTable(4);
table.setSpacingBefore(20);
try {
table.setWidths(new float[] { 1f,2, 3,1.5f});
} catch (DocumentException e) {
e.printStackTrace();
}
table.setHeaderRows(1);
table.setSplitRows(false);
table.setComplete(false);
PdfPCell headDate = new PdfPCell(new Phrase("NO",regularHead));
PdfPCell headName = new PdfPCell(new Phrase("ITEM",regularHead));
PdfPCell headDis = new PdfPCell(new Phrase("COMPANY",regularHead));
PdfPCell headCr = new PdfPCell(new Phrase("AMOUNT",regularHead));
PdfPCell headDe = new PdfPCell(new Phrase("DEBIT",regularHead));
headDate.setPaddingLeft(15);
headDate.setPaddingTop(10);
headDate.setPaddingBottom(14);
headDate.setVerticalAlignment(Element.ALIGN_MIDDLE);
headName.setPaddingTop(10);
headName.setPaddingBottom(14);
headName.setVerticalAlignment(Element.ALIGN_MIDDLE);
headDis.setPaddingTop(10);
headDis.setPaddingBottom(14);
headDis.setVerticalAlignment(Element.ALIGN_MIDDLE);
headCr.setPaddingTop(10);
headCr.setPaddingBottom(14);
headCr.setVerticalAlignment(Element.ALIGN_MIDDLE);
headDe.setPaddingTop(10);
headDe.setPaddingBottom(14);
headDe.setVerticalAlignment(Element.ALIGN_MIDDLE);
headDate.setBackgroundColor(printPrimary);
headName.setBackgroundColor(printPrimary);
headDis.setBackgroundColor(printPrimary);
headCr.setBackgroundColor(printPrimary);
headDe.setBackgroundColor(printPrimary);
headDate.setBorder(Rectangle.NO_BORDER);
headName.setBorder(Rectangle.NO_BORDER);
headDis.setBorder(Rectangle.NO_BORDER);
headCr.setBorder(Rectangle.NO_BORDER);
headDe.setBorder(Rectangle.NO_BORDER);
table.addCell(headDate);
table.addCell(headName);
table.addCell(headDis);
table.addCell(headCr);
int amountFull=0;
for (int aw=0;aw
HeaderFooter
HeaderFooter.java class is used for creating footer of the PDF, so users can add there company name and email at the bottom of PDF.
public class HeaderFooter extends PdfPageEventHelper {
private PdfPTable footer;
public HeaderFooter(PdfPTable footer) {
this.footer = footer;
}
public void onEndPage(PdfWriter writer, Document document) {
footer.writeSelectedRows(0, -1, 36, 64, writer.getDirectContent());
}
}
Bottom sheet is a component that slides up from bottom of the screen to reveal more content. You can find more detailed information of Bottom Sheet on Google Material Design guidelines.
Permission are a thing now. Presently from Marshmallow on words android require Additional runtime permissions. Above all in order to work properly it’s essential. You know what mean. Presumably we specify each permissions multiple times in a class. However this tutorial is about adding multiple permissions dynamically.Yes that’s right.First Place all the required permissions in an array then call a method it’s that simple. As a matter of fact Only devices above Marshmallow have runtime permissions. You must keep in mind that to.
Permission
There are two types of permissions.
Normal permissions
Dangerous permissions
1- Normal permission
Presently those permissions the system automatically grants to your app.Permissions Like internet.
2-Dangerous permissions
Similarly those permissions user must agree to grand. Examples are permissions for location ,sms etc…
Action bar color dynamically. Sometimes it is necessary to change the Action Bar and status bar color dynamically. This project shows how it can be achieved simply. Status bar color change is supported for lollipop and above devices. So the project works by checking build versions of the device.Only action-bar color is can be changed for devices below lollipop and both action bar and status-bar color are changeable for devices above lollipop, else app crashes. To give an overview activity contain three seek-bars each representing the primary colors Red,Blue and Green. The goal is to create our required color by combining these colors. For the first step is to check the build version of the device. if it’s below lollipop the default color is set, and if it’s above lollipop default status-bar color also applied.
Changes made to the seek-bar are being saved so when you reopen the app the color is the last one you selected. You can modify the code as you like “link to source code is down below”. Now straight to code because it’s simple and nothing more to say about it.
Here ,I will show you how to create a custom Navigation Drawer using the auto generated Android Studio Navigation Drawer template. Using the auto generated Android Studio Navigation Drawer gives you are great head start for most of the use cases of Navigation Drawer; however it can also leave you in the middle of nowhere if you want to apply some customization. Here is what our demo app will look like when completed.[the_ad id=”1065″]
Adding Navigation Drawer
Create a new Android project using Android Studio, Select the new project template, select Phone and Tablet as your target devices and choose any API level 16. Click next and select Activity with Navigation like the image below and click next.[the_ad id=”1065″]
ject, I have added the following Fragments. No functionality is actually implemented in these fragments, they are used as demo fragment to demonstrate Navigation Drawer
FragmentA
FragmentB
FragmentC
FragmentD
Screen shots
MainActivity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private LinearLayout clk1,clk2,clk3,clk4;
TextView textMatter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
textMatter=(TextView)findViewById(R.id.textMatter);
clk1=(LinearLayout)findViewById(R.id.click1);
clk2=(LinearLayout)findViewById(R.id.click2);
clk3=(LinearLayout)findViewById(R.id.click3);
clk4=(LinearLayout)findViewById(R.id.click4);
Initializing();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_nine) {
textMatter.setText("99");
return true;
}if (id == R.id.action_two) {
textMatter.setText("22");
return true;
}
return super.onOptionsItemSelected(item);
}
public void Initializing(){
Fragment fragment = null;
Class fragmentClass = FragmentA.class;
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame, fragment).commit();
}
public void ClickNavigation(View view){
Fragment fragment = null;
Class fragmentClass = FragmentA.class;
switch (view.getId()){
case R.id.click1:
fragmentClass = FragmentA.class;
clk1.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_clickb, null));
clk2.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_click, null));
clk3.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_click, null));
clk4.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_click, null));
break;
case R.id.click2:
fragmentClass = FragmentB.class;
clk1.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_click, null));
clk2.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_clickb, null));
clk3.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_click, null));
clk4.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_click, null));
break;
case R.id.click3:
fragmentClass = FragmentC.class;
clk1.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_click, null));
clk2.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_click, null));
clk3.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_clickb, null));
clk4.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_click, null));
break;
case R.id.click4:
fragmentClass = FragmentD.class;
clk1.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_click, null));
clk2.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_click, null));
clk3.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_click, null));
clk4.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_clickb, null));
break;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame, fragment).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
}
activity_main
As you can see below we commented the NavigationView and replaced it with Our LinearLayout.
You can download full code from here, You can modify the code us u like. In like manner feel free to comment your doubt’s below. Does our tutorials help you then help as spread the word, like and share.
App Widget are miniature application views that can be embedded in other applications (such as the Home screen) and receive periodic updates. These views are referred to as Widgets in the user interface, and you can publish one with an AppWidget provider. An application component that is able to hold other App Widgets is called an AppWidget host.
Describes the metadata for an AppWidget, such as the App Widget’s layout, update frequency, and the AppWidgetProvider class. This should be defined in XML.
Defines the basic methods that allow you to programmatically interface with the AppWidget, based on broadcast events. Through it, you will receive broadcasts when the App Widget is updated, enabled, disabled and deleted.
Adding the AppWidgetProviderInfo Metadata
The AppWidgetProviderInfo defines the essential qualities of an App Widget, such as its minimum layout dimensions, its initial layout resource, how often to update the App Widget, and (optionally) a configuration Activity to launch at create-time. Define the AppWidgetProviderInfo object in an XML resource using a single <appwidget-provider> element and save it in the project’s res/xml/ folder.
You must define an initial layout for your AppWidget in XML and save it in the project’s res/layout/ directory. You can design your AppWidget using the View objects listed below, but before you begin designing your AppWidget, please read and understand the AppWidget Design Guidelines.
The AppWidgetProvider class extends BroadcastReceiver as a convenience class to handle the AppWidget broadcasts. The AppWidgetProvider receives only the event broadcasts that are relevant to the AppWidget, such as when the AppWidget is updated, deleted, enabled, and disabled. It also require a service to make constant update to the widget.
public class AppWidgetObject extends AppWidgetProvider {
private Handler handler;
private Runnable runnable;
SimpleDateFormat simpleDateFormat;
String time;
Calendar calander;
Context context;
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
{
context.startService(new Intent(context, UpdateService.class));
}
public static class UpdateService extends Service {
private Handler handler;
private Runnable runnable;
SimpleDateFormat simpleDateFormat;
String time;
Calendar calander;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
TimeForUpdate();
return START_REDELIVER_INTENT;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void TimeForUpdate(){
handler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
handler.postDelayed(this, 1000);
try {
calander = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("hh : mm : ss");
time = simpleDateFormat.format(calander.getTime());
RemoteViews widgetUi = new RemoteViews(getPackageName(), R.layout.widget);
widgetUi.setTextViewText(R.id.idForTimeChange,time);
try
{
ComponentName widgetComponent = new ComponentName(getBaseContext(),AppWidgetObject.class);
AppWidgetManager widgetManager = AppWidgetManager.getInstance(getBaseContext());
widgetManager.updateAppWidget(widgetComponent, widgetUi);
Log.e("Widget", "Ok");
}
catch (Exception e)
{
Log.e("widget", "Failed to update widget", e);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
handler.postDelayed(runnable, 0);
}
}
}
You can download full code from here, You can modify the code us u like. In like manner feel free to comment your doubt’s below. Does our tutorials help you then help as spread the word, like and share. More details available here.
DayDreams are interactive screensavers launched when a charging device is idle, or docked in a desk dock. Dreams provide another modality for apps to express themselves, tailored for an exhibition/lean-back experience. So it’s found here and an official example can be found here. DayDream feature was introduced in Android 4.2,brings this kind of laid-back, whimsical experience to Android phones and tablets that would otherwise be sleeping.However if you haven’t checked it out, you can turn it on in the Settings app, in Display > Daydream touch When to Daydream to enable the feature when charging or docking or both in some cases.
An attract mode for apps
Apps that support Daydream can also take advantage of the full Android UI toolkit in this mode, which means it’s easy to take existing components of your app — including layouts, animations, 3D, and custom views—and remix them for a more ambient presentation.
And since you can use touchscreen input in this mode as well, you can provide a richly interactive experience if you choose.
.Daydream also provides an opportunity for your app to show off a little bit. However you can choose to hide some of your app’s complexity in favor of one or more visually compelling experiences that can entertain from across a room, possibly drawing the user into your full app, like a video game’s attract mode.
The architecture of a Daydream
In fact each Daydream implementation is a subclass of android.service.dreams.DreamService. When you extend DreamService, you’ll have access to a simple Activity-like life-cycle API.
As a matter of fact to be available to the system, your DreamService should be declared in the manifest as follows:
Daydream is only available on devices running version 4.2 of Android , which is API Level 17 and above.When targeting api level 21 and above, you must declare the service in your manifest file with the BIND_DREAM_SERVICE permission.
In fact additional information is specified with the <meta-data> element. So additional information for the dream is defined using the <dream> element in a separate XML file. As a result it allows you to point to an XML resource that specifies a settings Activity specific to your Daydream. Currently, the only addtional information you can provide is for a settings activity that allows the user to configure the dream behavior For example:
public class DayDream extends DreamService {
Handler handler;
Runnable runnable;
SimpleDateFormat simpleDateFormat;
Calendar calander;
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
// Hide system UI
setFullscreen(true);
// Set the dream layout
setContentView(R.layout.dream);
}
@Override
public void onDreamingStarted() {
super.onDreamingStarted();
TimeChange12();
}
public void TimeChange12(){
handler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
handler.postDelayed(this, 1000);
try {
calander = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("hh : mm : ss");
TextView txtTime= (TextView)findViewById(R.id.txtTime);
txtTime.setText(simpleDateFormat.format(calander.getTime()));
} catch (Exception e) {
e.printStackTrace();
}
}
};
handler.postDelayed(runnable, 0);
}
}
Consequently layout for dreaming can be whatever we like, can include animation interactive ui etc.However, be aware that if your screen saver is using too much of the available processing resources, the Android system will stop it from running to allow the device to charge properly.
Even so “Creating Interactive Screen Saver with Daydream” is explained above you can still download it from here, You can modify the code us u like. In like manner feel free to comment your doubt’s below. Does our tutorials help you then help as spread the word, like and share.