I am beginner in working with app widget. Here i have made one app widget of app and in its class set receiver on click of widget icon.Its working when user clicks on it.But the issue is receiver also gets called sometimes automatically.
I am not getting why this is happening.Help will be appreciated.
My app widget's class:
MyWidget.java:
public class MyWidget extends AppWidgetProvider {
static Context cont;
static SharedPreferences preferences;
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId) {
preferences = context.getSharedPreferences("pref", Context.MODE_PRIVATE);
cont = context;
Intent intent2 = new Intent(context, MyReceiver.class);
PendingIntent pendingIntent = PendingIntent.
getBroadcast(context, 0,
intent2, PendingIntent.FLAG_UPDATE_CURRENT);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.my_widget);
views.setOnClickPendingIntent(R.id.appwidget_text, pendingIntent);
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 onEnabled(Context context) {
preferences = context.getSharedPreferences("pref", Context.MODE_PRIVATE);
preferences.edit().putBoolean("key", true).commit();
}
#Override
public void onDisabled(Context context) {
preferences = context.getSharedPreferences("pref", Context.MODE_PRIVATE);
preferences.edit().putBoolean("key", false).commit();
}
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="*************************">
<application
android:allowBackup="true"
android:icon="#drawable/logo"
android:label="#string/app_name"
android:roundIcon="#drawable/logo"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".Home">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".Myservice" />
<receiver android:name=".MyReceiver"></receiver>
<receiver android:name=".MyWidget">
<intent-filter>
<action android:name="**********************" />
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/my_widget_info" />
</receiver>
</application>
</manifest>
Related
My widget app is running fine on all android version except 8 Oreo.
I get a W/BroadcastQueue: Background execution not allowed: receiving Intent message.
There is an interesting blog from CommonsWare but I don't fully understand why it applies to my case.
https://commonsware.com/blog/2017/04/11/android-o-implicit-broadcast-ban.html
My case looks pretty simple: I have a widget with a button and I want to change the text's button when it is clicked.
What is the right way to fix this issue?
TestWidget.java
public class TestWidget extends AppWidgetProvider {
private static RemoteViews views;
private static boolean buttonClicked = false;
public static final String ACTION_AUTO_UPDATE = "AUTO_UPDATE";
#Override
public void onReceive(Context context, Intent intent)
{
super.onReceive(context, intent);
if(intent.getAction().equals(ACTION_AUTO_UPDATE))
{
Log.i("TESTWID", "get onReceive");
}
}
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId) {
views = new RemoteViews(context.getPackageName(), R.layout.test_widget);
views.setOnClickPendingIntent(R.id.wid_btn_tst, setButton(context));
appWidgetManager.updateAppWidget(appWidgetId, views);
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
Log.i("TESTWID", "onupdate ");
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}
public static PendingIntent setButton(Context context) {
Intent intent = new Intent();
intent.setAction("TEST");
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
public static void pushWidgetUpdate(Context context, RemoteViews remoteViews) {
ComponentName myWidget = new ComponentName(context, TestWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(myWidget, remoteViews);
}
}
TestWidgetReceiver.java
public class TestWidgetReceiver extends BroadcastReceiver{
private static boolean isButtonON = false;
#Override
public void onReceive(Context context, Intent intent) {
Log.i("TESTWID", "onReceive "+intent.getAction());
if(intent.getAction().equals("TEST")){
updateWidgetButton(context, 2);
}
}
private void updateWidgetButton(Context context, int index) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.test_widget);
if(index == 2) {
if(isButtonON) {
remoteViews.setTextViewText(R.id.wid_btn_tst, "Test Off");
isButtonON = false;
}
else{
remoteViews.setTextViewText(R.id.wid_btn_tst, "Test On");
isButtonON = true;
}
}
TestWidget.pushWidgetUpdate(context.getApplicationContext(), remoteViews);
}
}
Manifest.xml:
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="Test"
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=".TestWidget">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<intent-filter>
<action android:name="AUTO_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/test_widget_info" />
</receiver>
<receiver
android:name=".TestWidgetReceiver"
android:label="widgetBroadcastReceiver" >
<intent-filter>
<action android:name="TEST" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/test_widget_info" />
</receiver>
</application>
It's subtle, but it is because of the implicit broadcast being used to trigger your TestWidgetReceiver. It is implicit because it is only specifying the action portion of the Intent. Make the broadcast Intent explicit by specifying the receiver class in the constructor:
public static PendingIntent setButton(Context context) {
Intent intent = new Intent(context, TestWidgetReceiver.class);
intent.setAction("TEST");
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
Things are changed now a days in Android. For the security & battery consumption google introduced so many ways & increased some problem for developers.
You haven't passed the Context of the TestWidgetReceiver.class to you intent.
You can do it like that in java
Intent intent = new Intent(context, TestWidgetReceiver.class);
or in kotlin
val intent = Intent(context, TestWidgetReceiver.class);
You can read more changes here
https://developer.android.com/about/versions/oreo/android-8.0-changes
Regards
I have a widget which installs OK on the screen but when I press the button on it it's supposed to open a activity in my project. I've tried everything, but it still doesn't work.
Here is my code:
public class MyWidgetProvider extends AppWidgetProvider {
public static String INTENT_ACTION="OPEN_SECOND_VIEW_ACTIVITY";
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
final int N = appWidgetIds.length;
for (int i = 0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
Intent intent = new Intent(context, SecondViewActivity.class);
intent.setAction(INTENT_ACTION);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
views.setOnClickPendingIntent(R.id.widgetButton, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
#Override
public void onReceive(Context context, Intent intent) {
Log.v("MT","onReceive called");
super.onReceive(context, intent);
Log.v("MT","constructor passed");
Log.v("MT",intent.getAction());
if (intent.getAction().equals(INTENT_ACTION)) {
Log.v("MT","works");
Toast.makeText(context, "works", Toast.LENGTH_SHORT).show();
}
}
}
Here the activity(which is not the main acitivity which I want to open)
public class SecondViewActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_dialog);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
int mAppWidgetId = -1;
if (extras != null) {
mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
}
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getApplicationContext());
RemoteViews views = new RemoteViews(getApplicationContext().getPackageName(), R.layout.widget_layout);
appWidgetManager.updateAppWidget(mAppWidgetId, views);
Intent resultValue = new Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
setResult(RESULT_OK, resultValue);
finish();
}
And here my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.multitanteo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<receiver android:name="MyWidgetProvider">
<intent-filter >
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data android:name="android.appwidget.provider"
android:resource="#xml/widget_info"/>
</receiver>
<activity
android:name="com.example.multitanteo.MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.multitanteo.SecondViewActivity"
android:label="#string/title_activity_second_view_acitivity" >
<intent-filter >
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE"/>
</intent-filter>
<intent-filter >
<action android:name="android.intent.action.myTimeTravel"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>
</application>
</manifest>
the widget_info
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="40dp"
android:minHeight="40dp"
android:updatePeriodMillis="86400000"
android:initialLayout="#layout/widget_layout"
android:previewImage="#drawable/ic_launcher"
android:configure="com.example.multitanteo.SecondViewActivity"
android:resizeMode="horizontal|vertical"
android:widgetCategory="home_screen|keyguard"
android:initialKeyguardLayout="#layout/widget_keyguard">
</appwidget-provider>
the widget_layout
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="#dimen/widget_margin"
android:id="#+id/widgetFrameLayout">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello this is my widget"/>
<Button
android:id="#+id/widgetButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
</FrameLayout>
The problem with your code is that PendingIntent created in a wrong way. Based on the code it looks like You want to receive that intent in AppWidgetProvider. If so, then you need to provide providers class for intent (instead of activity class):
final Intent intent = new Intent(context, MyWidgetProvider.class);
And get broadcast PendingIntent, not activity one:
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, appWidgetId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Refer to PendingIntent documentation for additional details of it's usage.
Below is working example of activity launch by click from AppWidget:
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
final Intent intent = new Intent(context, MyWidgetProvider.class);
intent.setAction(INTENT_ACTION);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, appWidgetId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
views.setOnClickPendingIntent(R.id.widgetButton, pendingIntent);
// Tell the AppWidgetManager to perform an update on the current app widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (intent.getAction().equals(INTENT_ACTION)) {
Toast.makeText(context, "works", Toast.LENGTH_SHORT).show();
final Intent activityIntent = new Intent(context.getApplicationContext(), MyActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(activityIntent);
}
}
i have a widget that it send and receive a specific sms, but when I restart the cellphone the widget doesn't work. how can i do it ?
i have that in the androidManifest.xml
<receiver
android:name=".Inicio"
android:enabled="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
<intent-filter>
<action android:name="com.alexander.android.saldo.BOOT_COMPLETED"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
and i try to call this
public static void llamarWidget(Context context) {
int widgetId = 0;
SMSSend.ejecutarTarea();
Intent intentOrigen = ((Activity) context).getIntent();
Bundle params = intentOrigen.getExtras();
widgetId = params.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
AppWidgetManager appWidgetManager = AppWidgetManager
.getInstance(context);
MiWidget.actualizarWidget(context, appWidgetManager,
widgetId);
Intent resultado = new Intent();
resultado.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId);
((Activity) context).setResult(RESULT_OK, resultado);
}
public class Inicio extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
WidgetConfig.llamarWidget(context);
}
}
I need to make a widget which, once clicked, would start a service. Service would perform a certain action, change the widgets picture, play a sound, etc., and stop.
AppWidgetProvider:
public class WidgetActivity extends AppWidgetProvider {
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
Intent intent = new Intent(context.getApplicationContext(), SilentService.class);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
PendingIntent pendingIntent = PendingIntent.getService(
context.getApplicationContext(), 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.LinLayWiget, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
context.startService(intent);
}
}
service:
public class SilentService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "I'm Alive!", 1500).show();
MediaPlayer mpl = MediaPlayer.create(this, R.raw.enter );
mpl.start();
}
#Override
public void onDestroy() {
//code to execute when the service is shutting down
}
#Override
public void onStart(Intent intent, int startid) {
//code to execute when the service is starting up
}
}
manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="FX.Widget"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<receiver android:name="widget.cam.com.WidgetActivity" android:label="FXMaster" android:icon="#drawable/assiconwi">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
<action android:name="android.appwidget.action.APPWIDGET_ENABLED"/>
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/widgetprovider" />
</receiver>
<service
android:enabled="true"
android:name=".SilentService">
</service>
</application>
</manifest>
But once I click on the widget, nothing happens... any ideas why?
Thanks!
I have a widget that lets you select from 2 sizes, it also has a config. For some reason after some time goes by, the buttons on my widget will unbind and you will not be able to click anything. I dont know why this is happening. Could it be the super.onReceive(context, intent) in my OnRecieve method? Would that cause it to unbind possibly? Also what would the sure fire way to make sure the buttons are ALWAYS binded be?
AppWidgetProvider
public class mWidget extends AppWidgetProvider {
public static String ACTION_WIDGET_REFRESH = "Refresh";
public static final String PREFS_NAME = "mWidgetPrefs";
#Override
public void onEnabled(Context context) {
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
RemoteViews remoteViews = buildLayout(context);
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
}
public static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId) {
RemoteViews views = buildLayout(context);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
public static RemoteViews buildLayout(Context context) {
RemoteViews remoteView = new RemoteViews(context.getPackageName(),
R.layout.widget_4x2);
Intent intent = new Intent(context, mWidget.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
intent, 0);
intent = new Intent(context, mWidget.class);
intent.setAction(ACTION_WIDGET_REFRESH);
pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
remoteView.setOnClickPendingIntent(R.id.refresh, pendingIntent);
return remoteView;
}
#Override
public void onReceive(Context context, Intent intent) {
RemoteViews remoteView = null;
remoteView = new RemoteViews(context.getPackageName(),
R.layout.widget_4x2);
if (intent.getAction().equals(ACTION_WIDGET_REFRESH)) {
Toast.makeText(context, "here", Toast.LENGTH_LONG).show();
} else {
super.onReceive(context, intent);
}
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".mwidgetConfig" android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
</intent-filter>
</activity>
<activity android:name=".mwidgetConfigSmall"
android:label="#string/app_name" android:theme="#android:style/Theme.NoTitleBar">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
</intent-filter>
</activity>
<!-- BEGIN 4X4 WIDGET -->
<receiver android:label="Test Widget 4x4"
android:name="com.test.mwidget.mWidget">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
<action
android:name="com.test.mwidget.mWidget.ACTION_WIDGET_REFRESH" />
</intent-filter>
<meta-data android:name="android.appwidget.provider"
android:resource="#xml/widget_4x4_provider" />
</receiver>
<!-- BEGIN 4X2 WIDGET -->
<receiver android:label="Test Widget 4x2"
android:name="com.test.mwidget.mWidgetSmall">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
<action
android:name="com.test.mwidget.mWidgetSmall.ACTION_WIDGET_REFRESH" />
</intent-filter>
<meta-data android:name="android.appwidget.provider"
android:resource="#xml/widget_4x2_provider" />
</receiver>
</application>
You should bind your pending intent on each onUpdate event.
You should iterate through all appWidgerIds.
Usually, I implement widget stuff as the following:
public void onUpdate(Context context,
AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
updateAllWidgetsInternal(context, appWidgetManager, appWidgetIds);
}
private static void updateAllWidgetsInternal(Context context,
AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
final RemoteViews views = buildLayout(context);
final int N = appWidgetIds.length;
for (int i=0; i<N; ++i) {
appWidgetManager.updateAppWidget(appWidgetIds[i], views);
}
}
// This function can be executed anywhere in any time to update widgets
public static void updateAllWidgets(Context context) {
final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
final int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context, mWidget.class));
updateAllWidgetsInternal(context, appWidgetManager, appWidgetIds);
}
I don't understand why you implemented onReceive().
It's only necessary if your widget is configured to catch other broadcasts than the standard widgets broadcast which are ACTION_APPWIDGET_DELETED, ACTION_APPWIDGET_DISABLED, ACTION_APPWIDGET_ENABLED and ACTION_APPWIDGET_UPDATE.
If not necessary, try without onReceive().