Updating appwidget cause set values to default - java

I am writing an application widget that takes data from a server and displays them in a appwidget.
The problem is that when there is no internet connection and at this point the system updates the widget, TextView text value reset to the default text setted with android:text="sometext"
It happens like this:
Widget placed on homescreen
Internet connection is active
Widget successfully updated
The text of the response from the server is installed in the TextView
Internet connection is not active
The system updates the widget
Previous text in the TextView reset to the value setted in android:text=""
I know that somewhere I incorrectly do something, because in other widgets (not my) with no connection to the Internet does not reset.
File WidgetProvider.java
public class WidgetProvider extends AppWidgetProvider {
public static String LOG_TAG = "MYAPPLOG";
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
Log.d(LOG_TAG, "onReceive");
}
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
Log.d(LOG_TAG, "onUpdate");
for (int widgetID : appWidgetIds)
{
updateWidget(context, widgetID);
}
}
#Override
public void onDeleted(Context context, int[] appWidgetIds) {
super.onDeleted(context, appWidgetIds);
Log.d(LOG_TAG, "onDeleted");
}
public void updateWidget(Context context, int widgetID)
{
context.startService(new Intent(context, UpdatingService.class).putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetID));
}
}
File UpdatingService.java
public class UpdatingService extends IntentService {
public static String LOG_TAG = "MYAPPLOG";
public UpdatingService() {
super("UpdatingService");
}
#Override
protected void onHandleIntent(Intent intent) {
// getting widgetID from intent and other vars
RemoteViews remoteViews = new RemoteViews(getApplicationContext().getPackageName(),
R.layout.initial_layout);
if(isConnected(getApplicationContext()))
{
String response = getServerResponse();
if(response != null)
{
try {
JSONObject JSON = new JSONObject(response);
// get data from server
// ...
// set values to the views
remoteViews.setTextViewText(R.id.textView, someText);
} catch (JSONException e) {
e.printStackTrace();
Log.d(LOG_TAG, "JSONObject failed");
}
}
else
{
// LOG: error connection to server
}
}
else
{
// LOG: No internet connection
}
// updating apwidget (set click action for the some button)
// if not do update then button will not work
Intent someIntent = new Intent(getApplicationContext(), WidgetProvider.class);
someIntent.setAction(WidgetProvider.ACTION_GOTO);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),
widgetID, someIntent, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.goToLayout, pendingIntent);
AppWidgetManager.getInstance(getApplicationContext().getApplicationContext())
.updateAppWidget(widgetID, remoteViews);
}
public boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni != null && ni.isConnected()) {
return true;
}
return false;
}
public String getServerResponse() {
// using HttpURLConnection
}
}
I hope for your help or a little tip. I wrote several widgets and all with this problem. Thank you very much for your attention.

When an AppWidget update happens then every property must be set, like all the values of text views, all click listeners, colors, etc. Simply everything. What is not set will use the default value from the layout XML.
In your case you do nothing in the else branch ("no internet") thus your app widget ends up with the default text. So when you fetch the data from the server you must save it and use it the next time there is no internet connection.

Related

Onclick Event for Android Widget

I've read about 10 posts now about onclick events and Widgets and I understand they are implemented differently. However, despite the success other people are having I seem to be finding it impossible to get it to work. I'm using Android Studio 2.2 and have created a simple test app. I have a button called button. I want a toast to display when I press the button.
I've copied the code as suggested in the other posts. Can someone take a look and see if I am doing anything wrong?
public class NewAppWidget extends AppWidgetProvider {
private static final String MyOnClick = "myOnClickTag";
protected PendingIntent getPendingSelfIntent(Context context, String action) {
Intent intent = new Intent(context, getClass());
intent.setAction(action);
return PendingIntent.getBroadcast(context, 0, intent, 0);
}
void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
int appWidgetId) {
CharSequence widgetText = context.getString(R.string.appwidget_text);
// Construct the RemoteViews object
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);
views.setOnClickPendingIntent(R.id.button, getPendingSelfIntent(context, MyOnClick));
views.setTextViewText(R.id.appwidget_text, widgetText);
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
//RemoteViews.setOnClickPendingIntent(R.id.button, getPendingSelfIntent(context, MyOnClick));
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// There may be multiple widgets active, so update all of them
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}
}
#Override
public void onEnabled(Context context) {
// Enter relevant functionality for when the first widget is created
}
#Override
public void onDisabled(Context context) {
// Enter relevant functionality for when the last widget is disabled
}
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);//add this line
if (MyOnClick.equals(intent.getAction())){
//your onClick action is here
//display in short period of time
Toast.makeText(context, "msg msgasdasd", Toast.LENGTH_SHORT).show();
}
};
}
OK - really weird. Restarted the android emulator and it started working.
Mmmmm.
Cheers

