How can i get lock unlock screen on emulator in android? - android

Recently I am doing one project in emulator lock and unlock screen. I put one button. I want to do that if i press that button I want to lock the phone.
my problem is when i press the button nothing is happening.
please give me any idea about this.
how i get lock unlock perform using this code.
public class Test extends Activity implements OnClickListener{
/** Called when the activity is first created. */
Button btn1;
private KeyguardManager mKeyguardManager;
private KeyguardManager.KeyguardLock mKeyguardLock;
private static final String TAG = "ALERTLock";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn1=(Button)findViewById(R.id.button1);
btn1.setOnClickListener(this);
int flags = getFlagsForVersion();
getWindow().addFlags(flags);
mKeyguardManager = (KeyguardManager)
getSystemService(Context.KEYGUARD_SERVICE);
}
public void onClick(View v) {
// TODO Auto-generated method stub
if(v==btn1)
{
disableKeyguard();
}
else
{
enableKeyguard();
}
}
private int getFlagsForVersion() {
final String possibleFlags[] = new String[] {
"FLAG_SHOW_WHEN_LOCKED",
"FLAG_DISMISS_KEYGUARD",
"FLAG_TURN_SCREEN_ON"
};
int flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
for(String flag:possibleFlags) {
try {
Field field = WindowManager.LayoutParams.class.getField(flag);
int value = field.getInt(null);
flags |= value;
}
catch(NoSuchFieldException e) { }
catch(IllegalAccessException e) { }
}
return flags;
}
private synchronized void enableKeyguard() {
if (mKeyguardLock != null) {
mKeyguardLock.reenableKeyguard();
mKeyguardLock = null;
}
}
private synchronized void disableKeyguard() {
if (mKeyguardLock == null) {
mKeyguardLock = mKeyguardManager.newKeyguardLock(TAG);
mKeyguardLock.disableKeyguard();
}
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
disableKeyguard();
}
#Override
public void onResume() {
super.onResume();
disableKeyguard();
}
}

