How Do I Update The Widget's TextViewText From A Broadcast Receiver? - java

I am trying to update my widget's TextView Text from a BroadcastReceiver on ClickPendingIntent. I am not having much luck. Can I please get some help with this? In my ActionReceiver.class which extends BroadcastReceiver, I know that I need to update the widget after changing the textview text. I am not sure how to do that. Unfortunately, I can't use statics without crashing the app and widget. Here is my code...
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mywidget">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<receiver android:name=".MyWidget">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/my_widget_info" />
</receiver>
<activity
android:name=".MainActivity"
android:screenOrientation="locked">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".ActionReceiver"/>
</application>
</manifest>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/myTV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textAlignment="center"
android:text="#string/default_tv_text"
android:textSize="16sp"
android:textStyle="bold"
android:textColor="#android:color/black"/>
<EditText
android:id="#+id/myET"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/myTV"
android:inputType="text"
android:hint="#string/default_et_text"
android:textAlignment="center"
android:textSize="16sp"
android:textStyle="bold"
android:textColor="#android:color/black"
tools:ignore="Autofill" />
<View
android:id="#+id/myView"
android:layout_width="match_parent"
android:layout_height="5dp"
android:layout_below="#id/myET"/>
<Button
android:id="#+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/myView"
android:layout_centerHorizontal="true"
android:text="#string/button_text"
android:textSize="16sp"
android:textStyle="bold"
android:textColor="#android:color/black"/>
</RelativeLayout>
my_widget.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="180dp"
android:layout_height="110dp"
android:padding="#dimen/widget_margin">
<TextView
android:id="#+id/appwidget_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_margin="8dp"
android:contentDescription="#string/appwidget_text"
android:text="#string/appwidget_text"
android:textColor="#android:color/white"
android:textSize="24sp"
android:textStyle="bold|italic" />
</RelativeLayout>
strings.xml
<resources>
<string name="app_name">My Widget</string>
<string name="default_tv_text">Hello World!</string>
<string name="default_et_text">Enter Something To Change The Text Above.</string>
<string name="button_text">OK</string>
<string name="appwidget_text">EXAMPLE</string>
<string name="appwidget_text_changed">Hello World!</string>
<string name="add_widget">Add widget</string>
</resources>
MainActivity.class
package com.example.mywidget;
import androidx.appcompat.app.AppCompatActivity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
TextView tv;
EditText et;
Button btn;
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = findViewById(R.id.myTV);
et = findViewById(R.id.myET);
btn = findViewById(R.id.myButton);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String getEditText = et.getText().toString();
if (!getEditText.isEmpty()) {
tv.setText(getEditText);
Toast.makeText(getBaseContext(), "Text Changed!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
MyWidget.class
package com.example.mywidget;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.widget.RemoteViews;
import android.widget.Toast;
import androidx.annotation.Nullable;
public class MyWidget extends AppWidgetProvider {
public void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId) {
CharSequence widgetText = context.getString(R.string.appwidget_text);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.my_widget);
views.setTextViewText(R.id.appwidget_text, widgetText);
Intent actionIntent = new Intent(context, ActionReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, actionIntent, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.appwidget_text, pi);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}
}
ActionReceiver.class
package com.example.mywidget;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import android.widget.Toast;
public class ActionReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
CharSequence getNewText = context.getString(R.string.appwidget_text_changed);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.my_widget);
views.setTextViewText(R.id.appwidget_text, getNewText); // The widget needs to be updated from here with something like this updateAppWidget(context, appWidgetManager, appWidgetId);
Toast.makeText(context, "Widget Updated!", Toast.LENGTH_SHORT);
}
}
My Updated MyWidget.class
public class MyWidget extends AppWidgetProvider {
public void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId) {
CharSequence widgetText = context.getString(R.string.appwidget_text);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.my_widget);
views.setTextViewText(R.id.appwidget_text, widgetText);
Intent actionIntent = new Intent(context, MyWidget.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, actionIntent, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.appwidget_text, pi);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}
#Override
public void onReceive(Context context, Intent intent) {
AppWidgetManager appWM = AppWidgetManager.getInstance(context);
ComponentName myWidget = new ComponentName(context, MyWidget.class);
int[] appWIDs = appWM.getAppWidgetIds(myWidget);
CharSequence getNewText = context.getString(R.string.appwidget_text_changed);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.my_widget);
views.setTextViewText(R.id.appwidget_text, getNewText);
if (appWIDs == null && appWIDs.length > 0) {
onUpdate(context, appWM, appWIDs);
Toast.makeText(context, "Widget Updated!", Toast.LENGTH_SHORT).show();
}
}
}
It's still not working for me. When I click the textview on the widget, it just launches the app. I'm trying to get the textview to change the default word "Example" to "Hello World" when the textview is clicked on. I've been trying for hours figuring this out.

