I have this receiver class, it' registered in my MainActivity, it's supposed to count unlocks.
My goal
I want to make it work even when the app itself is not running(the receiver is never unregistered). It should get the amount of unlocks to the main activity without starting/restarting the activity.
My problem
I have no idea how to do that. As you can see I have tried to do it with SharedPreferences, but it didn't work, the receiver works fine and gets broadcasts, I just don't want it to start everytime.
public class UnlockReceiver extends BroadcastReceiver {
private int count = 0;
private SharedPreferences preferences;
private SharedPreferences.Editor editor;
private static final String TAG = "UnlockReceiver";
#Override
public void onReceive(Context context, Intent intent) {
preferences = context.getSharedPreferences("label", 0);
count = preferences.getInt("tag", 0);
KeyguardManager keyguardManager = (KeyguardManager)context.getSystemService(Context.KEYGUARD_SERVICE);
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
if (!keyguardManager.inKeyguardRestrictedInputMode()) {
count++;
editor = preferences.edit();
editor.putInt("tag", count).commit();
Log.d(TAG, "unlock registered");
Intent i = new Intent(context, MainActivity.class);
i.putExtra("tag", count);
context.sendBroadcast(i);
}
} else {
if (!keyguardManager.isDeviceLocked()) {
count++;
editor = preferences.edit();
editor.putInt("tag", count).commit();
Log.d(TAG, "unlock registered");
Intent i = new Intent(context, MainActivity.class);
i.putExtra("tag", count);
context.sendBroadcast(i);
}
}
}
}
Related
I am Working on a project where i have two buttons and a textview (in layout) for a time picker to set notification,
buttonTimepicker & buttonCancelAlarm.
I used to save the Time, selected in the Time Picker by shared Preferences.
The shared preferences are working properly.
But the problem i am facing is that, when i click the Cancel button, My app still showing me the notification set by time picker, Even i had implement editor.clear(); on shared preference on click of Cancel button Listner.
When i remove the shared preferences it work properly canceling the time and notification.
Here, what i want is to save the time in a shared preference on Set Time button, And clear shared preference on cancel Time button.
public class drvschedule extends AppCompatActivity implements
TimePickerDialog.OnTimeSetListener {
private TextView mTextView;
SharedPreferences myPrefdrv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drvschedule);
mTextView = findViewById(R.id.drtmslctd);
Button buttonTimePicker = findViewById(R.id.setdrvtm);
buttonTimePicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment timePicker = new TimePickerFragment();
timePicker.show(getSupportFragmentManager(), "time picker");
}
});
Button buttonCancelTime = findViewById(R.id.cncldrvtm);
buttonCancelTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences.Editor editor=myPrefdrv.edit();
editor.clear();
editor.apply();
cancelAlarm();
}
});
myPrefdrv=getPreferences(MODE_PRIVATE);
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND, 0);
updateTimeText(c);
startAlarm(c);
}
private void updateTimeText(Calendar c) {
String timeText = "Notification set for Driving: ";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
timeText +=
DateFormat.getTimeInstance(DateFormat.SHORT).format(c.getTime());
}
mTextView.setText(timeText);
}
private void startAlarm(Calendar c) {
AlarmManager alarmManager = (AlarmManager)
getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1,
intent, 0);
if (c.before(Calendar.getInstance())) {
c.add(Calendar.DATE, 1);
}
SharedPreferences.Editor editor=myPrefdrv.edit();
editor.apply();
alarmManager.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(),
pendingIntent);
}
private void cancelAlarm() {
AlarmManager alarmManager = (AlarmManager)
getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1,
intent, 0);
alarmManager.cancel(pendingIntent);
mTextView.setText("Notification canceled");
}
}
//used to save preferences....
SharedPreferences.Editor editor=myPrefdrv.edit();
editor.apply();
//used to clear preference....
SharedPreferences.Editor editor=myPrefdrv.edit();
editor.clear();
editor.apply();
Please try this code To store ,get and clear sharedprefereces data
we have pass two parameters in this method getsharedpreferences(String PREFS_NAME ,int mode )
PREFS_NAME is the name of the file.
mode is the operating mode.
StoreData
SharedPreferences pref = getSharedPreferences("mypref", 0);
SharedPreferences.Editor editor = pref.edit();
editor.putString("deviceToc",token); // Storing string
editor.apply();
getData
SharedPreferences sharedpreferences = getSharedPreferences("mypref", 0);
SharedPreferences prefs = sharedpreferences;
String string = prefs.getString("deviceToc", null);
clear data
SharedPreferences sharedpreferences = getSharedPreferences("mypref", 0);
sharedpreferences.edit().clear().commit();
You can use this instead of time picker
editors.putLong("lastlogin", new Date().getTime());
this answer
The three methods: ringtone(); onActivityResult(); saveRingtone(); do work.
During the first load of the app the fourth method loadRingtone(); works too, it can play repeatingly any sound the user chooses.
But as the app restarts:
It does save and bring back the string of the User's chosen notification sound. But just as its supposed to play the sound, converted from that string, it plays the default instead.
I used some toasts to check the values.
Toast.makeText(this,uri.toString(),Toast.LENGTH_SHORT).show();
Toast.makeText(this,ringPath,Toast.LENGTH_SHORT).show();
public void ringtone(View view){
final Uri currentTone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, currentTone);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "Select Tone");
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, (Uri) null);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false);
this.startActivityForResult(intent, 5);
}
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent intent) {
if (resultCode == Activity.RESULT_OK && requestCode == 5){
uri = intent.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
if (uri == null) {
uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
sound = RingtoneManager.getRingtone(getApplicationContext(), uri);
saveRingtone();
}
}
public void saveRingtone(){
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Ring, uri.toString());
editor.apply();
}
public void loadRingtone(){
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
ringPath = sharedPreferences.getString(Ring, "");
if(ringPath == ""){
uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}else {
uri.parse(ringPath);
}
sound = RingtoneManager.getRingtone(getApplicationContext(), uri);
sound.play();
}
Its expected to play the notification that the "sound" variable is set up with in the loadRingtone(); method (not default sound).
I have two activities namely Registration and Login where I defined a Shared Preferences in the Registration class. On the Registration page, if you click on the button that takes you to the Login Activity from the Registration Activity. I am storing a Shared Preferences value, so that on launching the app the second time, let the app immediately go to the LoginActivity instead of opening the first Activity which is Registration Activity. Here is my SharedPreferences class called Session.
private SharedPreferences prefs;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
}
public void setusename(String usename) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username", usename).commit();
editor.commit();
public Boolean contKey(String key){
if (prefs.contains(key)){
return true;
}else{
return false;
}
}
Here is the button in the RegstrationActivity that stores the SharedPreferences value before going to the LoginActivity so that on launch the second time, it opens the LoginActivity class
loginLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
session = new Session(getApplicationContext());
session.setusename("hello123");
Intent intent = new Intent(getApplication(),ActivityLogin.class);
startActivity(intent);
finish();
}
});
I have defined this in the onCreate method of RegistrationActivity class to switch to the ActivityLogin screen on next time the app is launched
System.out.println("it got here...2");
try {
if (session.contKey("username")) {
System.out.println("it got here...");
Intent intent = new Intent(getApplication(), ActivityLogin.class);
startActivity(intent);
overridePendingTransition(R.anim.enter, R.anim.exit);
finish();
} else {
System.out.println("it got here...3");
Intent intent = new Intent(getApplication(), ActivityRegistration.class);
startActivity(intent);
finish();
overridePendingTransition(R.anim.enter, R.anim.exit);
}
}catch(Exception ex){
}
Please why is my Shared Preferences not switching to the LoginActivity the second time the is launched. Kindly assist
TRy this
private SharedPreferences prefs;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
prefs = PreferenceManager.getDefaultSharedPreferences(cntx);
}
public void setusename(String usename) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username", usename);
editor.commit();
}
}
public String getusename() {
return prefs.getString("username","");
}
}
than use this way to get value SharedPreferences
session = new Session(getApplicationContext());
session.setusename("hello123");
String username=session.getusename();
Sample code
try {
if (!session.getusename().equals("")) {
System.out.println("it got here...");
Intent intent = new Intent(getApplication(), ActivityLogin.class);
startActivity(intent);
overridePendingTransition(R.anim.enter, R.anim.exit);
finish();
} else {
System.out.println("it got here...3");
Intent intent = new Intent(getApplication(), ActivityRegistration.class);
startActivity(intent);
finish();
overridePendingTransition(R.anim.enter, R.anim.exit);
}
}catch(Exception ex){
}
Instead of default shared preference, you can define a private one with your desired name in the Activity A..like as follows..
SharedPreferences preferences = getSharedPreferences("myPreferences",0);
SharedPreferences.Editor editor= preferences.edit();
editor.putString("userName","raju");
editor.commit();
If you want to retrieve that value from shared preferences in Activty A(I mean in the same activity), you can use following code..
String user_name= preferences.getString("userName","N/A");
or else in Activity B(I mean in some other activty), this time you don't need editor(for retrieval)..the code will be as follows
SharedPreferences preferences = getSharedPreferences("myPreferences",0);
String user_name= preferences.getString("userName","N/A");
I was creating notification Intent that opens one of two activities depending on condition. Worked as expected since I have all intent flags required for this.
I tried to optimize my method flow by extracting new Intent and Class, so optimized code looked like this:
Class ActivityClass;
if (siteId > 0) {
//...
ActivityClass = DetailActivity.class;
} else {
//...
ActivityClass = MainActivityWithMenu.class;
}
Intent notificationIntent = new Intent(appContext, ActivityClass);
But then my notification stopped opening activities, so I changed it to:
Intent notificationIntent = null;
if (siteId > 0) {
notificationIntent = new Intent(appContext, DetailActivity.class);
} else {
notificationIntent = new Intent(appContext, MainActivityWithMenu.class);
}
Second version works without any problems, but I was wondering what is the difference between Activity.class and Class class and why first snippet won't work with Intent?
Whole function:
String title = "Upcoming site:";
Intent notificationIntent = null;
if (siteId > 0) {
pref.setNewVar("notificationSiteId", String.valueOf(siteId));
notificationIntent = new Intent(appContext, DetailActivity.class);
} else {
notificationIntent = new Intent(appContext, MainActivityWithMenu.class);
}
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TASK);
notificationIntent.putExtra("siteId", siteId);
PendingIntent pendingIntent = PendingIntent.getActivity(appContext, 0,
notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Notification.Builder nBuilder = new Notification.Builder(appContext)
.setContentTitle("Neeco - " + title)
.setContentText(text)
.setSmallIcon(R.drawable.clock_start)
.setContentIntent(pendingIntent);
boolean updateNotification = true;
if (pref.getVar("notificationText") != null && !pref.getVar("notificationText").equals(text)) {
Log.d(TAG, "New text in notification - " + text);
nBuilder.setSound(alarmSound);
nBuilder.setPriority(priority);
pref.setNewVar("notificationText", text);
} else if (pref.getVar("notificationText") == null) {
nBuilder.setSound(alarmSound);
nBuilder.setPriority(priority);
pref.setNewVar("notificationText", text);
} else {
updateNotification = false;
}
if (updateNotification) {
Notification notification = nBuilder.build();
NotificationManager mNotificationManager = (NotificationManager) appContext.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(Config.NOTIFICATION_ID.FOREGROUND_SERVICE, notification);
}
Class
It's a compiled form of.Java file.
A class is a combination of methods, variables and data types. Every Java or Android project must have at least one class.
Android finally used this .class files to produce an executable Apk
Example:
public class Data{
int ID;
String Name;
public void First_Method()
{
}
}
Activity
An activity is the equivalent of a Frame/Window in GUI toolkits.
If we want to use an activity class, we must use extend Activity in your android project.
Example
public class Main_Activity extends Activity{
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
}
}
I would like to know how to bypass the "Touch to Configure" on my android widget programmatically. Once I have installed the android widget on my device it says "Touch to configure" which then executes my class "IntelligenWidgetConfig.java". But I want this to automatically happen on start up of my application. Can anyone advise me on how to approach this method or any solution that might help?
Android Config Class:
public class IntelliGenWidgetConfig extends Activity {
private static final String TAG = "IntelliGenWidgetConfig";
public IntelliGenWidgetConfig() {
super();
}
public static int getAppWidgetId(Context context) {
SharedPreferences settings = context.getSharedPreferences("Intelligen", MODE_PRIVATE);
return settings.getInt("appWidgetId", 1);
}
protected void setAppWidgetId(int id) {
SharedPreferences settings = getSharedPreferences("Intelligen", MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("appWidgetId", id);
editor.commit();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the result to CANCELED. This will cause the widget host to cancel
// out of the widget placement if they press the back button.
setResult(RESULT_CANCELED);
// Find the widget id from the intent.
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
setAppWidgetId(extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID));
}
// If they gave us an intent without the widget id, just bail.
if (getAppWidgetId(this) == AppWidgetManager.INVALID_APPWIDGET_ID) {
finish();
}
final Context context = IntelliGenWidgetConfig.this;
RegisterForPushNotification(context);
// Push widget update
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.intelligen_widget_layout);
appWidgetManager.updateAppWidget(getAppWidgetId(this), views);
// Make sure we pass back the original appWidgetId
Intent resultValue = new Intent();
resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, getAppWidgetId(this));
setResult(RESULT_OK, resultValue);
finish();
}
private void RegisterForPushNotification(Context ctx) {
Intent registerIntent = new Intent("com.google.android.c2dm.intent.REGISTER");
registerIntent.putExtra("app", PendingIntent.getBroadcast(ctx, 0, new Intent(), 0));
registerIntent.putExtra("sender", "209845001369");
startService(registerIntent);
}
private void DeregisterFromPushNotification(Context ctx) {
Intent unregisterIntent = new Intent("com.google.android.c2dm.intent.UNREGISTER");
unregisterIntent.putExtra("app", PendingIntent.getBroadcast(ctx, 0, new Intent(), 0));
startService(unregisterIntent);
}
}
AndroidManifest.xml (section):
<activity android:name=".IntelliGenWidgetConfig" android:label="#string/app_name">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE"/>
</intent-filter>
</activity>
XML
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider
xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="180dp"
android:minHeight="360dp"
android:updatePeriodMillis="0"
android:initialLayout="#layout/intelligen_widget_layout"
android:resizeMode="vertical"
android:minResizeWidth="280dp"
android:minResizeHeight="70dp"
android:configure="za.co.infotech.www.intelligen.IntelliGenWidgetConfig"
android:previewImage="#drawable/preview">
</appwidget-provider>