So I've created a widget, and I'm tried my best to simulate a toggle button. Sense Widget doesn't support a toggle button I'm using a imagebutton and plan on changing the image depending on it's state.
Only problem is it's state isn't being saved and I'm not sure why.
package com.tdubstudios.beastmode;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import android.widget.Toast;
public class WidgetClass extends AppWidgetProvider{
private static final String ACTION_WIDGET_RECEIVER = "ActionRecieverWidget";
private RemoteViews views;
public boolean beastmodeOn = false;
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
final int N = appWidgetIds.length;
views = new RemoteViews("com.tdubstudios.beastmode", R.layout.widget_layout);
// Perform this loop procedure for each App Widget that belongs to this
// provider
for (int i = 0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
Intent intent = new Intent(context, WidgetClass.class);
intent.setAction(ACTION_WIDGET_RECEIVER);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
views.setOnClickPendingIntent(R.id.widget_ib, 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) {
if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
if(beastmodeOn){
beastmodeOn = false;
Toast.makeText(context, "beastmode is now off", Toast.LENGTH_SHORT).show();
}else{
beastmodeOn = true;
Toast.makeText(context, "beastmode is now ON", Toast.LENGTH_SHORT).show();
}
}
super.onReceive(context, intent);
}
#Override
public void onDeleted(Context context, int[] appWidgetIds) {
super.onDeleted(context, appWidgetIds);
Toast.makeText(context, "onDelete has been called in widgetClass", Toast.LENGTH_LONG).show();
}
}
No matter how many times I press the button I always get the toast "beastmode is now ON"
Any suggestions?
Thank you.
EDIT:
Ok so I added this code:
Log.i("widget","BEFORE beastmode is: "+beastmodeOn);
beastmodeOn = true;
Toast.makeText(context, "beastmode is now ON", Toast.LENGTH_SHORT).show();
Log.i("widget","AFTER beastmode is: "+beastmodeOn);
and my log gives me this back:
BEFORE beastmode is: false
AFTER beastmode is: true
It gives me this EVERY time I press the button. So obviously it creates a new instance or something to that effect. Once it executes it must destroy all variable values or something, maybe someone with more knowledge knows the right words.
So does anyone know a work around then?
So I don't exactly know why the above didn't work, I'm assuming because it creates a new instance. I've managed to make a work around though by using SharedPreferences to keep track of the toggle. Probably not the best way to do it but it works, so I'm happy.
For anyone else having this problem here ya go:
package com.tdubstudios.beastmode;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import android.widget.RemoteViews;
import android.widget.Toast;
public class WidgetClass extends AppWidgetProvider {
private static final String ACTION_WIDGET_RECEIVER = "ActionRecieverWidget";
private RemoteViews views;
public boolean beastmodeOn;
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
final int N = appWidgetIds.length;
views = new RemoteViews("com.tdubstudios.beastmode",
R.layout.widget_layout);
// Perform this loop procedure for each App Widget that belongs to this
// provider
for (int i = 0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
Intent intent = new Intent(context, WidgetClass.class);
intent.setAction(ACTION_WIDGET_RECEIVER);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
0, intent, 0);
views.setOnClickPendingIntent(R.id.widget_ib, pendingIntent);
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
boolean value = prefs.getBoolean("beastmodeOn", false);
if (value) {
Editor editor = prefs.edit();
editor.putBoolean("beastmodeOn", false);
editor.commit();
}
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
boolean value = prefs.getBoolean("beastmodeOn", false);
Editor editor = prefs.edit();
if (value) {
beastmodeOn = true;
} else {
beastmodeOn = false;
}
if (beastmodeOn) {
Toast.makeText(context, "beastmode is now off",
Toast.LENGTH_SHORT).show();
editor.putBoolean("beastmodeOn", false);
editor.commit();
} else {
Toast.makeText(context, "beastmode is now ON",
Toast.LENGTH_SHORT).show();
editor.putBoolean("beastmodeOn", true);
editor.commit();
}
}
super.onReceive(context, intent);
}
#Override
public void onDeleted(Context context, int[] appWidgetIds) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
boolean value = prefs.getBoolean("beastmodeOn", false);
if (value) {
Editor editor = prefs.edit();
editor.putBoolean("beastmodeOn", false);
editor.commit();
}
super.onDeleted(context, appWidgetIds);
}
}
Related
I want to make an app that shows a notification as soon as headphone is plugged in and remove it when it is plugged out. My app works fine when it is on or home button is pressed, but doesn't work when back is pressed or app is closed by long pressing home and swiping it away. What should I use in order to make it work?
This is my code
package com.example.earphone;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class HeadsetPlugReceiver extends BroadcastReceiver {
TextView t1;
#Override
public void onReceive(Context context, Intent intent) {
if (!intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
return;
}
boolean connectedHeadphones = (intent.getIntExtra("state", 0) == 1);
// boolean connectedMicrophone = (intent.getIntExtra("microphone", 0) == 1) && connectedHeadphones;
String headsetName = intent.getStringExtra("name");
Log.v("message", "headphone connected" + headsetName);
Intent i = new Intent(context, MainActivity.class);
PendingIntent p = PendingIntent.getActivity(context,0,i,0);
// Toast.makeText(context, "Headphone connected", Toast.LENGTH_SHORT).show();
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
int state = intent.getIntExtra("state", -1);
if(state==1){
Intent intent1 = new Intent(context, ES.class);
context.startForegroundService(intent1);
}
switch (state) {
case 0:
Intent intent1 = new Intent(context, ES.class);
context.stopService( intent1);
Toast.makeText(context, "Headphone ejected", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(context, "Headphone connected", Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(context, "I have no idea what the headset state is", Toast.LENGTH_SHORT).show();
}
}
}}
package com.example.earphone;
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 C_ID = "noti";
#Override
public void onCreate() {
super.onCreate();
createnoti();
}
private void createnoti(){
if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.O){
NotificationChannel nc = new NotificationChannel(
C_ID,"ex", NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager nm= getSystemService(NotificationManager.class);
nm.createNotificationChannel(nc);
}
}
}
package com.example.earphone;
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.example.earphone.App.C_ID;
public class ES extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent ni = new Intent(this,HeadsetPlugReceiver.class);
PendingIntent pi = PendingIntent.getActivity(this,0,ni,0);
Notification notification = new NotificationCompat.Builder(this, C_ID)
.setContentTitle("Headphones plugged in")
.setContentText("currently plugged in")
.setSmallIcon(R.mipmap.ic_launcher).setContentIntent(pi).build();
startForeground(1,notification);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
public class MainActivity extends AppCompatActivity {
Button b;
HeadsetPlugReceiver headsetPlugReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = findViewById(R.id.b);
// Intent intent = new Intent(this, ES.class);
//startService(intent);
headsetPlugReceiver = new HeadsetPlugReceiver();
IntentFilter i = new IntentFilter();
i.addAction("android.intent.action.HEADSET_PLUG");
registerReceiver(headsetPlugReceiver,i);
}
}
In my app an alarm creates a notification which works but I am trying to pass a string value from my main class FoodItems.java to AlarmReceiver.java which in turn passes the String to RingtoneServiceProvider.java which creates the custom notification to be displayed. As it stands the string appears to be successfully passing into AlarmReceiver.java as I had a toast message display it before to see but when it goes to RingtoneServiceProvider.java it becomes "null".
This is part of FoodItems.java where the string value 'name' is a value entered by the user that I want to appear on the notification.
private void setAlarm(Calendar targetCal){
Toast.makeText(getApplicationContext(),
"Alarm is set for " + targetCal.getTime(),Toast.LENGTH_LONG).show();
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
intent.putExtra("data",name);
intent.putExtra("ID", Alarmnum);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(),Alarmnum,intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);
}
This is AlarmReceiver.java
package com.example.kev00_000.kitchenhero;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String name = intent.getStringExtra("data");
int id = intent.getIntExtra("ID", 1);
Intent service_intent=new Intent(context, RingtonePlayingService.class);
service_intent.putExtra("data",name);
service_intent.putExtra("ID", id);
context.startService(service_intent);
NotificationManager notifications = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
}
}
And here is RingtonePlayingService.java
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
public class RingtonePlayingService extends Service {
MediaPlayer alarm;
private String name;
private static int NOTIFICATION_ID = 1;
#Nullable
#Override
public IBinder onBind(Intent intent) {
name = intent.getStringExtra("data");
NOTIFICATION_ID = intent.getIntExtra("ID", 1);
return null;
}
public void onCreate(){
super.onCreate();
alarm=MediaPlayer.create(this, R.raw.alarmclockbuzz);
alarm.setLooping(true);
Intent stopself = new Intent(this, StopAlarm.class);
PendingIntent pendingIntent
= PendingIntent.getBroadcast(this, 0, stopself, PendingIntent.FLAG_CANCEL_CURRENT);
final NotificationCompat.Builder notification
= new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.ic_launcher)
.setOngoing(true)
.setContentTitle("KitchenHero")
.setContentText("Time to put your "+name+" on!!")
.setAutoCancel(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
.addAction(R.drawable.ic_launcher, "STOP", pendingIntent);
Notification note=notification.build();
startForeground(NOTIFICATION_ID, note);
}
public int onStartCommand(Intent intent, int flags, int startId) {
alarm.start();
return START_NOT_STICKY;
}
public void onDestroy() {
alarm.stop();
alarm.release();
}
Using Shared Preferences to do this
public static final String MyPREFERENCES = "MyPrefs" ;
SharedPreferences sharedpreferences;
private void setAlarm(Calendar targetCal){
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("name",name);
editor.putString("ID",ID);
editor.commit();
Toast.makeText(getApplicationContext(),
"Alarm is set for " + targetCal.getTime(),Toast.LENGTH_LONG).show();
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(),Alarmnum,intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);
}
And get String in other class
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("name", "");
In my project user have to register and then proceed forward.After the restart of the app the login activity should start skipping the registration activity.But the problem arises when user restarts the app without registering,the login activity appears and not the register activity.So plz help me with this issue Thanks in Advance
package com.example.mobilefinder;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
public class SplashScreen extends Activity {
// Splash screen timer
private static int SPLASH_TIME_OUT = 4000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Context context = getApplicationContext();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
if(!prefs.getBoolean("firstTime", false)) {
// run your one time code here
Intent i = new Intent(getApplicationContext(), NewAccount.class);
startActivity(i);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
boolean firstboot = getSharedPreferences("BOOT_PREF", MODE_PRIVATE).getBoolean("firstboot", true);
//
if (firstboot){
// // 1) Launch the authentication activity
Intent i = new Intent(getApplicationContext(), NewAccount.class);
startActivity(i);
// // 2) Then save the state
getSharedPreferences("BOOT_PREF", MODE_PRIVATE)
.edit()
.putBoolean("firstboot", false)
.commit();
}
else
{
Intent i = new Intent(getApplicationContext(), enterpass.class);
startActivity(i);
}
// Intent i =new Intent(getApplicationContext(), NewAccount.class);
// startActivity(i);
// close this activity
finish();
}
}, SPLASH_TIME_OUT);
}
}
NewAccount.java
package com.example.mobilefinder;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Patterns;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class NewAccount extends Activity implements OnClickListener {
EditText ed1, ed2, ed3, ed4;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.newaccount);
Button ok;
ok = (Button) findViewById(R.id.new_account_btn_ok);
ok.setOnClickListener(this);
ed1 = (EditText) findViewById(R.id.new_account_name);
ed2 = (EditText) findViewById(R.id.new_account_email);
ed3 = (EditText) findViewById(R.id.new_account_pass);
ed4 = (EditText) findViewById(R.id.new_account_repass);
}
public final static boolean isValidEmail(String email) {
{
return Patterns.EMAIL_ADDRESS.matcher(email).matches();
}
}
#Override
public void onClick(View arg0) {
String s2 = ed2.getText().toString();
String s3 = ed3.getText().toString();
String s4 = ed4.getText().toString();
if (ed1.getText().toString().length() == 0
|| ed2.getText().toString().length() == 0
|| ed3.getText().toString().length() == 0
|| ed4.getText().toString().length() == 0) {
if (ed1.getText().toString().length() == 0) {
ed1.setError("field required");
} else if (ed2.getText().toString().length() == 0) {
ed2.setError("field required");
} else if (ed3.getText().toString().length() == 0) {
ed3.setError("field required");
} else if (ed4.getText().toString().length() == 0) {
ed2.setError("field required");
}
} else if (isValidEmail(s2) == false) {
Toast.makeText(getApplicationContext(), "Invalid Email",
Toast.LENGTH_SHORT).show();
} else if (ed3.getText().toString().length() < 6) {
Toast.makeText(getApplicationContext(), "Password too Short",
Toast.LENGTH_SHORT).show();
} else if (!s3.equals(s4)) {
Toast.makeText(getApplicationContext(), "Password Dont Match",
Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplicationContext(),
"Account Created Successfully", Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
}
}
Move this code inside NewAccount.class so firstboot will be set to false only when the user has authenticated.
// 2) Then save the state
getSharedPreferences("BOOT_PREF", MODE_PRIVATE)
.edit()
.putBoolean("firstboot", false)
.commit();
I've only rewieved it breefly but I'd put it here:
else {
Toast.makeText(getApplicationContext(),
"Account Created Successfully", Toast.LENGTH_SHORT).show();
// set firstboot to false here
getSharedPreferences("BOOT_PREF", MODE_PRIVATE)
.edit()
.putBoolean("firstboot", false)
.commit();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
When I scan my NFC tag, my application fires up and does what it have to do , but the tabhost goes missing. The mainactivity.java is where I initialize the tabhost with 3 tabs and this following first part of the code is one of the tab in which I utilize the NFC reading function. Is this because of the pendingintent? I don't really know how to fix it, do I have to implement the 3 tabs in every activity layout?
My code:
package com.example.ponpon;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.os.PatternMatcher;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
#TargetApi(10)
public class CouponManager extends Activity {
private static final String TAG = "NFCReadTag";
private NfcAdapter mNfcAdapter;
private IntentFilter[] mNdefExchangeFilters;
private PendingIntent mNfcPendingIntent;
public static final String PREF_FILE_NAME = "PrefFile";
private int[] images = new int[11];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.coupon_layout);
//List of images
images[0]=R.drawable.cp0;
images[1]=R.drawable.cp1;
images[2]=R.drawable.cp2;
images[3]=R.drawable.cp3;
images[4]=R.drawable.cp4;
images[5]=R.drawable.cp5;
images[6]=R.drawable.cp6;
images[7]=R.drawable.cp7;
images[8]=R.drawable.cp8;
images[9]=R.drawable.cp9;
images[10]=R.drawable.cp10;
//Restore preferences
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
//Image to use depending on coupon collected
final ImageView img = (ImageView)findViewById(R.id.imageView1);
if(storedPreference!=10)
{
img.setImageResource(images[storedPreference]);
img.invalidate();
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle("Coupon Redemption");
builder.setMessage("Redeem Your Coupon?");
builder.setInverseBackgroundForced(true);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", 0); // value to store
editor.commit();
img.setImageResource(images[0]);
img.invalidate();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
img.setImageResource(images[10]);
img.invalidate();
}
});
builder.show();
}
//Check and send Intent from NFC tag discovered
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
mNfcPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
/*| Intent.FLAG_ACTIVITY_CLEAR_TOP*/), 0);
IntentFilter coupontag = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
coupontag.addDataScheme("http");
coupontag.addDataAuthority("www.ichatime.com", null);
coupontag.addDataPath(".*", PatternMatcher.PATTERN_SIMPLE_GLOB);
mNdefExchangeFilters = new IntentFilter[] { coupontag };
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
if(mNfcAdapter != null) {
mNfcAdapter.enableForegroundDispatch(this, mNfcPendingIntent,
mNdefExchangeFilters, null);
} else {
Toast.makeText(getApplicationContext(), "Sorry, No NFC Adapter found.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onPause() {
super.onPause();
if(mNfcAdapter != null) mNfcAdapter.disableForegroundDispatch(this);
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
}
#Override
protected void onStop() {
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
}
#Override
protected void onDestroy() {
super.onDestroy();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
}
#Override
public void onBackPressed() {
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
super.onBackPressed();
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
NdefMessage[] messages = null;
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (rawMsgs != null) {
messages = new NdefMessage[rawMsgs.length];
for (int i = 0; i < rawMsgs.length; i++) {
messages[i] = (NdefMessage) rawMsgs[i];
}
}
if(messages[0] != null) {
String result="";
byte[] payload = messages[0].getRecords()[0].getPayload();
// this assumes that we get back am SOH followed by host/code
for (int b = 1; b<payload.length; b++) { // skip SOH
result += (char) payload[b];
}
if (result.contains("ichatime.com"))
{
final ImageView img = (ImageView)findViewById(R.id.imageView1);
/*if (storedPreference!=10)
{
Toast.makeText(getApplicationContext(), "Coupon collected!", Toast.LENGTH_SHORT).show();
storedPreference++;
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference);
img.setImageResource(images[storedPreference]);
img.invalidate();
}*/
if (storedPreference==10)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setTitle("Redeem Your Coupon?");
builder.setInverseBackgroundForced(true);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", 0); // value to store
editor.commit();
img.setImageResource(images[0]);
img.invalidate();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
img.setImageResource(images[10]);
img.invalidate();
}
});
builder.show();
}
else
{
Toast.makeText(getApplicationContext(), "Coupon collected!", Toast.LENGTH_SHORT).show();
storedPreference++;
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference);
editor.commit();
img.setImageResource(images[storedPreference]);
img.invalidate();
}}
else
{
Toast.makeText(getApplicationContext(), "Wrong tag detected!", Toast.LENGTH_SHORT).show();
}
//Debugging Mode to see what is contained in the tags.
// Toast.makeText(getApplicationContext(), "Tag Contains " + result, Toast.LENGTH_SHORT).show();
}
}
}
}
and also, my main activity:
package com.example.ponpon;
import android.os.Bundle;
import android.app.TabActivity;
import android.content.Intent;
import android.view.Menu;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
public class MainActivity extends TabActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabHost tabHost = getTabHost();
TabSpec spec1=tabHost.newTabSpec("Coupon Manager");
spec1.setContent(R.id.tab1);
spec1.setIndicator("Coupons");
Intent CouponsIntent = new Intent(this, CouponManager.class);
spec1.setContent(CouponsIntent);
TabSpec spec2=tabHost.newTabSpec("Help");
spec2.setIndicator("Help");
spec2.setContent(R.id.tab2);
Intent SettingsIntent = new Intent(this, Settings.class);
spec2.setContent(SettingsIntent);
TabSpec spec3=tabHost.newTabSpec("Write[Vendor]");
spec3.setIndicator("Write\n[Vendor]");
spec3.setContent(R.id.tab3);
Intent HelpIntent = new Intent(this, HelpActivity.class);
spec3.setContent(HelpIntent);
tabHost.addTab(spec1);
tabHost.addTab(spec2);
tabHost.addTab(spec3);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Take a close look at your logic: you have
if (storedPreference!=10) {
...stuff... (including storedPreference++)
}
if (storedPreference==10) {
...stuff...
} else {
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", 10);
img.setImageResource(images[10]);
img.invalidate();
}
You should consider replacing the contents of the else block with the storedPreference!=10 block, then getting rid of that first block. All you need is if storedPreference==10 and else.
I'm new at this android stuff and trying to teach myself the language and I'm running into a brick wall here.
I'm trying to program a really simple widge that is just a button. When the button is pressed the phone goes to silent mode. Unfortunately, the onlky thing that I am able to program the button do is pop a toast message.
Can someone please advise me on my errors. Thanks a bunch in advance. Here is my code:
package com.DoNotDisturb.widget;
import com.DoNotDisturb.widget.R;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;
public class DoNotDisturbWidget extends AppWidgetProvider {
public static String ACTION_WIDGET_CONFIGURE = "ConfigureWidget";
public static String ACTION_WIDGET_RECEIVER = "ActionReceiverWidget";
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
Intent active = new Intent(context, DoNotDisturbWidget.class);
active.setAction(ACTION_WIDGET_RECEIVER);
active.putExtra("msg", "Phone is silent");
PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0);
remoteViews.setOnClickPendingIntent(R.id.button_one, actionPendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
}
#Override
public void onReceive(Context context, Intent intent) {
// v1.5 fix that doesn't call onDelete Action
final String action = intent.getAction();
if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
final int appWidgetId = intent.getExtras().getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
this.onDeleted(context, new int[] { appWidgetId });
}
} else {
// check, if our Action was called
if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
String msg = "null";
try {
msg = intent.getStringExtra("msg");
} catch (NullPointerException e) {
Log.e("Error", "msg = null");
}
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification noty = new Notification(R.drawable.icon, "Do Not Disturb Feature Activated", System.currentTimeMillis());
noty.setLatestEventInfo(context, "Notice", msg, contentIntent);
notificationManager.notify(1, noty);
} else {
// do nothing
}
super.onReceive(context, intent);
}
}
private AudioManager getSystemService(String audioService) {
// TODO Auto-generated method stub
return null;
}
}