Related

i'm creating notification alarm app and the notification not created

i create this app but it is not send a notification at the time choosen please can any one help me to solve this problem
xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_horizontal"
tools:context=".MainActivity">
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your task"
android:layout_marginBottom="20dp"/>
<TimePicker
android:id="#+id/timePicker"
android:layout_width="300dp"
android:layout_height="342dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:layout_marginTop="30dp">
<Button
android:id="#+id/setBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="set"
android:layout_marginRight="20dp"/>
<Button
android:id="#+id/cancelBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="cancel"/>
</LinearLayout>
and this is the MainActivity class for app:
package com.examble.alarmlast;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
Button setbtn;
TimePicker timePicker;
EditText edt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setbtn = findViewById(R.id.setBtn);
edt=findViewById(R.id.editText);
timePicker=findViewById(R.id.timePicker);
final int hour = timePicker.getCurrentHour();
final int minute = timePicker.getCurrentMinute();
setbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
intent.putExtra("todo", edt.getText().toString());
alarmIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
// Set the alarm to start at 8:30 a.m.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY,hour );
calendar.set(Calendar.MINUTE, minute);
// setRepeating() lets you specify a precise custom interval--in this case,
// 20 minutes.
alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 20,
alarmIntent);
Toast.makeText(MainActivity.this, "Done!", Toast.LENGTH_SHORT).show();
}
});
}
}
and this is the AlarmReceiver class for app:
package com.examble.alarmlast;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import static androidx.core.content.ContextCompat.getSystemService;
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("todo");
// When notification is tapped, call MainActivity.
Intent mainIntent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, mainIntent, 0);
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O)
{
NotificationChannel notificationChannel = new NotificationChannel("n","n",
NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager myNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
myNotificationManager.createNotificationChannel(notificationChannel);
}
// Prepare notification.
NotificationCompat.Builder builder = new NotificationCompat.Builder(context,"n")
.setContentText(message)
.setContentTitle("It's Time!")
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setAutoCancel(true)
.setContentText(message)
.setWhen(System.currentTimeMillis())
.setContentIntent(contentIntent)
.setPriority(Notification.PRIORITY_MAX)
.setDefaults(Notification.DEFAULT_ALL);
// Notify
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
notificationManagerCompat.notify(999,builder.build());
}
}
AndroidManifast:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.abeer.alarmlast">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".AlarmReceiver" />
</application>
</manifest>
Receiver doesnt know when to invoke itself.
<receiver android:name=".AlarmReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
You need to specify when to invoke it.

Facing problem while viewing and downloading wallpapers in new activity