//try this once
and check the logcat is printing the line enable
public void onClick(View v) {
switch(v.getId()){
case R.id.button1:
//do this
Log.d("clicked enable","-----");
enableKeyguard();
break;
}

Related

sinch conference call hung up right after it starts

I managed to start a conference call cut it closes right after I start it with HUNG_UP cause and I got this in my log:
11-03 17:28:08.940: E/sinch-android-rtc(19101): peermediaconnection: virtual void rebrtc::SetSDPObserver::OnFailure(const string&)Failed to set remote answer sdp: Offer and answer descriptions m-lines are not matching. Rejecting answer.
11-03 17:28:08.940: E/sinch-android-rtc(19101): mxp: Failed to set remote answer sdp: Offer and answer descriptions m-lines are not matching. Rejecting answer.
can anybody help me solve this please?
Edit:
my scenario is when a user clicks the call button I ask him if he wants to start a new call or join an already created one.
I managed to make my code from this question (Sinch conference call error) work as my GroupService class had some bugs.
I start my call like this:
Intent intent1 = new Intent(CreateGroupCallActivity.this,SinchClientService.class);
intent1.setAction(SinchClientService.ACTION_GROUP_CALL);
String id = String.valueOf(uid) + "-" + call_id.getText().toString();
intent1.putExtra(SinchClientService.INTENT_EXTRA_ID,id);
startService(intent1);
and in my SinchClientService:
if(intent.getAction().equals(ACTION_GROUP_CALL))
{
String id = intent.getStringExtra(INTENT_EXTRA_ID);
if(id != null)
groupCall(id);
}
public void groupCall(String id) {
if (mCallClient != null) {
Call call = mCallClient.callConference(id);
CurrentCall.currentCall = call;
Log.d("call", "entered");
Intent intent = new Intent(this, GroupCallService.class);
startService(intent);
}
}
nd here is my GroupCallService
public class GroupCallScreenActivity extends AppCompatActivity implements ServiceConnection {
private SinchClientService.MessageServiceInterface mMessageService;
private GroupCallService.GroupCallServiceInterface mCallService;
private UpdateReceiver mUpdateReceiver;
private ImageButton mEndCallButton;
private TextView mCallDuration;
private TextView mCallState;
private TextView mCallerName;
//private TextView locationview;
private ImageView user_pic;
private long mCallStart;
private Timer mTimer;
private UpdateCallDurationTask mDurationTask;
ImageButton chat;
ImageButton speaker;
ImageButton mic;
boolean speaker_on = false;
boolean mic_on = true;
PowerManager mPowerManager;
WakeLock mProximityWakeLock;
final static int PROXIMITY_SCREEN_OFF_WAKE_LOCK = 32;
com.galsa.example.main.ImageLoader mImageLoader;
/*String location;
String longitude;
String latitude;*/
private class UpdateCallDurationTask extends TimerTask {
#Override
public void run() {
GroupCallScreenActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
updateCallDuration();
}
});
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
setContentView(R.layout.callscreen);
doBind();
mCallDuration = (TextView) findViewById(R.id.callDuration);
mCallerName = (TextView) findViewById(R.id.remoteUser);
mCallState = (TextView) findViewById(R.id.callState);
//locationview = (TextView) findViewById(R.id.location);
mEndCallButton = (ImageButton) findViewById(R.id.hangupButton);
chat = (ImageButton) findViewById(R.id.chat);
chat.setVisibility(View.GONE);
speaker = (ImageButton) findViewById(R.id.speaker);
mic = (ImageButton) findViewById(R.id.mic);
user_pic = (ImageView) findViewById(R.id.user_pic);
/*location = getIntent().getStringExtra("location");
longitude = getIntent().getStringExtra("longitde");
latitude = getIntent().getStringExtra("latitude");
locationview.setText(location);*/
mImageLoader = new com.galsa.example.main.ImageLoader(GroupCallScreenActivity.this, R.dimen.caller_image_height);
//mCallerName.setText(mCall.getRemoteUserId());
mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
mProximityWakeLock = mPowerManager.newWakeLock(PROXIMITY_SCREEN_OFF_WAKE_LOCK, Utils.TAG);
/*chat.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(GroupCallScreenActivity.this, MessagingActivity.class);
intent.putExtra(SinchClientService.INTENT_EXTRA_ID, mCallService.getCallerId());
intent.putExtra(SinchClientService.INTENT_EXTRA_NAME, mCallService.getCallerName());
startActivity(intent);
}
});*/
speaker.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(speaker_on)
{
mMessageService.speakerOn(speaker_on);
speaker_on = false;
speaker.setImageResource(R.drawable.speaker_off);
}
else
{
mMessageService.speakerOn(speaker_on);
speaker_on = true;
speaker.setImageResource(R.drawable.speaker_on);
}
}
});
mic.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mic_on)
{
mMessageService.micOn(mic_on);
mic_on = false;
mic.setImageResource(R.drawable.mic_off);
}
else
{
mMessageService.micOn(mic_on);
mic_on = true;
mic.setImageResource(R.drawable.mic_on);
}
}
});
mEndCallButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mCallService.endCall();
}
});
mCallStart = System.currentTimeMillis();
}
private void doBind() {
Intent intent = new Intent(this, SinchClientService.class);
bindService(intent, this, BIND_AUTO_CREATE);
intent = new Intent(this, GroupCallService.class);
bindService(intent, this, BIND_AUTO_CREATE);
}
private void doUnbind() {
unbindService(this);
}
#Override
protected void onStart() {
super.onStart();
mUpdateReceiver = new UpdateReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(GroupCallService.ACTION_FINISH_CALL_ACTIVITY);
filter.addAction(GroupCallService.ACTION_CHANGE_AUDIO_STREAM);
filter.addAction(GroupCallService.ACTION_UPDATE_CALL_STATE);
LocalBroadcastManager.getInstance(this).registerReceiver(mUpdateReceiver, filter);
}
#Override
public void onResume() {
super.onResume();
if(mProximityWakeLock != null && !mProximityWakeLock.isHeld()){
mProximityWakeLock.acquire();
}
mTimer = new Timer();
mDurationTask = new UpdateCallDurationTask();
mTimer.schedule(mDurationTask, 0, 500);
}
#Override
public void onPause() {
super.onPause();
if(isFinishing() && mProximityWakeLock != null && mProximityWakeLock.isHeld()){
mProximityWakeLock.release();
}
mDurationTask.cancel();
}
#Override
protected void onStop() {
super.onStop();
if(isFinishing() && mProximityWakeLock != null && mProximityWakeLock.isHeld()){
mProximityWakeLock.release();
}
if(mUpdateReceiver != null)
{
LocalBroadcastManager.getInstance(this).unregisterReceiver(mUpdateReceiver);
mUpdateReceiver = null;
}
}
#Override
public void onBackPressed() {
// User should exit activity by ending call, not by going back.
}
private void updateCallDuration() {
mCallDuration.setText(Utils.formatTimespan(System.currentTimeMillis() - mCallStart));
}
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
if(iBinder instanceof GroupCallService.GroupCallServiceInterface)
{
mCallService = (GroupCallService.GroupCallServiceInterface) iBinder;
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
ActionBar actionBar = getSupportActionBar();
if(mCallService.getCallerName() != null)
actionBar.setTitle(mCallService.getCallerName());
else
actionBar.setTitle("Group call");
actionBar.setIcon(R.drawable.callscreen);
if(mCallService.getCallerName() != null)
mCallerName.setText(mCallService.getCallerName());
else
mCallerName.setText("Group call");
mCallState.setText(mCallService.getCallState());
String pic = ChatDatabaseHandler.getInstance(this).getFriendpic(mCallService.getCallerId());
mImageLoader.displayImage(UserFunctions.hostImageDownloadURL + pic, user_pic);
}
else
mMessageService = (SinchClientService.MessageServiceInterface) iBinder;
mMessageService.enableMic();
mMessageService.disableSpeaker();
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mMessageService = null;
mCallService = null;
}
#Override
public void onDestroy() {
if(mUpdateReceiver != null)
{
LocalBroadcastManager.getInstance(this).unregisterReceiver(mUpdateReceiver);
mUpdateReceiver = null;
}
doUnbind();
super.onDestroy();
}
private class UpdateReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
if(GroupCallService.ACTION_FINISH_CALL_ACTIVITY.equals(intent.getAction()))
{
finish();
}
else if(GroupCallService.ACTION_CHANGE_AUDIO_STREAM.equals(intent.getAction()))
{
setVolumeControlStream(intent.getIntExtra("STREAM_TYPE", AudioManager.USE_DEFAULT_STREAM_TYPE));
}
else if(GroupCallService.ACTION_UPDATE_CALL_STATE.equals(intent.getAction()))
{
mCallState.setText(intent.getStringExtra("STATE"));
}
}
}
}
I start the call with the same way whether the user will start a new call or join a created one.