Android Service only runs whilst debugging

Background
I am creating a service that syncs a local Realm database (stored on phone) with an online database. The database stores users and measurements.
I initialise the service by calling 'startService(new Intent(this, SyncService.class));' during the splash activity's onCreate() method, and specify in the manifest that the service should run for the length of the application.
The service has a broadcast receiver. When the receiver detects a network change from 'not connected' to 'connected', it fires a method called syncDatabases().
This method finds all measurements recorded locally after the timestamp of the last API callback, and sends them to the database. The API responds to a request by returning the object + a unique ID.
When a measurement is made whilst the device is offline, it is stored locally. When an internet connection is made, the syncDatabases() method should be called in order to update the online server with the local measurements.
My steps...
Steps when debugging the project:
With wifi I open the app and with an external device make a new measurement. This appears on both the app and in the database. I then turn wifi off and make another measurement - this appears on the device.
I attach the debugger.
I turn back on wifi and this triggers the services' receivers' onReceive() method. I step through this and it all works according to plan. I reach the syncDatabases() method, and from there I receive the callback from the API, and it then updates the Realm database with the new ID value.
The problem...
If I don't attach the debugger, nothing happens. The new measurements aren't pushed to the database, and none of my Log.e calls are printed.
Why is this happening? And is there an alternative solution / fix for this problem?
Code
Service class
public class SyncService extends Service {
private static final String TAG = "SYNCSERVICE";
private boolean mConnected = false;
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getExtras() != null) {
final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
if (netInfo != null) {
switch (netInfo.getState()) {
case CONNECTED:
if (!mConnected) {
Log.e("NETWORK", "Network " + netInfo.getTypeName() + " now connected");
syncDatabases();
mConnected = true;
}
break;
default:
mConnected = false;
break;
}
} else mConnected = false;
}
}
};
#Override
public void onCreate() {
super.onCreate();
initReceiver();
ConnectivityManager connectivityManager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager.getActiveNetworkInfo() != null) {
mConnected = true;
}
android.util.Log.e(TAG, "onCreate: SyncService created");
}
#Override
public void onDestroy() {
super.onDestroy();
unInitReceiver();
android.util.Log.e(TAG, "onDestroy: SyncService destroyed");
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
android.util.Log.e(TAG, "onBind: SyncService bound");
return null;
}
#Override
public boolean onUnbind(Intent intent) {
android.util.Log.e(TAG, "onUnbind: SyncService unbound");
return super.onUnbind(intent);
}
#Override
public void onRebind(Intent intent) {
super.onRebind(intent);
android.util.Log.e(TAG, "onRebind: SyncService rebound");
}
private void initReceiver() {
IntentFilter filters = new IntentFilter();
filters.addAction("android.net.wifi.WIFI_STATE_CHANGED");
filters.addAction("android.net.wifi.STATE_CHANGE");
registerReceiver(mReceiver, filters);
}
private void unInitReceiver() {
unregisterReceiver(mReceiver);
}
public void syncDatabases() {
RealmResults<UserDB> users = RealmDB.getInstance(getApplicationContext()).where(UserDB.class).findAll();
if (users.size() > 0) {
int userId = users.get(0).getmUserID();
Log.e("MESSAGE", PreferenceUtils.getInstance().getLastSyncDate());
Date lastSync = null;
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.getDefault());
try {
lastSync = sdf.parse(PreferenceUtils.getInstance().getLastSyncDate());
}
catch (ParseException e) {
e.printStackTrace();
try {
lastSync = BaseFragment.FORMAT.parse(PreferenceUtils.getInstance().getLastSyncDate());
}
catch (ParseException e1) {
e1.printStackTrace();
}
}
if (lastSync != null) {
Date lastSyncOffset = new Date(lastSync.getTime() + 1000);
/** Get all local results which have been made after the last sync date
 **/
RealmResults<MeasurementDB> newLocalMeasurements = RealmDB.getInstance(getApplicationContext())
.where(MeasurementDB.class).equalTo("user_ID", userId)
.greaterThan("dateCreated", lastSyncOffset)
.findAll();
/** For each measurement made after the last sync, add it to the server
 **/
for (MeasurementDB measurement : newLocalMeasurements) {
TemperatureListener mListener = new TemperatureListener(measurement);
ApiRequest.getInstance(getApplicationContext()).registerNewMeasurement(measurement.getAverage(),
measurement.getDateCreated().toString(), mListener, mListener);
}
}
}
}
/**
* Temperature listener receives the local copy of the temperature item. onResponse can then
* directly mutate the object instead of searching local db
*/
private class TemperatureListener implements Response.Listener<Measurement>, Response.ErrorListener {
private MeasurementDB measurement;
public TemperatureListener(MeasurementDB measurement) {
this.measurement = measurement;
}
#Override
public void onErrorResponse(VolleyError error) {
Log.e("OnResponse", "Failure");
}
#Override
public void onResponse(Measurement response) {
Log.e("OnResponse", "Success");
/** Update our local measurement's ID value (supplied by server)
 **/
RealmDB.getInstance(getApplicationContext()).beginTransaction();
measurement.setMeasurement_ID(response.getmMeasurementId());
RealmDB.getInstance(getApplicationContext()).commitTransaction();
/** Update the last sync date
 **/
PreferenceUtils.getInstance().setLastSyncDate(response.getmDateCreated());
}
}
}
Initialisation of Service in splash activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mTimedOut = true;
finishActivity();
}
}, DURATION);
/** Will sync application / cloud databases in background of app when network connected. **/
startService(new Intent(this, SyncService.class));
doApiWork();
}
Manifest entry
Stop with task to kill the service at the same time as the app.
Exported 'false' stops other apps from using the service.
<service
android:name=".network.SyncService"
android:stopWithTask="true"
android:enabled="true"
android:exported="false"/>
EDIT
I removed the service and left a receiver class, registered in the manifest, which triggers methods on another class when needed. However the receiver is only triggered in debug mode.