I'm creating a Wallpaper application. I'm done with the categories and wallpapers inside each category using Picasso. And now I tried to make a new activity to view and download any wallpaper using Picasso. But after coding, when I click on the wallpaper the new activity never opens. Also there is no relevant error showing on the LogCat. Please help!
Here is the Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="me.umarkhan.walldeck">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/FullScreenTheme">
<activity android:name=".ViewWallpaper"></activity>
<activity android:name=".ListWallpaper" />
<activity
android:name=".HomeActivity"
android:label="#string/title_activity_home"
android:theme="#style/FullScreenTheme" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
XML Code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rootLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
tools:context="me.umarkhan.walldeck.ViewWallpaper">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/app_bar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:id="#+id/collapsing"
android:fitsSystemWindows="true"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleTextAppearance="#android:color/transparent"
android:layout_width="match_parent"
android:layout_height="350dp">
<ImageView
android:id="#+id/imageThumb"
android:contentDescription="WallDeck Wallpaper"
android:scaleType="centerCrop"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:layout_collapseMode="pin"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"></androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="590dp"
android:clipToPadding="false"
app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior"
tools:layout_editor_absoluteY="352dp">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
app:cardElevation="10dp"
app:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:padding="12dp"
android:text="Wallpaper description"
android:textSize="20sp"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
</androidx.core.widget.NestedScrollView>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fabWallpaper"
android:layout_marginRight="30dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_terrain_black_24dp"
android:elevation="6dp"
app:pressedTranslationZ="12dp"
app:layout_anchor="#id/app_bar_layout"
app:layout_anchorGravity="bottom|right|end"
android:backgroundTint="#android:color/white"/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fabDownload"
android:layout_marginLeft="30dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_file_download_black_24dp"
android:elevation="6dp"
app:pressedTranslationZ="12dp"
app:layout_anchor="#id/app_bar_layout"
app:layout_anchorGravity="bottom|left|start"
android:backgroundTint="#android:color/white"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
SaveImageHelper Class
package me.umarkhan.walldeck.Helper;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.provider.MediaStore;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import java.lang.ref.WeakReference;
public class SaveImageHelper implements Target {
private Context context;
private WeakReference<AlertDialog> alertDialogWeakReference;
private WeakReference<ContentResolver> contentResolverWeakReference;
private String name;
private String desc;
public SaveImageHelper(Context context, AlertDialog alertDialog, ContentResolver contentResolver, String name, String desc) {
this.context = context;
this.alertDialogWeakReference =new WeakReference<AlertDialog>(alertDialog);
this.contentResolverWeakReference =new WeakReference<ContentResolver>(contentResolver);
this.name = name;
this.desc = desc;
}
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
ContentResolver r = contentResolverWeakReference.get();
AlertDialog alertDialog = alertDialogWeakReference.get();
if (r != null)
MediaStore.Images.Media.insertImage(r,bitmap,name,desc);
alertDialog.dismiss();
Toast.makeText(context,"Download Successful", Toast.LENGTH_SHORT).show();
//Open Gallery After Download
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
context.startActivity(Intent.createChooser(intent,"View Picture"));
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}
ViewWallpaper Class
package me.umarkhan.walldeck;
import android.Manifest;
import android.app.AlertDialog;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.app.ActivityCompat;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.squareup.picasso.Picasso;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import com.squareup.picasso.Target;
import java.util.UUID;
import dmax.dialog.SpotsDialog;
import me.umarkhan.walldeck.Common.Common;
import me.umarkhan.walldeck.Helper.SaveImageHelper;
public class ViewWallpaper extends AppCompatActivity {
CollapsingToolbarLayout collapsingToolbarLayout;
FloatingActionButton floatingActionButton,fabDownload;
ImageView imageView;
CoordinatorLayout rootLayout;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case Common.PERMISSION_REQUEST_CODE:
{
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
AlertDialog dialog = new SpotsDialog(ViewWallpaper.this);
dialog.show();
dialog.setMessage("Please Wait....");
String fileName = UUID.randomUUID().toString()+".png";
Picasso.with(getBaseContext())
.load(Common.select_background.getimageLink())
.into(new SaveImageHelper(getBaseContext(),
dialog,
getApplicationContext().getContentResolver(),
fileName,
"WallDeck Wallpapers"));
}
else
Toast.makeText(this,"You need to grant permission to download image", Toast.LENGTH_SHORT).show();
}
}
}
private Target target = new Target(){
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_wallpaper);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//Init
rootLayout = (CoordinatorLayout)findViewById(R.id.rootLayout);
collapsingToolbarLayout = (CollapsingToolbarLayout)findViewById(R.id.collapsing);
collapsingToolbarLayout.setCollapsedTitleTextAppearance(R.style.CollapsedAppBar);
collapsingToolbarLayout.setExpandedTitleTextAppearance(R.style.ExpandedAppBar);
collapsingToolbarLayout.setTitle(Common.CATEGORY_SELECTED);
imageView = (ImageView)findViewById(R.id.imageThumb);
Picasso.with(this)
.load(Common.select_background.getimageLink())
.into(imageView);
floatingActionButton = (FloatingActionButton)findViewById(R.id.fabWallpaper);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Picasso.with(getBaseContext())
.load(Common.select_background.getimageLink())
.into(target);
}
});
fabDownload = (FloatingActionButton)findViewById(R.id.fabDownload);
fabDownload.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View view) {
//Check Permission
if (ActivityCompat.checkSelfPermission(ViewWallpaper.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE}, Common.PERMISSION_REQUEST_CODE);
return;
}
else
{
AlertDialog dialog = new SpotsDialog(ViewWallpaper.this);
dialog.show();
dialog.setMessage("Please Wait....");
String fileName = UUID.randomUUID().toString()+".png";
Picasso.with(getBaseContext())
.load(Common.select_background.getimageLink())
.into(new SaveImageHelper(getBaseContext(),
dialog,
getApplicationContext().getContentResolver(),
fileName,
"WallDeck Wallpapers"));
}
}
});
}
#Override
protected void onDestroy() {
Picasso.with(this).cancelRequest(target);
super.onDestroy();
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
}
I have already requested External Write Permission in HomeActivity:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case Common.PERMISSION_REQUEST_CODE:
{
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
Toast.makeText(this,"Permission Granted", Toast.LENGTH_SHORT).show();
else
Toast.makeText(this,"You need to grant permission to download image", Toast.LENGTH_SHORT).show();
}
break;
}
}
private AppBarConfiguration mAppBarConfiguration;
private Object Context;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("WallZone Pro");
setSupportActionBar(toolbar);
// Request Runtime Permission
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE},Common.PERMISSION_REQUEST_CODE);
}
Please help!
Please add the class from which to go to ViewWallpaper.class