android GPS still getting postion when i'm not moving

I'm developing a tracking app. and i have problem with GPS module. The app must record a route. App work fine, but sometimes when the device is not moving, GPS still receive
continuous coordinate that don't indicate my position, error is within a radius of 20 meter, and when I'm moving again work fine.
Please give me some tips that can help me to fix this problem. Thanks a lot.
I have 3 calsses
1 - GPSReceiver here is method for get location
public void getMyLoction(){
_locationManager = (LocationManager) _context.getSystemService(LOCATION_SERVICE);
_isGPSEnabled =_locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (_isGPSEnabled) {
if (_location == null) {
_locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, this);
if (_locationManager != null) {
_location = _locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
setLocation(_location);
}
}
}
}
2 RecordingActivity (take coordonates form services and processes then) work fine, a comment in method what they do.
public class RecordingActivity extends FragmentActivity {
public final static String BROADCAST_ACTION = "map.trackv";
public BroadcastReceiver receiver;
private GoogleMap map;
private TextView _messageToUser;
private Coordinate _pointFromService;
private long _timeWhenStartButtonWasPressed;
private List<Coordinate> _unprocessedCoords;
private List<Coordinate> _processedCoords;
private Button _stopButton;
private Button _startButton;
private String _startRecordingDate;
private String _stopRecordingDate;
private GPSReceiver _gps;
private DataBaseOperations _dataSource;
private boolean _recording;
private boolean _gpsStatus;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recording_route);
initActvity();
checkIfGPSisOn();
try {
Runtime.getRuntime().exec("logcat -f" + " /sdcard/Logcat.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d("nu pot", "DDDDD");
e.printStackTrace();
}
receveirWork();
IntentFilter intentFilt = new IntentFilter(BROADCAST_ACTION);
registerReceiver(receiver, intentFilt);
}
public void checkIfGPSisOn() {
//check on start
}
public void receveirWork() {
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// request points and process then,
}
};
}
#Override
protected void onDestroy() {
super.onDestroy();
if (_stopButton.isEnabled())
{
stopService(new Intent(this, RecordingService.class));
_unprocessedCoords = null;
_processedCoords = null;
}
unregisterReceiver(receiver);
}
#Override
protected void onResume() {
if (!_stopButton.isEnabled()) {
_startButton.setEnabled(true);
_messageToUser.setText(Constants.PRESS_START_BUTTON);
map.clear();
}
super.onResume();
}
// actiune buton start;
public void startButtonEvent(View V) {
buttonsStateAndMessageToShow(false, true, Constants.MESSAGE_TO_WAIT);
_timeWhenStartButtonWasPressed = System.currentTimeMillis();
startService(new Intent(this, RecordingService.class));
// start service to get position
}
public void stopButtonEvent(View V) {
stopService(new Intent(this, RecordingService.class));
// stop service
// save route in BD
// resetData;
}
public void initActvity() {
// init date
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// save state
}
}
3 RecordingServices class, ii think here is the problem.
public class RecordingService extends Service {
private Thread _backgroundWork;
private boolean _threadCanRun;
private GPSReceiver _gps;
private Coordinate _pointToSent;
public void onCreate() {
super.onCreate();
_threadCanRun = true;
_backgroundWork = new Thread(new Runnable() {
#Override
public void run() {
Looper.prepare();
getLocationFromGPS();
Looper.loop();
}
});
}
public int onStartCommand(Intent intent, int flags, int startId) {//
_backgroundWork.start();
return super.onStartCommand(intent, flags, startId);
}
public void onDestroy() {
_threadCanRun = false;
super.onDestroy();
}
public IBinder onBind(Intent intent) {
return null;
}
public void getLocationFromGPS() {
while (_threadCanRun) {
Intent _intent = new Intent(RecordingActivity.BROADCAST_ACTION);
_gps = new GPSReceiver(this);
_gps.getMyLoction();
if (_gps.getIsGPSEnabled()) {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {}
sentPoint(_intent);
} else {
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {}
_intent.putExtra("latitude", 0);
_intent.putExtra("longitude", 0);
_intent.putExtra("time", 0);
_intent.putExtra("GPSstatus", false);
sendBroadcast(_intent);
}
}
}
private void sentPoint(Intent _intent) {
_pointToSent = new Coordinate(_gps.getLatitude(), _gps.getLongitude(), _gps.getTime());
_intent.putExtra("latitude", _pointToSent.getLatitude());
_intent.putExtra("longitude", _pointToSent.getlongitude());
_intent.putExtra("time", _pointToSent.getTime());
_intent.putExtra("GPSstatus", _gps.getIsGPSEnabled());
sendBroadcast(_intent);
_pointToSent = null;
}
}
repeating the Location update request depends on how u implemented your tracking system
but in general(which is not recommended , just change your request update rate to save client Battery usage) you can find the distance between your locations by location1.distanceTo(location2) so if the distance is smaller than 30m then put the new location away