How to update App Widget with list view from an Activity

I know this has been asked for many times but I went through the documentation from top to bottom, read all answers here and none of them helped.
To be honest, each answer says something different about how to aproach this.
Now back to my question. I want to update the widget list view from some activity and I created WidgetProvider#sendUpdateBroadcastToAllWidgets() for this purpose which I call from the activity.
It eventually calls the onUpdate() so the broadcast is received correctly. But the views are not refreshed.
I also tried to call AppWidgetManager#notifyAppWidgetViewDataChanged() and refreshed the data in WidgetFactory#onDataSetChanged() but the method has never been called.
So I guess this all does not work because the remote views factory is cached but I don't know how to reliably overcome this. Any thoughts?
And what about contexts? I always have to supply one but I don't really care much which one. Does it matter?
Thanks
PROVIDER
public class WidgetProvider extends AppWidgetProvider {
public static void sendUpdateBroadcastToAllWidgets(Context context) {
int allWidgetIds[] = AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName(context, WidgetProvider.class));
Intent intent = new Intent(context, WidgetProvider.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds);
context.sendBroadcast(intent);
}
#Override
public void onUpdate(Context context, AppWidgetManager widgetManager, int[] widgetIds) {
for (int id : widgetIds) {
updateWidget(context, widgetManager, id);
}
super.onUpdate(context, widgetManager, widgetIds);
}
#Override
public void onDeleted(Context context, int[] widgetIds) {
WidgetPreferences prefs = new WidgetPreferences(context);
for (int widgetId : widgetIds) {
prefs.getWidgetPreferences(widgetId).edit().clear().commit();
}
super.onDeleted(context, widgetIds);
}
private static void updateWidget(Context context, AppWidgetManager widgetManager, int widgetId) {
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
// set list adapter
Intent serviceIntent = new Intent(context, WidgetService.class);
serviceIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId);
serviceIntent.setData(Uri.parse(serviceIntent.toUri(Intent.URI_INTENT_SCHEME)));
views.setRemoteAdapter(android.R.id.list, serviceIntent);
views.setEmptyView(android.R.id.list, android.R.id.empty);
// set widget title
WidgetDataCategory category = new WidgetPreferences(context).getSavedCategory(widgetId);
views.setTextViewText(R.id.titleText, context.getString(category.titleResourceId()));
// set onclick listener - we create a pending intent template and when an items is clicked
// the intent is filled with missing data and sent
Intent startActivityIntent = new Intent(context, SimplePersonDetailActivity.class);
startActivityIntent.setData(Uri.parse(startActivityIntent.toUri(Intent.URI_INTENT_SCHEME)));
startActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivityIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, startActivityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
views.setPendingIntentTemplate(android.R.id.list, pendingIntent);
// all hail to Google
widgetManager.updateAppWidget(widgetId, views);
}
}
FACTORY
public class WidgetFactory implements RemoteViewsService.RemoteViewsFactory {
private Context context;
private List<Person> people = new ArrayList<>();
public WidgetFactory(Context context, Intent intent) {
this.context = context;
int widgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
if (widgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
WidgetPreferences prefs = new WidgetPreferences(context);
WidgetDataCategory category = prefs.getSavedCategory(widgetId);
int numberOfItemsToShow = prefs.getSavedLimit(widgetId);
people = category.filterAndSlice(new PersonDao(context).getAllForGroup(Constants.SIMPLE_GROUP_ID), numberOfItemsToShow);
}
}
#Override
public void onCreate() {}
#Override
public void onDataSetChanged() {}
#Override
public void onDestroy() {}
#Override
public int getCount() {
return people.size();
}
#Override
public RemoteViews getViewAt(int position) {
Person person = people.get(position);
BigDecimal amount = ListViewUtil.sumTransactions(new TransactionDao(context).getAllForPerson(person));
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.item_widget);
remoteViews.setTextViewText(R.id.nameText, person.getName());
remoteViews.setTextViewText(R.id.amountText, MoneyFormatter.withoutPlusPrefix().format(amount));
// fill details for the onclick listener (updating the pending intent template
// set in the WidgetProvider)
Intent listenerIntent = new Intent();
listenerIntent.putExtra(Constants.PERSON_ID, people.get(position).getId());
remoteViews.setOnClickFillInIntent(R.id.widgetItem, listenerIntent);
return remoteViews;
}
#Override
public RemoteViews getLoadingView() {
return null;
}
#Override
public int getViewTypeCount() {
return 1;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public boolean hasStableIds() {
return true;
}
}
I would say that notifyAppWidgetViewDataChanged method should work for you.
You have to build AppWidgetManager and get appWidgetIds and then just call notifyAppWidgetViewDataChanged on your AppWidgetManager.
Pseudo Code,
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
int appWidgetIds[] = appWidgetManager.getAppWidgetIds(
new ComponentName(context, WidgetProvider.class));
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.listview);
For more, you can checkout my answer here which contains demo on github.
I had a widget implementation in my project. I have modified the below code so that data in widget can be changed from one of my Activity in application. Only showing the essential code for your specific use case. Here I am having a button with text in my widget. Through login button click in my Activity , I am modifying the button text in my widget
Below is my AppWidgetProvider.java class
public class AppWidgetTrackAsset extends AppWidgetProvider{
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// Perform this loop procedure for each App Widget that belongs to this provider
final int N = appWidgetIds.length;
for (int i=0; i<N; i++) {
int appWidgetId = appWidgetIds[i];
// Create an Intent to launch Activity
Intent intent = new Intent(context, WidgetAlertActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
// Get the layout for the App Widget and attach an on-click listener
// to the button
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.app_widget_track_asset);
views.setOnClickPendingIntent(R.id.sosButton, 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);
Log.v(Constants.WIDGET_LOG, "onReceive called with " + intent.getAction());
if (intent.getAction().equals("update_widget")) {
// widget update started
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.app_widget_track_asset);
// Update text , images etc
remoteViews.setTextViewText(R.id.sosButton, "My updated text");
// Trigger widget layout update
AppWidgetManager.getInstance(context).updateAppWidget(
new ComponentName(context, AppWidgetTrackAsset.class), remoteViews);
}
}
#Override
public void onEnabled(Context context) {
// Enter relevant functionality for when the first widget is created
}
#Override
public void onDisabled(Context context) {
// Enter relevant functionality for when the last widget is disabled
}
}
Below is my Activity where I am updating the widget button text on click of my login button
LoginActivity.java
public class LoginActivity extends AppCompatActivity implements View.OnClickListener{
Button loginButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginButton=(Button)findViewById(R.id.loginButton);
loginButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.loginButton){
updateWidget();
}
}
private void updateWidget(){
try {
Intent updateWidget = new Intent(this, AppWidgetTrackAsset.class);
updateWidget.setAction("update_widget");
PendingIntent pending = PendingIntent.getBroadcast(this, 0, updateWidget, PendingIntent.FLAG_CANCEL_CURRENT);
pending.send();
} catch (PendingIntent.CanceledException e) {
Log.e(Constants.UI_LOG,"Error widgetTrial()="+e.toString());
}
}
}
Layout for app widget goes like this
app_widget_track_asset.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/widgetbackground"
android:padding="#dimen/widget_margin">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/sosButton"
android:text="SOS"
android:textSize="20sp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
/>
</RelativeLayout>
Below is the manifest file essential part for widget
<receiver android:name=".appwidget.AppWidgetTrackAsset">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/app_widget_track_asset_info" />
</receiver>

