android home button pressed - android

please check this code completely and suggest me some ideas
i had executed this in android studio 3.0.1 and showing me no error but doesnt shows any ouput
HomeWatcher mHomeWatcher = new HomeWatcher(this);
mHomeWatcher.setOnHomePressedListener(new OnHomePressedListener() {
#Override
public void onHomePressed() {
// do something here...
}
#Override
public void onHomeLongPressed() {
}
});
mHomeWatcher.startWatch();
check this
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
public class HomeWatcher {
static final String TAG = "hg";
private Context mContext;
private IntentFilter mFilter;
private OnHomePressedListener mListener;
private InnerRecevier mRecevier;
public HomeWatcher(Context context) {
mContext = context;
mFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
}
public void setOnHomePressedListener(OnHomePressedListener listener) {
mListener = listener;
mRecevier = new InnerRecevier();
}
public void startWatch() {
if (mRecevier != null) {
mContext.registerReceiver(mRecevier, mFilter);
}
}
public void stopWatch() {
if (mRecevier != null) {
mContext.unregisterReceiver(mRecevier);
}
}
class InnerRecevier extends BroadcastReceiver {
final String SYSTEM_DIALOG_REASON_KEY = "reason";
final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
if (reason != null) {
Log.e(TAG, "action:" + action + ",reason:" + reason);
if (mListener != null) {
if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
mListener.onHomePressed();
} else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
mListener.onHomeLongPressed();
}
}
}
}
}
}
}
check this
public interface OnHomePressedListener {
public void onHomePressed();
public void onHomeLongPressed();
}
this code was not working for me i tried of toasting a msg when home button is pressed in onHomePressed() method but msg not display plz help me to get through it

You arenĀ“t supposed to see when users press the "Home" key, mostly for security reasons and consistent behaviour for the user.
(Except for special cases like Launchers)
Most methods of doing it have been disabled already, your method probably has been disabled aswell.

Related

center the text in a Full screen Dialog

I am trying to develop network app which shows a dialog when network is disconnected. I have made everything but the text inside the dialog is not centered.
package com.example.ayyappaboddupalli.networkchecker;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
/**
* Created by ayyappaboddupalli on 10/23/2017.
*/
public class ApplicationClass extends Application implements android.app.AlertDialog.OnDismissListener {
private static ApplicationClass mInstance;
private NetworkObserver networkObserver;
private NetworkDetector detector;
private AlertDialog.Builder ad = null;
private AlertDialog alertDialog;
public AlertDialog getAlertDialog() {
return alertDialog;
}
#Override
public void onCreate() {
super.onCreate();
networkObserver = new NetworkObserver();
}
public static ApplicationClass getmInstance() {
if (mInstance == null) {
synchronized (Object.class) {
mInstance = mInstance == null ? new ApplicationClass() : mInstance;
}
}
return mInstance;
}
public NetworkObserver getNetworkObserver() {
if (networkObserver == null) {
networkObserver = new NetworkObserver();
return networkObserver;
} else {
return networkObserver;
}
}
public void registerReceiver(Context context) {
detector = new NetworkDetector();
context.registerReceiver(detector, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
public void unRegisterReciver(Context context) {
try {
unregisterReceiver(detector);
} catch (Exception f) {
}
}
public void showDialog(Context context) {
if(alertDialog!=null)
{
alertDialog.dismiss();
}
ad = new AlertDialog.Builder(context);
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.weak_net_dialog, null);
ad.setView(view);
alertDialog = ad.create();
alertDialog.show();
alertDialog.setCancelable(false);
}
#Override
public void onDismiss(DialogInterface dialog) {
alertDialog=null;
}
}
public class NetworkDetector extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
boolean isNetOn=isnetworkOnline(context);
ApplicationClass.getmInstance().getNetworkObserver().setValue(isNetOn);
}
public boolean isnetworkOnline(Context context)
{
try {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//should check null because in airplane mode it will be null
return (netInfo != null && netInfo.isConnected());
} catch (NullPointerException e) {
e.printStackTrace();
return false;
}
}
}
public class NetworkObserver extends Observable {
private boolean netWorkOff=false;
public boolean isNetWorkOff() {
return netWorkOff;
}
public void setValue(boolean netWorkOff) {
this.netWorkOff = netWorkOff;
setChanged();
notifyObservers();
}
}
#Override
public void update(Observable o, Object arg) {
if(ApplicationClass.getmInstance().getNetworkObserver().isNetWorkOff()) {
Toast.makeText(getApplicationContext(),"Network is online",Toast.LENGTH_LONG).show();
if(ApplicationClass.getmInstance().getAlertDialog()!=null&&ApplicationClass.getmInstance().getAlertDialog().isShowing())
ApplicationClass.getmInstance().getAlertDialog().dismiss();
}
else
{
ApplicationClass.getmInstance().showDialog(this);
// Toast.makeText(getApplicationContext(),"Network is offline",Toast.LENGTH_LONG).show();
}
}
Try this:
android:layout_gravity="center"
use following lines in ur xml file:
android:center_vertical = true
android:center_horizontal=true
It will work if you are using relativeLayout
also set width to match_parent of your dialogue and editText