Pointing to wrong UI from posted Runnable after screen orintation changes

This is my little test program. My problem is that from run() method I access to fields of wrong (old) Activity, which was destroyed after screen orientation changed. What's the way to handle this situation?
And, by the way, I must have my activity been recreated, because in real application I have different layouts for portrait and landscape modes!
public class MainActivity extends Activity {
private EditText edit;
private Button button;
private ProgressDialog progressDialog;
private boolean isLoginInProgress = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit = (EditText) findViewById(R.id.edit_timer);
button = (Button) findViewById(R.id.btn_start);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
if (edit.getText().toString().length() == 0) throw new Exception();
long dTime = Long.parseLong(edit.getText().toString());
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
MainActivity.this.isLoginInProgress = false;
progressDialog.dismiss();
}
}, dTime);
progressDialog.show();
isLoginInProgress = true;
} catch (Exception e) {
Toast.makeText(MainActivity.this, "bad time value", Toast.LENGTH_SHORT).show();
}
}
});
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("loading");
if (savedInstanceState != null) { // activity is restarted
isLoginInProgress = savedInstanceState.getBoolean("fl_login");
edit.setText(savedInstanceState.getString("edit"));
}
if (isLoginInProgress) { // Show dialog again
progressDialog.show();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean("fl_login", isLoginInProgress);
outState.putString("edit", edit.getText().toString());
}
#Override
public void onDestroy(){
super.onDestroy();
progressDialog.dismiss();
}
}
You Can Use Database(SQLITE) for Storing Your Values..

EditText displayed nothing when resuming. (activity destroyed by android system)

