I m developing an android app.
The main activity is a preferencescreen
public class MainActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
my app contains also a service that start automatically when the android boot.
In the onStart() of my service class, I m trying to retrieve data saved by the user in the preferencescreen with the following code
public void onStart(Intent intent, int startId) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
get_prefrence_settings((Preference) preferences);
jniTask = new JniBackGround();
jniTask.execute(new String[] { "http://www.easycwmp.org" });
}
private void get_prefrence_settings(Preference p) {
if (p instanceof PreferenceGroup) {
PreferenceGroup pGrp = (PreferenceGroup) p;
for (int i = 0; i < pGrp.getPreferenceCount(); i++) {
get_prefrence_settings(pGrp.getPreference(i));
}
} else {
if (p instanceof ListPreference) {
ListPreference listPref = (ListPreference) p;
p.setSummary(listPref.getEntry());
client_interface = (String) listPref.getEntry();
}
if (p instanceof CheckBoxPreference) {
if (((TwoStatePreference) p).isChecked())
enable = "1";
}
if (p instanceof EditTextPreference) {
if (pref_key.equals("Time")) {
time = editTextPref.getText();
}
}
}
}
but I m getting a crash when my service start that indicate that:
android.app.SharedPreferencesImpl can not be cast to android.preference.Preference
How to retrieve the preference settings from my onStart() service without loading the MainActivity interface?
How to retrieve the preference settings from my onStart() service without loading the MainActivity interface?
Call getString(), getInt(), or related getter methods on the SharedPreferences object.
Related
The following code serves as my handler when the user taps a push notification. The code is working properly and launchURL is accurately recorded in my log. However, as a next step I would like to direct the user to an activity called ViewPushLink. I have attempted to follow similar instructions found elsewhere on S.O., but as a newbie, I would appreciate some specific help.
class ExampleNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
public static String launchURL;
#Override
public void notificationOpened(OSNotificationOpenResult result) {
OSNotificationAction.ActionType actionType = result.action.type;
JSONObject data = result.notification.payload.additionalData;
if (data != null) {
launchURL = data.optString("launchURL");
if (launchURL != null) {
Log.i("OneSignalExample", "launchURL value: " + launchURL);
}
}
}
}
EDIT: ExampleNotificationOpenedHandler is called from my Main Activity as show below:
public class MainActivity extends AppCompatActivity {
private ProgressDialog progress;
public static boolean isNetworkStatusAvailable (Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null)
{
NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
if(netInfos != null)
if(netInfos.isConnected())
return true;
}
return false;
}
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
// OneSignal Initialization
OneSignal.startInit(this)
.inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
.unsubscribeWhenNotificationsAreDisabled(true)
.setNotificationOpenedHandler(new ExampleNotificationOpenedHandler())
.init();
Change your Activity to this; Surely it will help you.
class ExampleNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
public static String launchURL;
#Override
public void notificationOpened(OSNotificationOpenResult result) {
OSNotificationAction.ActionType actionType = result.action.type;
JSONObject data = result.notification.payload.additionalData;
if (data != null) {
launchURL = data.optString("launchURL");
if (launchURL != null) {
Log.i("OneSignalExample", "launchURL value: " + launchURL);
Intent intent = new Intent(getApplicationContext, ViewPushLink.class)
startActivity(intent);
}
}
}
}
Put your code in the Application Class of your project.
For push notification handling using the OneSignal SDK, three things need to be considered.{if your project has multiple fragments and one Main Activity(Navigation Drawer Activity) and rest of other activities get called from the fragments of MainActivity}
Target Activity
Related Actions like, which part of your
activity, which fragment you want to open, differentiate which each
with some action that you can find in the jsonObject Data
Intent
Flags, an example you want to open an Activity, whose instance is
already in backStack, so you may want to clear the back stack and
open the new instance of the activity or may open the same instance.
Example:
public XYZApplication extends Application{
class ExampleNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
public static String launchURL;
#Override
public void notificationOpened(OSNotificationOpenResult result) {
OSNotificationAction.ActionType actionType = result.action.type;
JSONObject data = result.notification.payload.additionalData;
if (data != null) {
String target = data.optString("target");
String action = "";
switch (target) {
case "xyz":
action = data.optString("action");
Utils.setTarget(target);
if (action.equalsIgnoreCase("xyz")
|| action.equalsIgnoreCase("abc")) {
Intent xyzIntent = new Intent(getApplicationContext(), XYZActivity.class);
homeIntent.putExtra("action_key", "action_xyz");
homeIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(xyzIntent);
}
for more details refer to one signal SDK Documentation
https://documentation.onesignal.com/docs
I'd appreciate if you could advise on my problem.
I'm working on AR app using Vuforia SDK for Unity3D and Android plugins.
I have several ImageTargets and 3D models on my scene.
My class that works with android plugin looks like this:
public class AssetBundleAugmenter : MonoBehaviour, ITrackableEventHandler
{
void Start()
{
StartCoroutine(DownloadAndCache());
mTrackableBehaviour = GetComponent<TrackableBehaviour>();
if (mTrackableBehaviour)
{
mTrackableBehaviour.RegisterTrackableEventHandler(this);
}
init();
}
public void OnTrackableStateChanged(
TrackableBehaviour.Status previousStatus,
TrackableBehaviour.Status newStatus)
{
if (newStatus == TrackableBehaviour.Status.DETECTED ||
newStatus == TrackableBehaviour.Status.TRACKED ||
newStatus == TrackableBehaviour.Status.EXTENDED_TRACKED)
{
if (!mAttached && mBundleInstance)
{
// if bundle has been loaded, let's attach it to this trackable
//...
}
OnTrackingFound();
}
else
{
OnTrakingLost();
}
}
private void OnTrackingFound()
{
if (mTrackableBehaviour is ImageTargetAbstractBehaviour)
{
GetJavaObject().Call("OnMarkerFound");
}
}
void onButtonClicked(int index)
{
//Changing current 3D model material
}
#if UNITY_ANDROID
private AndroidJavaObject javaObj = null;
//LISTENING TO BUTTON CLICK EVENTS FROM ANDROID
private sealed class EventListner : AndroidJavaProxy
{
private AssetBundleAugmenter mReceiver;
public EventListner(AssetBundleAugmenter receiver)
: base("com.mypackage.myapp.ImageTargetTracker$Listner")
{
mReceiver = receiver;
}
public void onButtonClicked(int index) //change color of model
{
mReceiver.onButtonClicked(index);
}
}
private AndroidJavaObject GetJavaObject()
{
if (javaObj == null)
{
javaObj = new AndroidJavaObject("com.mypackage.myapp.ImageTargetTracker");
}
return javaObj;
}
AndroidJavaObject activity;
private void init()
{
// Retrieve current Android Activity from the Unity Player
AndroidJavaClass jclass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
activity = jclass.GetStatic<AndroidJavaObject>("currentActivity");
// Pass reference to the current Activity into the native plugin,
GetJavaObject().Call("setActivity", activity, new EventListner(this));
}
#else
void init() {}
#endif
}
So I attached this script to all of my ImageTargets on the scene, which I know must be wrong, because UnityPlayer gets initialized several times in my init() function.
I tried to attach the script to ARCamera on my scene, and write initialization only there, but I'm not sure how to access currentActivity in scripts that work with ImageTargets. Also, I use listener - the interface in my plugin that listens to button clicks to fire some functionality in unity.
My plugin code:
public class ImageTargetTracker {
public static interface Listner {
public void onButtonClicked(int index);
}
private Listner mListner;
protected Activity mCurrentActivity;
public void setActivity(Activity activity, Listner listner)
{
mCurrentActivity = activity;
mListner = listner;
mCurrentActivity.runOnUiThread(new Runnable() {
public void run() {
LayoutInflater inflater = mCurrentActivity.getLayoutInflater();
Resources resources = mCurrentActivity.getResources();
String pkgName = mCurrentActivity.getPackageName();
int id = resources.getIdentifier("camera_layout", "layout", pkgName);
View view = inflater.inflate(id, null);
mCurrentActivity.addContentView(view, param);
//INITIALIZING UI ELEMENTS HERE (DISPLAYED ON TOP OF CAMERA)
}
public void OnMarkerFound(){
mCurrentActivity.runOnUiThread(new Runnable() {
public void run() {
//Showing some UI elements
}
});
}
}
So, how can I globally initialize the Activity and my plugin class in Unity one time, and use them in all of my scripts?
As discussed in the comments, I recommend using the singleton pattern.
In my app once user provide three inputs, AsyncTask starts which connects to the server and gets info for two more fields. Once AsyncTask is finished, I want to set those two received values in opened setting page.
I searched and try this code, but not updating summary for fields for which value has fetched from server.
Problem is I'm not able to set values received from server as summary to EditTextPreference. If I reopen settngs page it shows value not without reopening.
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
updatePreference(key);
}
private void updatePreference(String key) {
if (key.equals("id")) {
Preference preference = findPreference(key);
if (preference instanceof EditTextPreference) {
EditTextPreference editTextPreference = (EditTextPreference) preference;
if (editTextPreference.getText().trim().length() > 0) {
editTextPreference.setSummary(editTextPreference.getText());
} else {
editTextPreference.setSummary("");
}
}
} else if (key.equals("sclass")) {
Preference preference = findPreference(key);
if (preference instanceof EditTextPreference) {
EditTextPreference editTextPreference = (EditTextPreference) preference;
if (editTextPreference.getText().trim().length() > 0) {
editTextPreference.setSummary(editTextPreference.getText());
} else {
editTextPreference.setSummary("");
}
}
}
}
Create a listener and call it in your onCreate
sharedPrefYourObj.registerOnSharedPreferenceChangeListener(this);
try to register you listener onResume and unregister it onPause though rather than onCreate!
example :
protected void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
protected void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
I'm writing an app for the Sony Smartwatch, using their SDK. Here's part of the main activity:
class SmartTickerActivity extends ControlExtension {
private Handler mHandler;
SmartTickerActivity(final String hostAppPackageName, final Context context, Handler handler) {
super(context, hostAppPackageName);
if (handler == null) {
throw new IllegalArgumentException("handler == null");
}
}
#Override
public void onStart() {
//do some stuff
PreferenceManager.setDefaultValues(mContext, R.xml.preference, false);
}
The problem is that the saved preferences aren't being applied on the Smartwatch when the application launches. Nor are the default preference values from XML. However, if I click on any of the app's preferences on the phone, the saved preference values are immediately applied to the Smartwatch.
Note that the main class has no onCreate() method, and that's throwing me for a loop.
Here's part of the Preference activity:
public class MyPreferenceActivity extends PreferenceActivity {
private OnSharedPreferenceChangeListener mListener = new OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Preference pref = findPreference(key);
if (pref instanceof ListPreference) {
ListPreference listPref = (ListPreference) pref;
pref.setSummary(listPref.getEntry().toString());
}
if (pref instanceof EditTextPreference) {
EditTextPreference editTextPref = (EditTextPreference) pref;
pref.setSummary(editTextPref.getText().toString());
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preference);
setSummaries();
setTypeface(SmartTickerActivity.mainLayout);
if (previewLayout != null) setTypeface(previewLayout);
// Handle read me
Preference readMe = findPreference(getText(R.string.preference_key_read_me));
readMe.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference readMe) {
showDialog(DIALOG_READ_ME);
return true;
}
});
// Handle about
Preference about = findPreference(getText(R.string.preference_key_about));
about.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference about) {
showDialog(DIALOG_ABOUT);
return true;
}
});
// Handle preview
Preference preview = findPreference(getText(R.string.preference_key_preview_dialog));
preview.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preview) {
showDialog(DIALOG_PREVIEW);
return true;
}
});
}
I'm rather inexperienced at Android development, so the problem might very well have nothing to do whatsoever with the Sony SDK. Can anyone help?
You are correct, the preferences of the official sample extensions are not loaded until the PreferenceActivity is shown for the first time. If you use correct default values when accessing the preferences, this should not be a problem.
If you would like for the preferences to be loaded when the extension is initiated the first time, you could extend the android.app.Application class, and the onCreate method.
For example:
public class MySmartWatchApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
PreferenceManager.setDefaultValues(this, R.xml.app_preferences, false);
}
}
My application has a few activities, and a background service. My question is, if I have the context variable in the service, how can I tell which activity is currently open? I need to do this to direct the next action my service takes. For example,
if (context is activity_1) {
//take this action
} else if (context is activity_2) {
//do this instead...
}
That's the basic gist of what I'm trying to do.
Help much appreciated.
You could set a SharedPreferences entry in each onResume() method of your activities and read that value from the service. To keep it clean you could write an Activity that does that and then extend all your activities from it:
public class MyActivity extends Activity {
private static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onResume() {
getContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
.edit()
.putInt("activtiyIdRunning", getActivityId() )
.commit();
super.onResume();
}
abstract protected int getActivityId();
}
public class MyConcreteActivity1 extends MyActivity {
#Override
protected int getActivityId() {
return 1;
}
// your normal code
}
in your service than just call:
int currentActivity = getContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
.getInt("activityIdRunning",-1);