Mopub: integration with the Millennial Media native ads adapter

Does anyone know how to integrate the Millennial Media native ads adapter?
I read this page: https://support.millennialmedia.com/hc/en-us/articles/205081010-MoPub-Integrations
Downloaded the android adapters and then replace the APID with my APID, but don't know what the DCN is and I was unable to find it on their site.
I think I'm getting the error below because I have not inputted the DCN:
03-24 22:07:12.832 29491-29491/? D/MoPub: Attempting to invoke custom
event: com.mopub.nativeads.MillennialNative 03-24 22:07:12.850
29491-29491/? V/MoPub: Native Ad failed to load with error:
CustomEventNative was configured incorrectly.. 03-24 22:07:13.328
29491-29491/? D/MoPub: Attempting to invoke custom event:
com.mopub.nativeads.MoPubCustomEventNative
This is their adapter I'm using the Millennial Media:
package com.mopub.nativeads;
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import com.millennialmedia.AppInfo;
import com.millennialmedia.MMException;
import com.millennialmedia.MMSDK;
import com.millennialmedia.NativeAd;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static com.mopub.nativeads.NativeImageHelper.preCacheImages;
public class MillennialNative extends CustomEventNative {
public static final String DCN_KEY = "dcn";
public static final String APID_KEY = "XXX";
private final static String LOGCAT_TAG = "MoPub->MM-Native";
private static final Handler UI_THREAD_HANDLER = new Handler(Looper.getMainLooper());
public String siteId;
#Override
protected void loadNativeAd(final Activity activity,
final CustomEventNativeListener listener,
final Map<String, Object> localExtras,
final Map<String, String> serverExtras) {
String placementId;
if ( !MMSDK.isInitialized() ) {
try {
MMSDK.initialize(activity);
} catch ( Exception e ) {
Log.e(LOGCAT_TAG, "Unable to initialize the Millennial SDK-- " + e.getMessage());
e.printStackTrace();
UI_THREAD_HANDLER.post(new Runnable() {
#Override
public void run() {
listener.onNativeAdFailed(NativeErrorCode.NATIVE_ADAPTER_CONFIGURATION_ERROR);
}
});
return;
}
}
if ( extrasAreValid( serverExtras )) {
placementId = serverExtras.get(APID_KEY);
siteId = serverExtras.get(DCN_KEY);
} else {
UI_THREAD_HANDLER.post(new Runnable() {
#Override
public void run() {
listener.onNativeAdFailed(NativeErrorCode.NATIVE_ADAPTER_CONFIGURATION_ERROR);
}
});
return;
}
try {
AppInfo ai = new AppInfo().setMediator("mopubsdk");
if ( siteId != null && siteId.length() > 0 ) {
ai = ai.setSiteId(siteId);
} else {
ai = ai.setSiteId(null);
}
MMSDK.setAppInfo(ai);
} catch ( IllegalStateException e ) {
Log.w(LOGCAT_TAG, "Caught exception: " + e.getMessage());
UI_THREAD_HANDLER.post(new Runnable() {
#Override
public void run() {
listener.onNativeAdFailed(NativeErrorCode.NATIVE_ADAPTER_CONFIGURATION_ERROR);
}
});
return;
}
try {
NativeAd nativeAd = NativeAd.createInstance(placementId, NativeAd.NATIVE_TYPE_INLINE);
final MillennialStaticNativeAd millennialStaticNativeAd =
new MillennialStaticNativeAd(activity,
nativeAd,
new ImpressionTracker(activity),
new NativeClickHandler(activity),
listener);
millennialStaticNativeAd.loadAd();
} catch ( MMException e ) {
UI_THREAD_HANDLER.post(new Runnable() {
#Override
public void run() {
listener.onNativeAdFailed(NativeErrorCode.NATIVE_ADAPTER_CONFIGURATION_ERROR);
}
});
}
}
private boolean extrasAreValid(final Map<String, String> serverExtras) {
String placementId = serverExtras.get(APID_KEY);
return (serverExtras.containsKey(APID_KEY) &&
placementId != null && placementId.length() > 0 );
}
static class MillennialStaticNativeAd extends StaticNativeAd implements NativeAd.NativeListener {
private final Context mContext;
private NativeAd mNativeAd;
private final ImpressionTracker mImpressionTracker;
private final NativeClickHandler mNativeClickHandler;
private final CustomEventNativeListener mListener;
private final MillennialStaticNativeAd mMillennialStaticNativeAd;
public MillennialStaticNativeAd(final Context context,
final NativeAd nativeAd,
final ImpressionTracker impressionTracker,
final NativeClickHandler nativeClickHandler,
final CustomEventNativeListener customEventNativeListener) {
mContext = context.getApplicationContext();
mNativeAd = nativeAd;
mImpressionTracker = impressionTracker;
mNativeClickHandler = nativeClickHandler;
mListener = customEventNativeListener;
mMillennialStaticNativeAd = this;
nativeAd.setListener(this);
}
void loadAd() {
Log.i(LOGCAT_TAG, "Loading native ad...");
try {
mNativeAd.load(mContext, null);
} catch (MMException e) {
Log.w(MillennialNative.LOGCAT_TAG, "Caught configuration error Exception.");
e.printStackTrace();
UI_THREAD_HANDLER.post(new Runnable() {
#Override
public void run() {
mListener.onNativeAdFailed(NativeErrorCode
.NATIVE_ADAPTER_CONFIGURATION_ERROR);
}
});
}
}
// Lifecycle Handlers
#Override
public void prepare(final View view) {
// Must access these methods directly to get impressions to fire.
mNativeAd.getIconImage();
mNativeAd.getDisclaimer();
mImpressionTracker.addView(view, this);
mNativeClickHandler.setOnClickListener(view, this);
}
#Override
public void clear(final View view) {
mImpressionTracker.removeView(view);
mNativeClickHandler.clearOnClickListener(view);
}
#Override
public void destroy() {
mImpressionTracker.destroy();
mNativeAd.setListener(null);
mNativeAd = null;
}
// Event Handlers
#Override
public void recordImpression(final View view) {
notifyAdImpressed();
try {
mNativeAd.fireImpression();
Log.i(LOGCAT_TAG, "Millennial native impression recorded.");
} catch ( MMException m ) {
Log.e(LOGCAT_TAG, "Millennial native impression NOT tracked: " + m.getMessage() );
}
}
#Override
public void handleClick(final View view) {
notifyAdClicked();
mNativeClickHandler.openClickDestinationUrl(getClickDestinationUrl(), view);
mNativeAd.fireClicked();
Log.i(LOGCAT_TAG, "Millennial native ad clicked!");
}
// MM'S Native mListener
#Override
public void onLoaded(NativeAd nativeAd) {
// Set assets
String iconImageUrl = nativeAd.getImageUrl(NativeAd.ComponentName.ICON_IMAGE, 1);
String mainImageUrl = nativeAd.getImageUrl(NativeAd.ComponentName.MAIN_IMAGE, 1);
setTitle(nativeAd.getTitle().getText().toString());
setText(nativeAd.getBody().getText().toString());
setCallToAction(nativeAd.getCallToActionButton().getText().toString());
final String clickDestinationUrl = nativeAd.getCallToActionUrl();
if (clickDestinationUrl == null) {
UI_THREAD_HANDLER.post(new Runnable() {
#Override
public void run() {
Log.d(LOGCAT_TAG,
"Millennial native encountered null destination url. Failing over.");
mListener.onNativeAdFailed(
NativeErrorCode.NATIVE_ADAPTER_CONFIGURATION_ERROR);
}
});
return;
}
setClickDestinationUrl(clickDestinationUrl);
setIconImageUrl(iconImageUrl);
setMainImageUrl(mainImageUrl);
final List<String> urls = new ArrayList<String>();
if ( iconImageUrl != null ) { urls.add(iconImageUrl); }
if ( mainImageUrl != null ) { urls.add(mainImageUrl); }
UI_THREAD_HANDLER.post(new Runnable() {
#Override
public void run() {
// This has to be run on the main thread:
preCacheImages(mContext, urls, new NativeImageHelper.ImageListener() {
#Override
public void onImagesCached() {
mListener.onNativeAdLoaded(mMillennialStaticNativeAd);
Log.i(LOGCAT_TAG, "Millennial native ad loaded");
}
#Override
public void onImagesFailedToCache(NativeErrorCode errorCode) {
mListener.onNativeAdFailed(errorCode);
}
});
}
});
}
#Override
public void onLoadFailed(NativeAd nativeAd, NativeAd.NativeErrorStatus nativeErrorStatus) {
final NativeErrorCode error;
switch ( nativeErrorStatus.getErrorCode() ) {
case NativeAd.NativeErrorStatus.LOAD_TIMED_OUT:
error = NativeErrorCode.NETWORK_TIMEOUT;
break;
case NativeAd.NativeErrorStatus.NO_NETWORK:
error = NativeErrorCode.CONNECTION_ERROR;
break;
case NativeAd.NativeErrorStatus.UNKNOWN:
error = NativeErrorCode.UNSPECIFIED;
break;
case NativeAd.NativeErrorStatus.LOAD_FAILED:
case NativeAd.NativeErrorStatus.INIT_FAILED:
error = NativeErrorCode.UNEXPECTED_RESPONSE_CODE;
break;
case NativeAd.NativeErrorStatus.ADAPTER_NOT_FOUND:
error = NativeErrorCode.NATIVE_ADAPTER_CONFIGURATION_ERROR;
break;
case NativeAd.NativeErrorStatus.DISPLAY_FAILED:
case NativeAd.NativeErrorStatus.EXPIRED:
error = NativeErrorCode.UNSPECIFIED;
break;
default:
error = NativeErrorCode.NETWORK_NO_FILL;
}
UI_THREAD_HANDLER.post(new Runnable() {
#Override
public void run() {
mListener.onNativeAdFailed(error);
}
});
Log.i(LOGCAT_TAG, "Millennial native ad failed: " + nativeErrorStatus.getDescription() );
}
#Override
public void onClicked(NativeAd nativeAd, NativeAd.ComponentName componentName, int i) {
Log.i(LOGCAT_TAG, "Millennial native SDK's click tracker fired.");
}
#Override
public void onAdLeftApplication(NativeAd nativeAd) {
Log.i(LOGCAT_TAG, "Millennial native SDK has left the application.");
}
#Override
public void onExpired(NativeAd nativeAd) {
Log.i(LOGCAT_TAG, "Millennial native ad has expired!");
}
}
}