My Activity is named BlacklistAddActivity.
UI element: EditText editText, Button btn1. When I click btn1, it will launch contact list activity and I can pick a contact from the contact list. Then send the contact info back to BlacklistAddActivity, and set the contact's name to the text1 by editText.setText(contact.name).
The problem is, sometimes, in contact list, if I do some operations: enter dialer from recent applicaton window(long press home key), and make a call etc... As we know, the android will check memory to decide destroying the activity stack or not. If memory is low, it will destroy the background activities, including BlacklistActivity.
Now, resume to contact list and pick a contact, resume to BlacklistActivity, it will be recreated. I can get contact's info correctly at onActivityResult(). Then, editText.setText(contact.name). Strange thing is: the editText shown on UI is still empty.
The following is my code: (not completely)
public class BlacklistAddActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
static final boolean DBG = true;
private static final String TAG = "BlacklistAddActivity";
private static final String KEY_MATCH_CRITERIA = "match_criteria";
private SharedPreferences mSharedPreferences;
private ListPreference mCriteria;
private static final int CONTACT_ITEM = 0;
private static final int LOGS_ITEM = 1;
private static final String NUM_PROJECTION[] = { Phone.DISPLAY_NAME, Phone.NUMBER };
protected static final Intent CONTACT_IMPORT_INTENT;
static {
CONTACT_IMPORT_INTENT = new Intent(Intent.ACTION_GET_CONTENT);
CONTACT_IMPORT_INTENT.setType(Phone.CONTENT_ITEM_TYPE);
}
private Context mContext;
private EditText editText;
private ImageButton searchButton;
private TwSoftkeyItem mLeftSoftkey, mRightSoftkey;
private AlertDialog mSearchDialog = null;
private InputMethodManager imm;
private boolean updateMode;
private String mNumber;
private int mMatchCriteria;
#Override
protected void onCreate(Bundle savedInstanceState) {
initTitle();
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate()");
setContentView(R.layout.blacklist_number_layout);
addPreferencesFromResource(R.xml.blacklist_add_num_prefs);
mSharedPreferences = getPreferenceScreen().getSharedPreferences();
mContext = getBaseContext();
mCriteria = (ListPreference) findPreference(KEY_MATCH_CRITERIA);
editText = (EditText) findViewById(R.id.edit_text);
editText.requestFocus();
searchButton = (ImageButton) findViewById(R.id.search_button);
mLeftSoftkey = (TwSoftkeyItem) findViewById(R.id.skleft);
mRightSoftkey = (TwSoftkeyItem) findViewById(R.id.skright);
initValue();
initEvent();
imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
handler.postDelayed(new Runnable() {
public void run() {
imm.showSoftInput(editText, 1);
}
}, 200);
}
private void initTitle() {
String str = getIntent().getStringExtra("FROM");
if (str != null) {
if (DBG) Log.i(TAG, "initTitle() => from: " + str);
if (str.equals("msg")) {
setTitle(R.string.list_msg_block_num);
} else {
setTitle(R.string.list_call_block_num);
}
}
}
private void initValue() {
updateMode = getIntent().getBooleanExtra("UPDATE_MODE", false);
Log.i(TAG, "the updatemode is: "+ updateMode);
if (updateMode == true) { //from Edit
mNumber = getIntent().getStringExtra("NUMBER");
mMatchCriteria = getIntent().getIntExtra("CRITERIA", 0);
editText.setText(mNumber);
editText.setSelection(mNumber.length());
mCriteria.setValueIndex(mMatchCriteria);
mCriteria.setSummary(mCriteria.getEntry());
} else { // from Add
mCriteria.setValueIndex(0);
mCriteria.setSummary(mCriteria.getEntry());
}
}
private void initEvent() {
searchButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
alertDialogSearch();
}
});
editText.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean focused) {
if (focused == true) {
handler.postDelayed(new Runnable() {
public void run() {
imm.showSoftInput(editText, 1);
}
}, 200);
} else {
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
}
});
editText.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER && event.getAction() == KeyEvent.ACTION_UP) {
editText.requestFocus();
return true;
}
return false;
}
});
mLeftSoftkey.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("NUMBER", editText.getText().toString());
intent.putExtra("CRITERIA", mCriteria.findIndexOfValue(mCriteria.getValue()));
setResult(RESULT_OK, intent);
finish();
}
});
mRightSoftkey.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setResult(RESULT_CANCELED, null);
finish();
}
});
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState)
{
if(DBG){
if(null != editText)
Log.d(TAG, "onRestoreInstanceState: Edit Text is: "+editText.getText().toString());
}
super.onRestoreInstanceState(savedInstanceState);
if(DBG){
if(null != editText)
Log.d(TAG, "onRestoreInstanceState: Edit Text is: "+editText.getText().toString());
}
}
#Override
protected void onResume() {
super.onResume();
Log.i(TAG, "onResume()");
if(null != editText)
if (DBG) Log.d(TAG, "onResume() Edit Text is: "+editText.getText().toString());
mSharedPreferences.registerOnSharedPreferenceChangeListener(this);
mCriteria.setSummary(mCriteria.getEntry());
}
#Override
protected void onPause() {
super.onPause();
mSharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
if (mSearchDialog != null) {
mSearchDialog.dismiss();
mSearchDialog = null;
}
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (DBG) Log.v(TAG, "onSharedPreferenceChanged(), key: " + key);
if (KEY_MATCH_CRITERIA.equals(key)) {
if (mCriteria.getEntry() == null) {
mCriteria.setValueIndex(0);
}
mCriteria.setValue(sharedPreferences.getString(key, mCriteria.getEntry().toString()));
mCriteria.setSummary(mCriteria.getEntry());
if (DBG) Log.v(TAG, "setValue: " + mCriteria.getEntry().toString());
}
}
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
System.out.println("DONE");
break;
}
}
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String output = "";
switch (requestCode) {
case CONTACT_ITEM:
if (resultCode != RESULT_OK) {
Log.e(TAG, "onActivityResult() => canceled");
} else {
Cursor cursor = getContentResolver().query(data.getData(), NUM_PROJECTION, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
output = cursor.getString(1);
if (DBG) Log.d(TAG, "onActivityResult() => contact output: " + output);
if (Utils.isValidNum(mContext, output)) {
editText.setText(output);
if (DBG) Log.d(TAG, "onActivityResult() Edit Text is: "+editText.getText().toString());
}
}
cursor.close();
}
}
break;
case LOGS_ITEM:
if (resultCode == RESULT_OK) {
output = data.getStringExtra("NUMBER");
if (DBG) Log.d(TAG, "onActivityResult() => logs output: " + output);
if (Utils.isValidNum(mContext, output)) {
editText.setText(output);
} else {
output = null;
Utils.displayToast(mContext, getString(R.string.vip_msg_wrong_number));
}
}
break;
}
handler.postDelayed(new Runnable() {
public void run() {
imm.showSoftInput(editText, 1);
}
}, 200);
if (output != null && output.length() > 0) {
editText.requestFocus();
editText.setSelection(output.length());
}
}
private void alertDialogSearch() {
AlertDialog.Builder ad = new AlertDialog.Builder(this);
ad.setTitle(R.string.title_search).setItems(R.array.dialog_search, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent;
switch (which) {
case CONTACT_ITEM:
startActivityForResult(CONTACT_IMPORT_INTENT, CONTACT_ITEM);
break;
case LOGS_ITEM:
intent = new Intent("contacts.com.sec.android.app.dialertab.calllog.LogsListActivity");
intent.putExtra("OPTION", 1);
startActivityForResult(intent, LOGS_ITEM);
break;
}
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
});
mSearchDialog = ad.show();
}
}
Android does not automatically backup any data on your Activity when it gets destroyed. You have to manually back your data up before it gets destroyed and restore it when your Activity is recreated.
To backup your data, you must override this method. (It will be called before your activity gets destroyed.)
#Override
protected void onSaveInstanceState(Bundle savedInstanceState)
{
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("key", value); //save your data in key-value pair
}
To restore your data, you must override this method. (It will be called before your activity resumes.)
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
value = savedInstanceState.getString("key"); //retrieve your data using its corresponding key
}
if your text is not set/displayed correctly you should take a close look at your onCreate(), onResume() and onRestoreInstanceState() implementation.
so the answer from arci is what i would also answer in this case.
you say it is working the first time and also working if the Activity will not get killed. But when the Activity got killed and recreated it is not working. This sounds like you work on the wrong reference at some point.Especially when you use Listeners this can happen easily
You should go into debug mode and check your Activity and EditText instance (via memory adress) are the same/correct every time you access it.
I don't realy see the problem with your code but it has to be something like this.
Note: everytime you use startActivity(), go into landscape/portrait mode or something other calling onCreate() you may get a new Activity instance.
Note II: everytime onCreate() is called you get most likely call setContentView() what ends up in getting a newly inflated/created view. this means your EditText and other Views will be a new instance.