Call measure how far you dragged in Android

I made an application running in the background, and I want to add a function to measure the slide on the screen. I'll leave you the code for both, and someone can help me. I'm a beginner and I've been looking all over trying to solve this without results.
I know the post is too long, but I did not know how to shorten it so you can understand it.
The code for running the application in the background
App.java
package com.codinginflow.foregroundserviceexample;
import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
public class App extends Application {
public static final String CHANNEL_ID = "exampleServiceChannel";
#Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Example Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager =
getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.codinginflow.foregroundserviceexample">
<application
android:name=".App"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".ExampleService" />
</application>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
</manifest>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
android:padding="16dp"
tools:context="com.codinginflow.foregroundserviceexample.MainActivity">
<EditText
android:id="#+id/edit_text_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Input" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="startService"
android:text="Start Service" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="stopService"
android:text="Stop Service" />
</LinearLayout>
ExampleService.java
package com.codinginflow.foregroundserviceexample;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import static com.codinginflow.foregroundserviceexample.App.CHANNEL_ID;
public class ExampleService extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("inputExtra");
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this,
CHANNEL_ID)
.setContentTitle("Example Service")
.setContentText(input)
.setSmallIcon(R.drawable.ic_android)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
MainActivity.java
package com.codinginflow.foregroundserviceexample;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
private EditText editTextInput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextInput = findViewById(R.id.edit_text_input);
}
public void startService(View v) {
String input = editTextInput.getText().toString();
Intent serviceIntent = new Intent(this, ExampleService.class);
serviceIntent.putExtra("inputExtra", input);
ContextCompat.startForegroundService(this, serviceIntent);
}
public void stopService(View v) {
Intent serviceIntent = new Intent(this, ExampleService.class);
stopService(serviceIntent);
}
}
Code for sliding measurement
Point p1;
Point p2;
View view = new View(this);
view.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN)
p1 = new Point((int) event.getX(), (int) event.getY());
else if(event.getAction() == MotionEvent.ACTION_UP)
p2 = new Point((int) event.getX(), (int) event.getY());
return false;
}
});
Can someone call me this code in my app?

How to make clickable widget [Android]

I've created a widget, and on click an Activity has to be launched, I followed the answer to this question [Clickable widgets in android].
However, on click I am unable to get any response, here is the java code to my widget:
Widget.java
public class Widget extends AppWidgetProvider
{
private static String YOUR_AWESOME_ACTION = "YourAwesomeAction";
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
{
Intent intent = new Intent(context, HomeTeamSelector.class);
intent.setAction(YOUR_AWESOME_ACTION);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
views.setOnClickPendingIntent(R.id.widgetLayout, pendingIntent);
}
#Override
public void onReceive(Context context, Intent intent)
{
super.onReceive(context, intent);
if (intent.getAction().equals(YOUR_AWESOME_ACTION))
{
Intent x = new Intent(context,HomeTeamSelector.class);
context.startActivity(x);
}
}
}
This is the code to the xml file:
widget.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="#+id/widgetLayout"
android:layout_height="match_parent"
android:transitionGroup="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name_extra"
android:id="#+id/textView"
android:layout_centerInParent="true"
android:textColor="#color/colorPrimary"
android:textSize="30sp" />
</RelativeLayout>
The widget is rendered, however I am unable to get any response on click, what is possibly causing this, and how to fix?
try to add AppWidgetProvider receiver in AndroidMenifest.xml like
<receiver
android:name=".Widget"
android:label="#string/widget">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/widget" />
</receiver>