RunonUI Thread blocks a AsynTask in android from executing to completion

I have an issue with runOnuiThread and AsyncTask getting called together.
My AsynchTask gets data to populate a listView through runOnUIThread call.
This Asych Task can get data even when UI is not in focus . It starts from a UI screen and runs until application is logged out.
Now data coming from this Task can populate only a particular listview.
Now if i invoke another Asynch Task from another view using call executeOnExecutor call for AsynchTask, the Asynch Task does not run to compeltion. It locks up.
If I comment out code for the never ending AsychTask called Receiver.. then all UI's listview get populated and no Asych Task locks.
This Receiver waits on a REST API call for response to return but since I am running through executeonExecutor call, it should be parallel processing.
I need to have the receiver running all the time as that is an integral of my application.
What strategy can I use here to fix this issue.
Here are my code snippets.
public class Receiver {
private final static String QUEUE_NAME = "hello";
private String m_ErrorMessage;
private IRunOnUIThreadCallback iRunOnUIThreadCallback;
private Send m_Received;
private int m_TimeoutDuration;//how long the reading of new message waits in milli seconds
public void SetCallback(IRunOnUIThreadCallback runOnUIThreadCallback)
{
iRunOnUIThreadCallback = runOnUIThreadCallback;
}
public void SetTimeoutDuration(int timeout)
{
m_TimeoutDuration = timeout;
}
public void StartReceiver(Send receiverInfo)
{
String receivedInfo = null;
try {
new ReceiveInfo ().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, receiverInfo);
}
catch(Exception exp)
{
m_ErrorMessage = exp.getMessage();
}
}
private class ReceiveInfo extends AsyncTask<Send, Void, Send>
{
//initiate vars
public receive() {
super();
//my params here
}
protected Message doInBackground(Send... receiverInfo)
{
Send recv=null;
try {
PreferenceSingleton single = PreferenceSingleton.getInstance();
final User user = single.getUser();
final SvcApi svc = LoginAuthSvc.init();
Send send=(Send)receiverInfo[0];
send.setUserId(user.getUsername());
//dxbrem
while (true) {
recv=svc.receive(send);
String str= recv.get();
if ((str == null || (str.trim().length() == 0))) {
continue;
}
//DJ uncomment
iRunOnUIThreadCallback.RunAfterIsReceived(recv);
//messages.add(message);
System.out.println(" [x] Received '" + recv + "'");
}
}catch(Exception exp)
{
m_ErrorMessage = exp.getMessage();
}
return recv;
}
}
public String getErrorMessage() {
return m_ErrorMessage;
}
}
public interface IRunOnUIThreadCallback {
public void RunAfterIsReceived(ByteSent m);
public void RunAfterIsReceived(Send m);
}
The class that handles this.. has the following code and
public class MainFragment extends Fragment implements MFragment.OnFragmentInteractionListener, IRunOnUIThreadCallback {
private Receiver mReceiver;
public void SetUICallbackOnMessageReceiver()
{
mReceiver.SetCallback(this);
}
private void callRunUIThread(final SentInfo m) {
getActivity().runOnUiThread(new Runnable() {
public void run() {
if (m!= null) {
mGridArray.add(message);
if (mListAdapter != null) {
mListAdapter.notifyDataSetChanged();
mListView.setSelection(mListAdapter.getCount());
mListView.smoothScrollToPosition(mListAdapter.getCount());
}
}
}
}); // end of runOnUiThread
}
#Override
public void RunAfterIsReceived(ByteSent m) {
}
#Override
public void RunAfterIsReceived(Sent m) {
SentInfo m= new SentInfo(false, recv.getInfo());
callRunUIThread(msg);
}
mListAdapter is the ListAdapater
mListView is the ListView
Here is the AsynchTask code
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
public class CallableTask<T> extends AsyncTask<Void,Double,T> {
private static final String TAG = CallableTask.class.getName();
public static <V> void invoke(Callable<V> call,Activity activity, TaskCallback<V> callback){
new CallableTask<V>(activity,call, callback).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR );
}
private Callable<T> callable_;
private AsyncTask<Void, Void, String> asyncTask_;
private Context context;
private Activity activity;
private Fragment fragmentActivity;
private android.support.v4.app.Fragment dynamicFragment;
private TaskCallback<T> callback_;
private Exception error_;
public CallableTask(Fragment actvy,Callable<T> callable, TaskCallback<T> callback) {
callable_ = callable;
callback_ = callback;
fragmentActivity=actvy;
}
public CallableTask(Activity actvy,Callable<T> callable, TaskCallback<T> callback) {
callable_ = callable;
callback_ = callback;
activity=actvy;
}
#Override
protected T doInBackground(Void... ts) {
T result = null;
try{
result = callable_.call();
} catch (Exception e){
Log.e(TAG, "Error invoking callable in AsyncTask callable: " + callable_, e);
error_ = e;
}
return result;
}
#Override
protected void onPostExecute(T r) {
if(error_ != null){
callback_.error(error_);
}
else {
callback_.success(r,activity);
}
}
public static <V> void invoke(Callable<V> call, Fragment _frg, TaskCallback<V> callback) {
new CallableTask<V>(_frg,call, callback).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR );
}
// public CallableTask(android.support.v4.app.Fragment chatActivity,Callable<T> callable, TaskCallback<T> callback) {
// callable_ = callable;
// callback_ = callback;
// dynamicFragment=chatActivity;
// }
public CallableTask(android.support.v4.app.Fragment actvy,Callable<T> callable, TaskCallback<T> callback) {
callable_ = callable;
callback_ = callback;
dynamicFragment=actvy;
}
public static <V> void invoke(Callable<V> call, android.support.v4.app.Fragment _frg, TaskCallback<V> callback) {
new CallableTask<V>(_frg,call, callback).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR );
}
}
This gets called here... only when clicking on a button Send.
CallableTask.invoke(new Callable<Sent>() {
#Override
public Sent call() throws Exception {
}, this, new TaskCallback<Sent>() {
#Override
public void success(Sent result, Context context) {
mGridArray.add(result);
if (mListAdapter != null) {
mListAdapter.notifyDataSetChanged();
mListView.setSelection(mListAdapter.getCount());
mListView.smoothScrollToPosition(mListAdapter.getCount());
}
#Override
public void error(Exception e) {
}
});
Thanks
Dhiren
I finally resolved this by running a Asynch.cancel call on the thread from the activity fragment that started this thread. when I move away from activity. If I did not , it blocked any other tasks from running,

Android AIDL and Service and Activity parceable seems to be passing default class values

I have a strange issue going on, I have created an Android service, and a widget that consumes it. I have some complex objects that are sent between the two via AIDL. I have no problems registering my callbacks, and the service is populating the data correctly and sending it to the callbacks, but when I put a breakpoint on the writeToParcel method, and activate my debugger on the widget, I notice that the method is serializing the default class values, and not the ones the service populated it with. Does anyone have any suggestions for figuring out what is going on.
Here is my object:
Node.java:
package my.unique.package.name.service;
import java.util.ArrayList;
import java.util.HashMap;
import android.os.Parcel;
import android.os.Parcelable;
public class Node implements Parcelable {
protected int mNodeId;
protected double mBatteryLevel = -1;
protected double mBatteryTemp;
protected String mRadioName;
protected String mIPAddress;
protected String mFirmwareVersion;
protected String mModel;
protected String mSerialNumber;
protected String mUptime;
protected double mTemp;
protected double mInputVoltage;
protected double mBatteryClockVoltage;
protected String mSource;
protected double mLatitude;
protected double mLongitude;
protected double mAltitude;
protected String mFixType;
protected int mSatellites;
protected String mNTPServer;
protected ArrayList<Neighbor> mNeighbors;
protected HashMap<String, String> mManagedNodes;
protected HashMap<String, String> mOtherNodes;
public Node()
{
}
/**
* Node Constructor for Parcelable Interface
*
* #param in
* Parcel in
*/
public Node(Parcel in) {
String[] data = new String[19];
in.readStringArray(data);
mNodeId = Integer.parseInt(data[0]);
mBatteryLevel = Double.parseDouble(data[1]);
mBatteryTemp = Double.parseDouble(data[2]);
mRadioName = data[3];
mIPAddress = data[4];
mFirmwareVersion = data[5];
mModel = data[6];
mSerialNumber = data[7];
mUptime = data[8];
mTemp = Double.parseDouble(data[9]);
mInputVoltage = Double.parseDouble(data[10]);
mBatteryClockVoltage = Double.parseDouble(data[11]);
mSource = data[12];
mLatitude= Double.valueOf(data[13]);
mLongitude = Double.valueOf(data[14]);
mAltitude = Double.valueOf(data[15]);
mFixType = data[16];
mSatellites = Integer.valueOf(data[17]);
mNTPServer = data[18];
}
//Removed public get/set methods...
public static final Parcelable.Creator<Node> CREATOR = new Parcelable.Creator<Node>() {
public Node createFromParcel(Parcel in) {
return new Node(in);
}
public Node[] newArray(int size) {
return new Node[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[] { String.valueOf(mNodeId),
String.valueOf(mBatteryLevel), String.valueOf(mBatteryTemp),
mRadioName, mIPAddress, mFirmwareVersion, mModel,
mSerialNumber, mUptime, String.valueOf(mTemp),
String.valueOf(mInputVoltage),
String.valueOf(mBatteryClockVoltage),
mSource, String.valueOf(mLatitude), String.valueOf(mLongitude),
String.valueOf(mAltitude), mFixType,
String.valueOf(mSatellites), mNTPServer});
}
}
Node.aidl:
package my.unique.package.namespace.service;
parcelable Node;
This is how the service notifies callbacks
private void notifyCallbacksOfUpdate(Node updated) {
final int N = mNodeUpdatedCallbacks.beginBroadcast();
for (int i = 0; i < N; i++) {
try {
mNodeUpdatedCallbacks.getBroadcastItem(i).NodeUpdated(updated);
} catch (RemoteException e) {
// The RemoteCallbackList will take care of removing
// the dead object for us.
}
}
mNodeUpdatedCallbacks.finishBroadcast();
}
EDIT: Additional Code from consumer
MyApplication.java
public void bindConnection()
{
if (mServiceConnection == null) {
// create connection to service
mServiceConnection = new MyServiceConnection(this);
Intent i = new Intent("my.unique.package.IService");
boolean bound = bindService(i, mConnection,
Context.BIND_AUTO_CREATE);
Log.v("Service Bound: ", String.valueOf(bound));
}
}
Connection Class
import my.unique.package.service.IService;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
public class MyServiceConnection implements ServiceConnection {
private IService service;
private Context mContext;
public MyServiceConnection(Context context)
{
mContext = context;
}
public void onServiceConnected(ComponentName name, IBinder boundService) {
service = IService.Stub.asInterface(boundService);
if(service != null)
{
mContext.sendBroadcast(new Intent(MyApplication.BOUND_TO_SERVICE));
}
}
public void onServiceDisconnected(ComponentName name) {
service = null;
}
protected IService getService()
{
return service;
}
}
In here is where I get notified of updates to the node, service sends correct info, but here is where it receives the default values. The node object class is in the same jar as the service and widget, just different packages, does the AIDL need to be copied to all of the packages, or can it reference it cross packages.
private INodeUpdatedCallback nodeUpdated = new INodeUpdatedCallback.Stub() {
#Override
public void NodeUpdated(Node nodeInfo) throws RemoteException {
Log.v("Node Updated: ", nodeInfo.getRadioIP());
if (nodeInfo.getIP().equalsIgnoreCase(mIp)
&& requestedLogin) {
requestedLogin = false;
ViewSwitcher vs = (ViewSwitcher) findViewById(R.id.vsSettings);
if (vs.getDisplayedChild() != VIEW_SETTINGS) {
vs.setInAnimation(AnimationUtils.loadAnimation(
WaveRelaySettingsActivity.this, R.anim.fade_in));
vs.setOutAnimation(AnimationUtils.loadAnimation(
WaveRelaySettingsActivity.this, R.anim.fade_out));
vs.setDisplayedChild(VIEW_SETTINGS);
}
}
}
};
Aidl for stub of callback
package my.unique.namespace.service;
import my.unique.namespace.service.Node;
oneway interface INodeUpdatedCallback {
void NodeUpdated(out Node nodeInfo);
}
I believe you need to change out to in in your AIDL.
package my.unique.namespace.service;
import my.unique.namespace.service.Node;
oneway interface INodeUpdatedCallback {
void NodeUpdated(in Node nodeInfo);
}

Why main thread can't update UI elements inside a horizontallistview?

Last few days I'm trying to update some UI Views inside a custom HorizontalListView. I've been trying countless way like using Async Task, posting message via handler etc. I didn't figure out to update them. As a result, I tried to build a queue system to update them one by one. Here is my code and it's still not updating them.
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import roboguice.RoboGuice;
import CustomChannel;
import EGPInfo;
import android.content.Context;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;
public class EPGLoader {
static private EPGLoader _instance;
public static EPGLoader getInstance(Context context) {
if (_instance == null) {
_instance = new EPGLoader();
}
mContext = context;
return _instance;
}
private HashMap<String, WeakReference<EPGChannel>> _cachedChannels;
private Queue<EPGChannel> _queue;
private EPGThread _thread;
private static Context mContext;
private boolean _isBusy;
public EPGLoader() {
_cachedChannels = new HashMap<String, WeakReference<EPGChannel>>();
_queue = new LinkedList<EPGChannel>();
_isBusy = false;
}
public void load(ArrayList<TextView> textViews, CustomChannel channel) {
Iterator<EPGChannel> it = _queue.iterator();
EPGChannel epgChannel = new EPGChannel();
epgChannel.setChannel(channel);
epgChannel.setTextViews(textViews);
while (it.hasNext()) {
if (it.next().equals(epgChannel)) {
it.remove();
break;
}
}
_queue.add(epgChannel);
loadNext();
}
private void loadNext() {
Iterator<EPGChannel> it = _queue.iterator();
if (!_isBusy && it.hasNext()) {
_isBusy = true;
EPGChannel epgChannel = it.next();
it.remove();
EPGChannel epgCache = get(epgChannel.getChannel().getChannelId());
if (epgCache != null) {
Log.i("A", "Cache");
epgChannel.textViews.get(0).setText("1");
epgChannel.textViews.get(1).setText("2");
epgChannel.textViews.get(2).setText("3");
epgChannel.textViews.get(3).setText("4");
_isBusy = false;
loadNext();
} else {
_thread = new EPGThread(epgChannel);
_thread.start();
Log.i("A", "Live");
}
}
}
private EPGChannel get(String channelId) {
if (_cachedChannels.containsKey(channelId)) {
return _cachedChannels.get(channelId).get();
} else {
return null;
}
}
private class EPGThread extends Thread {
private EPGChannel EPGChannel;
final Handler threadHandler = new Handler();
final Runnable threadCallBack = new Runnable() {
#Override
public void run() {
onLoad();
}
};
public EPGThread(EPGChannel epgChannel) {
this.EPGChannel = epgChannel;
}
private void onLoad() {
if (_thread != null) {
EPGChannel epgChannel = _thread.EPGChannel;
// epgChannel.getTextViews().get(1).setText(epgChannel.getChannel().getName());
epgChannel.getTextViews().get(0).setText("1");
epgChannel.getTextViews().get(1).setText("2");
epgChannel.getTextViews().get(2).setText("3");
epgChannel.getTextViews().get(3).setText("4");
}
_thread = null;
_isBusy = false;
loadNext();
}
#Override
public void run() {
try {
_isBusy = true;
ChannelManager channelManager = RoboGuice.getInjector(mContext).getInstance(ChannelManager.class);
ArrayList<EGPInfo> epgInfo = channelManager.getChannelEPG(EPGChannel.getChannel().getChannelId());
if (epgInfo.size() == 2) {
EPGChannel.getChannel().updateEPGInformations(epgInfo.get(0), epgInfo.get(1));
}
if (!_cachedChannels.containsKey(EPGChannel.getChannel().getChannelId()))
_cachedChannels.put(EPGChannel.getChannel().getChannelId(), new WeakReference<EPGLoader.EPGChannel>(EPGChannel));
} catch (Exception e) {
e.printStackTrace();
} finally {
threadHandler.post(threadCallBack);
}
}
}
private class EPGChannel {
private ArrayList<TextView> textViews;
private CustomChannel channel;
public ArrayList<TextView> getTextViews() {
return textViews;
}
public void setTextViews(ArrayList<TextView> textViews) {
this.textViews = textViews;
}
public CustomChannel getChannel() {
return channel;
}
public void setChannel(CustomChannel channel) {
this.channel = channel;
}
}
}
I call it from main thread when getView event of ArrayAdapter fires.
#Override
public View getView(int position, View retval, ViewGroup parent) {
if (retval == null) {
retval = LayoutInflater.from(parent.getContext()).inflate(R.layout.channel_item, null);
}
final CustomChannel currentChannel = getItem(position);
final TextView nowTitle = (TextView) retval.findViewById(R.id.channel_item_current_show_title);
final TextView nowPlayTime = (TextView) retval.findViewById(R.id.channel_item_current_show_play_time);
final TextView nextTitle = (TextView) retval.findViewById(R.id.channel_item_next_show_title);
final TextView nextPlayTime = (TextView) retval.findViewById(R.id.channel_item_next_show_play_time);
ArrayList<TextView> textViews = new ArrayList<TextView>();
textViews.add(nowTitle);
textViews.add(nowPlayTime);
textViews.add(nextTitle);
textViews.add(nextPlayTime);
EPGLoader.getInstance(mContext).load(textViews, currentChannel);
return retval;
}
So, what is wrong with my codes? Thanks in advance.
Edit: I replace the HorizontalListView with normal Android's ListView and it works but I have to use HorizontalListView in the project. Any suggesstions?
Edit 2: I reward to back (HorizontalListView) and tried to set Background color of some UI controllers, guess what? It updated. It doesn't update text property!!! Why????

Categories

Resources