How to stop NfcAdapter.ACTION_NDEF_DISCOVERED becoming true when device boots?

My application starts when the device boots (Nexus 7). When my device boots if(action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) becomes true. Then the code inside the if crashes because the intent was not really a ACTION_NDEF_DISCOVERED but a boot.
I can put a try catch and then it won't crash. However then NFC won't work. To get NFC to work the application must be closed and reopened.
Is there a way to check the if(action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) but have it ignore the booting? It is really annoying because the if is checking for NFC not boot.
#Override
public void onResume()
{
super.onResume();
// NFC code.
Intent intent = getIntent();
String action = intent.getAction();
PendingIntent pi = this.createPendingResult(0x00A, new Intent(), 0);
nfcAdapter.enableForegroundDispatch(this, pi, null, null);
try
{
// NFC transfer. Receiving message here.
if(action != null && action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED))
{
Parcelable[] parcelables = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage inNdefMessage = (NdefMessage) parcelables[0];
NdefRecord[] inNdefRecords = inNdefMessage.getRecords();
NdefRecord NdefRecord_0 = inNdefRecords[0];
String inMsg = new String(NdefRecord_0.getPayload());
Toast.makeText(getApplicationContext(), "Toasty: "+inMsg + action.toString(), Toast.LENGTH_LONG).show();
textInfo.setText(inMsg);
}
}
catch(Exception e)
{
Log.e("NFC", e.getMessage());
}
}
This is the code that checks for BOOTING.
public class BootManager extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED))
{
Intent i = new Intent(context, Login_Activity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
}
In the Login_Activity, Could this be altering the intent?
#Override
protected void onNewIntent(Intent intent)
{
setIntent(intent);
}

BroadcastReceiver for listening mobile data state

I used a Broadcast Receiver for listening the current wifi state.
So it sets the current state to the text (connected, connecting, disabled,...) of a togglebutton (setText).
It works fine!
But now I want to do the same thing with the mobile data state..
So I used TelephonyManager to setup the receiver:
this.registerReceiver(this.DataStateChangedReceiver,
new IntentFilter(TelephonyManager.ACTION_PHONE_STATE_CHANGED));
Then I copied the code from the wifi receiver and edited it:
private BroadcastReceiver DataStateChangedReceiver
= new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
// TODO Auto-generated method stub
int extraDataState = intent.getIntExtra(TelephonyManager.EXTRA_STATE ,
TelephonyManager.DATA_DISCONNECTED);
switch(extraDataState){
case TelephonyManager.DATA_CONNECTED:
data_toggle.setChecked(true);
break;
case TelephonyManager.DATA_DISCONNECTED:
data_toggle.setChecked(false);
break;
case TelephonyManager.DATA_CONNECTING:
data_toggle.setChecked(true);
break;
case TelephonyManager.DATA_SUSPENDED:
data_toggle.setChecked(true);
break;
}
}
};
The app starts but nothing happened with the toogleButton..
Is TelephonyManager the wrong way to do this? ConnectivityManager?
I want to set an onclicklistener to turn on / off the mobile data.
How to do this is the next question..
In my work I have used a trick with ACTION_SCREEN_ON and _OFF...... So, the trick is in such thing.... you create boolean variable in Receiver.class, and then change it when connection state is changed.... And then in service (or activity), where you get intent do what to do.....
private boolean screenOff;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
}
Intent i = new Intent(context, InternetService.class);
i.putExtra("screen_state", screenOff);
context.startService(i);
}

Categories

Resources