Android remoteViews with buttons , when click the button, the notification bar can not pack up

I have customized a notification with the remoteviews, the view contains layouts and two buttons, what I want is that when users click a layout which named "contentLayout", the activity "Test" will be opened, and when Users click buttons, "remindTenMinButton" or "remindLaterButton", the action "Test2" will started.now the problem is the activity "Test" started correctly, but for the activity "Test2", when I clicked the button in the notification bar, it seems nothing happened, but when I click the "back", when the notification bar fold back, I can see the Test2 has already started, so the question is how to make the notification bar fold back when user click the button in the remoteview?
below are my codes:
MainActivity:
package com.example.androidtest2;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RemoteViews;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
MainActivity.this).setSmallIcon(R.drawable.ic_launcher);
String notifyTitle = "title....";
String notifyContent = "content......";
RemoteViews remoteViews = new RemoteViews(MainActivity.this
.getPackageName(), R.layout.notification_bar);
remoteViews.setTextViewText(R.id.title, notifyTitle);
remoteViews.setTextViewText(R.id.content, notifyContent);
Intent resultIntent = new Intent(MainActivity.this, Test.class);
TaskStackBuilder stackBuilder = TaskStackBuilder
.create(MainActivity.this);
stackBuilder.addParentStack(Test.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder
.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT);
Intent notifyLaterIntent = new Intent(MainActivity.this,
NotificationProcesssingReceiver.class);
PendingIntent PendingNotifyLaterIntent = PendingIntent
.getBroadcast(MainActivity.this, 0, notifyLaterIntent,
PendingIntent.FLAG_CANCEL_CURRENT
| PendingIntent.FLAG_ONE_SHOT);
Intent notify10LaterIntent = new Intent(MainActivity.this,
NotificationProcesssingReceiver.class);
PendingIntent PendingNotify10LaterIntent = PendingIntent
.getBroadcast(MainActivity.this, 0,
notify10LaterIntent, 0);
remoteViews.setOnClickPendingIntent(R.id.contentLayout,
resultPendingIntent);
remoteViews.setOnClickPendingIntent(R.id.remindLaterButton,
PendingNotifyLaterIntent);
remoteViews.setOnClickPendingIntent(R.id.remindTenMinButton,
PendingNotify10LaterIntent);
NotificationManager mNotificationManager = (NotificationManager) MainActivity.this
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = mBuilder.build();
notification.defaults = Notification.DEFAULT_SOUND;
notification.audioStreamType = android.media.AudioManager.ADJUST_LOWER;
notification.icon = R.drawable.ic_launcher;
notification.tickerText = "ticker text...";
notification.bigContentView = remoteViews;
// mId allows you to update the notification later on.
mNotificationManager.notify(1, notification);
}
});
}
}
NotificationProcesssingReceiver:
package com.example.androidtest2;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class NotificationProcesssingReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent)
{
Intent test = new Intent(context, Test2.class);
test.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//context.startActivity(toMainScreen);
context.startActivity(test);
}
}
Test:
public class Test extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
/* NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(1);*/
}
}
Test2:
public class Test2 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test2);
}
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${packageName}.${activityClass}" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:layout_marginLeft="56dp"
android:text="Button" />
</RelativeLayout>
notification_bar.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="100dp" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/contentLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/desk_command_oye" />
<LinearLayout
android:id="#+id/contentTextLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/imageView1"
android:orientation="vertical" >
<TextView android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Title...."/>
<TextView android:id="#+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="text content"/>
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:id="#+id/buttonsLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/linearLayout1"
android:layout_toRightOf="#+id/linearLayout1" >
<Button android:id="#+id/remindTenMinButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button1"/>
<Button android:id="#+id/remindLaterButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button2"/>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
activity_test.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="${packageName}.${activityClass}" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
activity_test2.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${packageName}.${activityClass}" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
</RelativeLayout>
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidtest2"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.androidtest2.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.androidtest2.Test"
android:label="#string/title_activity_test" >
</activity>
<receiver android:name="com.example.androidtest2.NotificationProcesssingReceiver" >
</receiver>
<activity
android:name="com.example.androidtest2.Test2"
android:label="#string/title_activity_test2" >
</activity>
</application>
Found the question, use below code:
Intent it = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
context.sendBroadcast(it);
For the detail, check this link:

Categories