Implement double click for button in Android

How can I implement double click for a button in Android?
Should I use OnDoubleTapListener?
int i = 0;
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
i++;
Handler handler = new Handler();
Runnable r = new Runnable() {
#Override
public void run() {
i = 0;
}
};
if (i == 1) {
//Single click
handler.postDelayed(r, 250);
} else if (i == 2) {
//Double click
i = 0;
ShowDailog();
}
}
});
private long lastTouchTime = 0;
private long currentTouchTime = 0;
..
#Override
public void onClick(View view) {
lastTouchTime = currentTouchTime;
currentTouchTime = System.currentTimeMillis();
if (currentTouchTime - lastTouchTime < 250) {
Log.d("Duble","Click");
lastTouchTime = 0;
currentTouchTime = 0;
}
}
This is probably a good place to start:
Android: How to detect double-tap?
I recommend switching to a more native way like long press (answer to linked question) or something more creative (using multi-touch), unless you are bent on the Windows default double-click way of doing things?
You may have a valid reason though - double clicking is after all faster than long press.
I wrote this for popping up a Toast message on a double click in a mapping application:
private long lastTouchTime = -1;
#Override
public boolean onTouchEvent(MotionEvent e, MapView mapView) {
GeoPoint p = null;
if (e.getAction() == MotionEvent.ACTION_DOWN) {
long thisTime = System.currentTimeMillis();
if (thisTime - lastTouchTime < 250) {
// Double click
p = mapView.getProjection().fromPixels((int) e.getX(), (int) e.getY());
lastTouchTime = -1;
} else {
// too slow
lastTouchTime = thisTime;
}
}
if (p != null) {
showClickedLocation(p);// Raise a Toast
}
return false;
}
This is a good site for performing double click...
I used it and worked.
http://mobile.tutsplus.com/tutorials/android/android-gesture/
I used it and worked:
public class DoubleClickTest extends Activity {
String TAG = "DoubleOrSingleClickTest";
private boolean waitDouble = true;
private static final int DOUBLE_CLICK_TIME = 350; // double click timer
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.double_click_test);
Button button = (Button) findViewById(R.id.buttonDoubleOrSingleClicked);
button.setOnClickListener(listenerDoubleOrSingle);
}
View.OnClickListener listenerDoubleOrSingle = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (waitDouble == true) {
waitDouble = false;
Thread thread = new Thread() {
#Override
public void run() {
try {
sleep(DOUBLE_CLICK_TIME);
if (waitDouble == false) {
waitDouble = true;
singleClick();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
} else {
waitDouble = true;
doubleClick();
}
}
};
// single event
private void singleClick() {
Log.i(TAG, "singleClick");
}
// double event
private void doubleClick() {
Log.i(TAG, "doubleClick");
}
}
It comes from "https://elingwange.iteye.com/blog/1613177"
Create your own DoubleTapListener
You can create a DoubleTapListener by inheriting View.OnClickListener and adding a Callback of your listener.
MyDoubleClickListener.class
public class MyDoubleClickListener implements View.OnClickListener{
private boolean isRunning= false;
private int resetInTime =500;
private int counter=0;
private DoubleClickCallback listener;
public DoubleTapListener(Context context)
{
listener = (DoubleClickCallback)context;
}
#Override
public void onClick(View v) {
if(isRunning)
{
if(counter==1) //<-- makes sure that the callback is triggered on double click
listener.onDoubleClick(v);
}
counter++;
if(!isRunning)
{
isRunning=true;
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(resetInTime);
isRunning = false;
counter=0;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
}
DoubleClickCallback.class
public interface DoubleClickCallback {
public void onDoubleClick(View v);
}
And you are done. You can use this Listener in any Activity.
How do I use this DoubleClickListener in my Activity?
Implement Callback in your activity and override the method.
public class MainActivity extends AppCompatActivity implements MyDoubleClickListener{
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new DoubleTapListener(this)); //<-- Set listener
}
#Override
public void onDoubleClick(View v) {
// Toast to show double click
}
}
Important point is using this concept you can create any kind of listener (Triple-click listener)
Relevant Links:
See the full working code HERE

Categories

Resources