I am making a default phone call. Everything works well till I made a call to the switchboard operator.
In this kind of call, the phone says: "Press 1 to do A, press 2 to do B".
I did some research for hours but couldn't find one...
I did try this code, but it doesn't work.
keyPressed(KeyEvent.KEYCODE_1); // when press key 1
private void keyPressed(int keyCode) {
....
Intent i = new Intent(Intent.ACTION_CALL, Uri.parse("tel://" + keyCode));
startActivity(I);
....
playTone(ToneGenerator.TONE_DTMF_1, TONE_LENGTH_INFINITE);
}
Big thanks for any of your suggestions!
Added 1:
I am using InCallService like this:
class CallService : InCallService() {
private var isShowEnded = true
override fun onCallAdded(call: Call) {
super.onCallAdded(call)
OngoingCall().setCall(call)
CallActivity.getInstance().start(this, call)
isShowEnded = false
}
override fun onCallRemoved(call: Call) {
super.onCallRemoved(call)
OngoingCall().setCall(null)
}
}
and OngoingCall:
public class OngoingCall {
public static BehaviorSubject<Integer> state = BehaviorSubject.create();
private static Call sCall;
public Call getsCall() {
return sCall;
}
#RequiresApi(api = Build.VERSION_CODES.M)
private Object callback = new Call.Callback() {
#Override
public void onStateChanged(Call call, int newState) {
super.onStateChanged(call, newState);
state.onNext(newState);
}
};
#RequiresApi(api = Build.VERSION_CODES.M)
public final void setCall(#Nullable Call value) {
if (sCall != null) {
sCall.unregisterCallback((Call.Callback) callback);
}
if (value != null) {
value.registerCallback((Call.Callback) callback);
state.onNext(value.getState());
}
sCall = value;
}
#RequiresApi(api = Build.VERSION_CODES.M)
public void answer() {
if (sCall != null) {
assert sCall != null;
sCall.answer(VideoProfile.STATE_AUDIO_ONLY);
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
public void hold(boolean hold) {
if (sCall != null) {
if (hold) sCall.hold();
else sCall.unhold();
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
public void addCall(Call call) {
if (sCall != null) {
sCall.conference(call);
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
public void hangup() {
if (sCall != null) {
sCall.disconnect();
}
}
}
And then I tried this when pressing keyboard:
mTrueCallerOngoingCall.getsCall().playDtmfTone((char) tone); // inside playTone()
But it's still not working :(
Update 2:
I have fixed my adding this method:
private char getChar(int tone) {
if (tone == 0) return '0';
else if (tone == 1) return '1';
else if (tone == 2) return '2';
else if (tone == 3) return '3';
else if (tone == 4) return '4';
else if (tone == 5) return '5';
else if (tone == 6) return '6';
else if (tone == 7) return '7';
else if (tone == 8) return '8';
else if (tone == 9) return '9';
else if (tone == 10) return '*';
else return '#';
}
and change from my above code to
mTrueCallerOngoingCall.getsCall().playDtmfTone(getChar(tone));
mTrueCallerOngoingCall.getsCall().stopDtmfTone();
It is .Hope can help you.
call.playDtmfTone(char);
The call PATH:
android.telecom.Call;
From: Any Class extends InCallService.
In Method: onCallAdded(call);
Related
I have build an audioplayer which is deployed in android google playstore. I'm using crashlytics to monitor crashes and ANRs. Recently I have been getting a lot of crashes MediaButtonReceiver. The headset clicks work fine in many devices. But some devices are giving this problem.
Crashlytics report -
Fatal Exception: java.lang.RuntimeException: Unable to start receiver android.support.v4.media.session.MediaButtonReceiver: java.lang.IllegalStateException: Could not find any Service that handles android.intent.action.MEDIA_BUTTON or implements a media browser service.
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2866)
at android.app.ActivityThread.access$1700(ActivityThread.java:182)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1551)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5706)
at java.lang.reflect.Method.invoke(Method.java)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1033)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:828)
MediaSession code -
private void initMediaSession() throws RemoteException {
if (mediaSessionManager != null) return; //mediaSessionManager exists
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mediaSessionManager = (MediaSessionManager) getSystemService(Context.MEDIA_SESSION_SERVICE);
}
// Create a new MediaSession
mediaSession = new MediaSessionCompat(this, "AudioPlayer");
//Get MediaSessions transport controls
transportControls = mediaSession.getController().getTransportControls();
//set MediaSession -> ready to receive media commands
mediaSession.setActive(true);
//indicate that the MediaSession handles transport control commands
// through its MediaSessionCompat.Callback.
mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS|MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS);
//Set mediaSession's MetaData
updateMetaData();
mediaSession.setCallback(new MediaSessionCompat.Callback() {
#Override
public void onPlay() {
super.onPlay();
resumeMedia();
}
#Override
public void onPause() {
super.onPause();
pauseMedia();
}
#Override
public void onSkipToNext() {
super.onSkipToNext();
}
#Override
public void onSkipToPrevious() {
super.onSkipToPrevious();
}
#Override
public boolean onMediaButtonEvent(Intent mediaButtonIntent) {
if (su.getHeadsetEnableSwitch()) {
String intentAction = mediaButtonIntent.getAction();
if (Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
KeyEvent event = mediaButtonIntent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event != null) {
int action = event.getAction();
Log.e("Headset key: ", String.valueOf(action));
if (action == KeyEvent.ACTION_DOWN) {
Log.e("Headset: ", "Action down");
headsetClickCount++;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (headsetClickCount == 1) {
if (isPng()) pauseMedia();
else resumeMedia();
headsetClickCount = 0;
} else if (headsetClickCount == 2) {
if (su.getDoubleClickAction() == 0) {
} else if (su.getDoubleClickAction() == 1)
skipToPrevious();
else if (su.getDoubleClickAction() == 2) skipToNext();
headsetClickCount = 0;
} else if (headsetClickCount == 3) {
if (su.getTripleClickAction() == 0) {
} else if (su.getTripleClickAction() == 1)
skipToPrevious();
else if (su.getTripleClickAction() == 2) skipToNext();
headsetClickCount = 0;
}
}
}, 750);
}
if (action == KeyEvent.FLAG_LONG_PRESS) {
if (su.getLongClickAction() == 0) {
} else if (su.getLongClickAction() == 1) skipToPrevious();
else if (su.getLongClickAction() == 2) skipToNext();
}
if (action == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE) {
Log.e("Headset: ", "headset sethook");
if (isPng()) pauseMedia();
else resumeMedia();
}
if (action == KeyEvent.KEYCODE_MEDIA_NEXT) {
skipToNext();
}
if (action == KeyEvent.KEYCODE_MEDIA_PREVIOUS) {
skipToPrevious();
}
if (action == KeyEvent.KEYCODE_MEDIA_PAUSE) {
pauseMedia();
}
if (action == KeyEvent.KEYCODE_MEDIA_PLAY) {
resumeMedia();
}
}
}
return true;
}
return true;
}
});
}
What could be the problem and how to solve this?
My thoughts - Maybe this happens because user opens other music apps that has this feature while my app is still playing.
You have to create your own media button receiver class, say MyMediaButtonReceiver.java, that extends MediaButtonReceiver, and it will be empty except for the onReceive method that you have to override, calling super.onReceive(...) between a try-catch that captures the IllegalStateException:
public class MyMediaButtonReceiver extends MediaButtonReceiver {
#Override
public void onReceive(Context context, Intent intent) {
try {
super.onReceive(context, intent);
} catch (IllegalStateException e) {
Log.d(this.getClass().getName(), e.getMessage());
}
}
}
Then you have to declare that receiver class in your Manifest (or replace your previous MediaButtonReceiver class declaration, if you had one), like:
<receiver android:name=".MyMediaButtonReceiver" >
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
class MyMediaButtonReceiver : MediaButtonReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == Intent.ACTION_MEDIA_BUTTON) {
val event = intent.getParcelableExtra<KeyEvent>(Intent.EXTRA_KEY_EVENT)
if (event.action == KeyEvent.ACTION_UP || event.action ==
KeyEvent.ACTION_DOWN) {
when (event.keyCode) {
// handle cancel button
KeyEvent.KEYCODE_MEDIA_STOP -> context.sendIntent(ACTION_FINISH)
// handle play button
KeyEvent.KEYCODE_MEDIA_PLAY, KeyEvent.KEYCODE_MEDIA_PAUSE -> context.sendIntent(ACTION_PLAY_PAUSE)
}
}
}
}
}
kotlin extension for send event to media service
fun Context.sendIntent(action: String) {
Intent(this, MediaPlayerService::class.java).apply {
this.action = action
try {
if (isOreoPlus()) {
startForegroundService(this)
} else {
startService(this)
}
} catch (ignored: Exception) {
}
}
}
add Receiver in manifest
<receiver android:name=".player.receivers.MyMediaButtonReceiver" >
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
I have implemented recycler view in the following manner :
now on the click of any one of the rows, the view is expanded like this :
now the problem i am facing is that when i try to expand the last item of the recycler view , the view is expanded but we cannot understand as the recycler view does not scroll up. so it is expaned in real but since it is below the screen the user thinks that nothing has happened.
Like in the 1st image if we click on the last item, i.e. photograph the row is expanded but we donot understand untill we actually scroll it up like this :
so now how do i acheive this ? i mean if the last item on the screen is expanded how to i scroll it a bit up so the user understands the difference.
CODE :
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof ViewHolder)
{
final ViewHolder bodyholder = (ViewHolder) holder;
if (UtilInsta.PendingDoc.get(position).name.length() == 0) {
pd = new InstaDrawer();
bodyholder.penddoc_tv.setText(UtilInsta.PendingDoc.get(position).DOC_NAME);
if (UtilInsta.PendingDoc.get(position).ADDININFO_FLAG.equalsIgnoreCase("Y")) {
bodyholder.tv_clickforkyc.setVisibility(View.VISIBLE);
} else {
bodyholder.tv_clickforkyc.setVisibility(View.GONE);
}
bodyholder.pending_row.setId(position);
bodyholder.pending_row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// crop(position);
InstaDrawer.pendingDocList= UtilInsta.PendingDoc.get(v.getId());
UtilInsta.setPosition(con, v.getId());
if (bodyholder.pend_ll.getVisibility() == View.VISIBLE) {
UtilInsta.PendingDoc.get(v.getId()).option = false;
bodyholder.pend_ll.setVisibility(View.GONE);
bodyholder.tv_clickforkyc.setVisibility(View.GONE);
if (bodyholder.remarks_layout.getVisibility() == View.VISIBLE) {
bodyholder.remarks_layout.setVisibility(View.GONE);
UtilInsta.PendingDoc.get(v.getId()).will_chek = false;
UtilInsta.PendingDoc.get(v.getId()).unable_chek = false;
}
} else {
bodyholder.pend_ll.setVisibility(View.VISIBLE);
// setHide(v.getId());
if (UtilInsta.PendingDoc.get(v.getId()).ADDININFO_FLAG.equalsIgnoreCase("Y")) {
bodyholder.tv_clickforkyc.setVisibility(View.VISIBLE);
} else {
bodyholder.tv_clickforkyc.setVisibility(View.GONE);
}
UtilInsta.PendingDoc.get(v.getId()).option = true;
if (UtilInsta.PendingDoc.get(v.getId()).MIN_DOC == "Y") {
bodyholder.provie_later.setVisibility(View.GONE);
bodyholder.unable_submit.setVisibility(View.GONE);
}
}
if(expandedpos>=0 && expandedpos!=v.getId())
{
int prev = expandedpos;
notifyItemChanged(prev);
}
expandedpos = v.getId();
}
});
// holder.acct_name_tv.setText(pendingDocLists.get(position).CUST_NAME);
bodyholder.camera.setId(position);
bodyholder.camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InstaDrawer.pendingDocList= UtilInsta.PendingDoc.get(v.getId());
UtilInsta.setPosition(con, v.getId());
if (UtilInsta.PendingDoc.get(v.getId()).ADDININFO_FLAG.equalsIgnoreCase("Y")) {
if (Util.isNetworkConnected(con))
DocumentInfo(0, v.getId());
else
Util.shownointernet(con);
}
else {
UtilInsta.setFILE_NAME(con, "");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
( con.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || con.checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)){
ActivityCompat.requestPermissions(((Activity)con),
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, com.app.hdfc.Manifest.permission.CAMERA},
MyConstants.READ_EXTERNAL_STORAGE_PERMISSION_CAM);
}
else
{
if(UtilInsta.PendingDoc.get(v.getId()).DOC_NAME.equalsIgnoreCase("Photograph"))
{
Intent intent = new Intent(con, FrontCamera.class);
UtilInsta.CUST_NO = UtilInsta.PendingDoc.get(v.getId()).CUST_NO;
(con).startActivity(intent);
((Activity)con).finish();
}else {
Intent intent = new Intent(con, CroppingActivity.class);
intent.putExtra("camera_gallery", 0);
intent.putExtra("fromRecycler", true);
intent.putExtra("position", v.getId());
intent.putExtra("DOC_NAME", UtilInsta.PendingDoc.get(v.getId()).DOC_NAME);
UtilInsta.doc_name = UtilInsta.PendingDoc.get(v.getId()).DOC_NAME;
Log.d("Recycler", UtilInsta.doc_name);
intent.putExtra("CUST_NO", UtilInsta.PendingDoc.get(v.getId()).CUST_NO);
(con).startActivity(intent);
((Activity) con).finish();
}
}
}
}
});
bodyholder.gallery.setId(position);
bodyholder.gallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InstaDrawer.pendingDocList= UtilInsta.PendingDoc.get(v.getId());
UtilInsta.setPosition(con, v.getId());
if (UtilInsta.PendingDoc.get(v.getId()).ADDININFO_FLAG.equalsIgnoreCase("Y"))
if(Util.isNetworkConnected(con))
DocumentInfo(1, v.getId());
else
Util.shownointernet(con);
else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
con.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(((Activity)con),
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MyConstants.READ_EXTERNAL_STORAGE_PERMISSION);
}
else {
UtilInsta.setFILE_NAME(con, "");
Intent intent = new Intent(con, CroppingActivity.class);
intent.putExtra("camera_gallery", 1);
intent.putExtra("fromRecycler", true);
intent.putExtra("position", v.getId());
intent.putExtra("DOC_NAME", UtilInsta.PendingDoc.get(v.getId()).DOC_NAME);
UtilInsta.doc_name = UtilInsta.PendingDoc.get(v.getId()).DOC_NAME;
Log.d("Recycler", UtilInsta.doc_name);
intent.putExtra("CUST_NO", UtilInsta.PendingDoc.get(v.getId()).CUST_NO);
(con).startActivity(intent);
((Activity) con).finish();
}
}
}
});
if (UtilInsta.PendingDoc.get(position).MIN_DOC.equalsIgnoreCase("Y")) {
bodyholder.provie_later.setVisibility(View.GONE);
bodyholder.unable_submit.setVisibility(View.GONE);
} else {
bodyholder.provie_later.setVisibility(View.VISIBLE);
bodyholder.unable_submit.setVisibility(View.VISIBLE);
}
bodyholder.provie_later.setId(position);
bodyholder.provie_later.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (remark == 1) {
remark = 0;
bodyholder.provie_later.setImageResource(R.drawable.circle1);
bodyholder.remarks_layout.setVisibility(View.GONE);
UtilInsta.PendingDoc.get(v.getId()).will_chek = false;
} else if (remark == 0 || remark == 2) {
bodyholder.unable_submit.setImageResource(R.drawable.circle2);
bodyholder.provie_later.setImageResource(R.drawable.circle1_hover);
remark = 1;
bodyholder.remarks_layout.setVisibility(View.VISIBLE);
UtilInsta.PendingDoc.get(v.getId()).will_chek = true;
}
}
});
bodyholder.unable_submit.setId(position);
bodyholder.unable_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (remark == 2) {
remark = 0;
bodyholder.unable_submit.setImageResource(R.drawable.circle2);
bodyholder.remarks_layout.setVisibility(View.GONE);
UtilInsta.PendingDoc.get(v.getId()).unable_chek = false;
} else if (remark == 0 || remark == 1) {
bodyholder.provie_later.setImageResource(R.drawable.circle1);
bodyholder.unable_submit.setImageResource(R.drawable.circle2_hover);
remark = 2;
bodyholder.remarks_layout.setVisibility(View.VISIBLE);
UtilInsta.PendingDoc.get(v.getId()).unable_chek = true;
}
}
});
bodyholder.tv_clickforkyc.setId(position);
bodyholder.tv_clickforkyc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Util.isNetworkConnected(con))
DocumentInfo(2, v.getId()); // 2 for kyc list
else
Util.shownointernet(con);
}
});
bodyholder.remarks_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String remark_str = bodyholder.remarks_edittext.getText().toString().trim();
if (remark_str.equalsIgnoreCase("")) {
Toast.makeText(con, "Please enter some remark", Toast.LENGTH_LONG).show();
} else if (remark_str.length() > 100) {
Toast.makeText(con, "Please enter remark less than 100 characters", Toast.LENGTH_LONG).show();
} else {
//Toast.makeText(con, "Remark : " + remark + " Submitted", Toast.LENGTH_LONG).show();
String remarktype = "";
if (remark == 1) {
remarktype = "PROVIDE_LATER";
} else if (remark == 2) {
remarktype = "NOT_AVAILABLE";
}
Log.e("Remarktype", remarktype + "1 " + remark);
if(Util.isNetworkConnected(con)) {
uploddoc(remarktype, remark_str);
bodyholder.remarks_edittext.setText("");
}
else
Util.shownointernet(con);
bodyholder.remarks_layout.setVisibility(View.GONE);
bodyholder.pend_ll.setVisibility(View.GONE);
UtilInsta.PendingDoc.get(position).option = false;
bodyholder.tv_clickforkyc.setVisibility(View.GONE);
}
}
});
// if (!UtilInsta.PendingDoc.get(position).REMARKS.equalsIgnoreCase("")) {
// bodyholder.remarks_tv.setVisibility(View.VISIBLE);
// bodyholder.remarks_tv.setText("*Remark - " + UtilInsta.PendingDoc.get(position).REMARKS);
if (UtilInsta.PendingDoc.get(position).STATUS.equalsIgnoreCase("NOT_AVAILABLE")) {
bodyholder.remarks_tv.setVisibility(View.VISIBLE);
bodyholder.remarks_tv.setText("*Remark - " + UtilInsta.PendingDoc.get(position).REMARKS);
bodyholder.unable_submit.setImageResource(R.drawable.circle2_hover);
bodyholder.provie_later.setImageResource(R.drawable.circle1);
bodyholder.remarks_edittext.setText(UtilInsta.PendingDoc.get(position).REMARKS);
UtilInsta.PendingDoc.get(position).unable_chek =true;
} else if (UtilInsta.PendingDoc.get(position).STATUS.equalsIgnoreCase("PROVIDE_LATER")) {
bodyholder.remarks_tv.setVisibility(View.VISIBLE);
bodyholder.remarks_tv.setText("*Remark - " + UtilInsta.PendingDoc.get(position).REMARKS);
bodyholder.unable_submit.setImageResource(R.drawable.circle2);
bodyholder.provie_later.setImageResource(R.drawable.circle1_hover);
bodyholder.remarks_edittext.setText(UtilInsta.PendingDoc.get(position).REMARKS);
UtilInsta.PendingDoc.get(position).will_chek =true;
}
else {
bodyholder.remarks_tv.setVisibility(View.GONE);
bodyholder.unable_submit.setImageResource(R.drawable.circle2);
bodyholder.provie_later.setImageResource(R.drawable.circle1);
bodyholder.remarks_edittext.setText("");
}
bodyholder.pending_row.setVisibility(View.VISIBLE);
bodyholder.acct_name_tv.setVisibility(View.GONE);
if (UtilInsta.PendingDoc.get(position).unable_chek) {
bodyholder.provie_later.setImageResource(R.drawable.circle1);
bodyholder.unable_submit.setImageResource(R.drawable.circle2_hover);
bodyholder.remarks_layout.setVisibility(View.VISIBLE);
UtilInsta.PendingDoc.get(position).unable_chek = true;
} else {
bodyholder.unable_submit.setImageResource(R.drawable.circle2);
bodyholder.remarks_layout.setVisibility(View.GONE);
UtilInsta.PendingDoc.get(position).unable_chek = false;
}
if (UtilInsta.PendingDoc.get(position).will_chek) {
bodyholder.unable_submit.setImageResource(R.drawable.circle2);
bodyholder.provie_later.setImageResource(R.drawable.circle1_hover);
bodyholder.remarks_layout.setVisibility(View.VISIBLE);
UtilInsta.PendingDoc.get(position).will_chek = true;
} else {
bodyholder.provie_later.setImageResource(R.drawable.circle1);
bodyholder.remarks_layout.setVisibility(View.GONE);
UtilInsta.PendingDoc.get(position).will_chek = false;
}
if (UtilInsta.PendingDoc.get(position).option) {
bodyholder.pend_ll.setVisibility(View.VISIBLE);
if (UtilInsta.PendingDoc.get(position).ADDININFO_FLAG.equalsIgnoreCase("Y")) {
bodyholder.tv_clickforkyc.setVisibility(View.VISIBLE);
} else {
bodyholder.tv_clickforkyc.setVisibility(View.GONE);
}
UtilInsta.PendingDoc.get(position).option = true;
if (UtilInsta.PendingDoc.get(position).MIN_DOC == "Y") {
bodyholder.provie_later.setVisibility(View.GONE);
bodyholder.unable_submit.setVisibility(View.GONE);
}
} else {
bodyholder.pend_ll.setVisibility(View.GONE);
bodyholder.tv_clickforkyc.setVisibility(View.GONE);
if (bodyholder.remarks_layout.getVisibility() == View.VISIBLE) {
bodyholder.remarks_layout.setVisibility(View.GONE);
UtilInsta.PendingDoc.get(position).will_chek = false;
UtilInsta.PendingDoc.get(position).unable_chek = false;
}
}
} else if (UtilInsta.PendingDoc.get(position).name.length() > 0) {
bodyholder.pending_row.setVisibility(View.GONE);
bodyholder.acct_name_tv.setVisibility(View.VISIBLE);
bodyholder.acct_name_tv.setText(UtilInsta.PendingDoc.get(position).name);
//continue comeback;
}
if(expandedpos == position)
{
bodyholder.pend_ll.setVisibility(View.VISIBLE);
if(UtilInsta.PendingDoc.get(position).option)
bodyholder.tv_clickforkyc.setVisibility(View.VISIBLE);
else
bodyholder.tv_clickforkyc.setVisibility(View.GONE);
}else
{
bodyholder.pend_ll.setVisibility(View.GONE);
bodyholder.tv_clickforkyc.setVisibility(View.GONE);
}
}else if (holder instanceof FooterViewHoldrer){
FooterViewHoldrer footerViewHoldrer = (FooterViewHoldrer) holder;
if(UtilInsta.PendingDoc.size()==0)
{
footerViewHoldrer.empty_pendingdoc.setVisibility(View.VISIBLE);
footerViewHoldrer.pending_continue.setVisibility(View.GONE);
footerViewHoldrer.loan_sanctioned.setVisibility(View.GONE);
}
else
{
footerViewHoldrer.empty_pendingdoc.setVisibility(View.GONE);
footerViewHoldrer.pending_continue.setVisibility(View.VISIBLE);
footerViewHoldrer.loan_sanctioned.setVisibility(View.VISIBLE);
}
if(submit_activate)
{
footerViewHoldrer.pending_continue.setBackgroundResource(R.drawable.background_button);
}else
{
footerViewHoldrer.pending_continue.setBackgroundResource(R.color.myblack);
}
footerViewHoldrer.pending_continue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(submit_activate) {
// Toast.makeText(con,"Button Activated.",Toast.LENGTH_SHORT).show();
if(Util.isNetworkConnected(con))
new UpdateStep().execute();
else
Util.shownointernet(con);
}else
{
Toast.makeText(con,"Submit/Remark all Documents",Toast.LENGTH_SHORT).show();
}
}
});
}
}
Try This:
yourRecyclerView.scrollToPosition(position);
the variable position will be having the value of the expanded position.
I have a handler inside oncreate of an activity. It receives a value from handler.sendEmptyMessage.
handleMessage is fired and it reaches till the line where I try to update the textview as shown below:
mImageCountText.setText("" + mCountText);
But the text of textview never gets changed. What am I missing here?
Is there anything obvious that causes this issue?
Any help is much appreciated.
EDIT
Handler code
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
final int what = msg.what;
if (what == Constants.HANDLER_APP_UPDATE) {
if (!UserHelper.isAppBuildVerionSameAsUpdate(HomeActivity.this)) {
updateNotificationAlert();
showAppUpdatePopUp();
}
} else if (what == Constants.HANDLER_COLLECTION_UPDATE) {
//TODO: Refresh collection
} else {
mCountText = what;
if (!Utils.isTablet()) {
if (mCountText == 0) {
mImageCountText.setVisibility(View.INVISIBLE);
} else {
mImageCountText.setVisibility(View.VISIBLE);
mImageCountText.setText("" + mCountText); // this does not work
}
} else {
if (mCountText == 0) {
mCollectionsFragment.refreshAfterUpload();
mCountTextForUplaod.setVisibility(View.INVISIBLE);
} else {
mCollectionsFragment.refreshAfterUpload();
mCountTextForUplaod.setVisibility(View.VISIBLE);
mCountTextForUplaod.setText("" + mCountText);
}
}
}
}
};
Onreceive from where value is sent
#Override
public void onReceive(final Context context, final Intent intent) {
Runnable runnable = new Runnable() {
public void run() {
if (intent.getAction() != null && intent.getAction().equals(Constants.BROADCAST_INTENT_FILTER)) {
boolean broadcastStatus = intent.getBooleanExtra(Constants.BROADCAST_DATA_STATUS, false);
String broadcastStatusMessage = intent.getStringExtra(Constants.BROADCAST_DATA_STATUS_MESAGE);
if (broadcastStatus) {
mCountText = PreferenceHelper.getFromPreference(context, Constants.RECENT_IMAGES_COUNT, 0);
handler.sendEmptyMessage(PreferenceHelper.getFromPreference(context, Constants.RECENT_IMAGES_COUNT, 0));
}
} else {
if (intent.getAction() != null && intent.getAction().equals(Constants.BROADCAST_ACTION_APP_UPDATE)) {
handler.sendEmptyMessage(Constants.HANDLER_APP_UPDATE);
} else if (intent.getAction() != null && intent.getAction().equals(Constants.BROADCAST_ACTION_COLLECTION_UPDATE)) {
handler.sendEmptyMessage(Constants.HANDLER_COLLECTION_UPDATE);
}
}
}
};
Thread mythread = new Thread(runnable);
mythread.start();
Your code is too complex. You don't need the handler and definitively not the thread. Thy it like this:
#Override
public void onReceive(final Context context, final Intent intent) {
if (intent.getAction() != null && intent.getAction().equals(Constants.BROADCAST_INTENT_FILTER)) {
boolean broadcastStatus = intent.getBooleanExtra(Constants.BROADCAST_DATA_STATUS, false);
String broadcastStatusMessage = intent.getStringExtra(Constants.BROADCAST_DATA_STATUS_MESAGE);
if (broadcastStatus) {
mCountText = PreferenceHelper.getFromPreference(context, Constants.RECENT_IMAGES_COUNT, 0);
if (mCountText == 0) {
mCollectionsFragment.refreshAfterUpload();
mCountTextForUplaod.setVisibility(View.INVISIBLE);
} else {
mCollectionsFragment.refreshAfterUpload();
mCountTextForUplaod.setVisibility(View.VISIBLE);
mCountTextForUplaod.setText("" + mCountText);
}
}
} else {
if (intent.getAction() != null && intent.getAction().equals(Constants.BROADCAST_ACTION_APP_UPDATE)) {
if (!UserHelper.isAppBuildVerionSameAsUpdate(HomeActivity.this)) {
updateNotificationAlert();
showAppUpdatePopUp();
}
} else if (intent.getAction() != null && intent.getAction().equals(Constants.BROADCAST_ACTION_COLLECTION_UPDATE)) {
// TODO
}
}
}
I'm writinng Android app that receiving data via bluetooth from another device. Those data as in fact streaming non-stop. After getting about 50 or 70 of them, app slows down and stop showing me received data. App cache is full, but clearing it (deleting context.getCacheDir()) doesn't help. After restarting whole app, I can again get next part of data. WHat can I do for avoiding this "lag"?
my MainActivity:
public class MainActivity extends Activity {
private BluetoothAdapter bluetoothAdapter;
private boolean pendingRequestEnableBt = false;
private final String SAVED_PENDING_REQUEST_ENABLE_BT = "PENDING_REQUEST_ENABLE_BT";
private BluetoothResponseHandler mHandler;
private static MainActivity instance;
private DeviceConnector connector;
private TextView console;
private String deviceName;
private final int REQUEST_CONNECT_DEVICE = 1;
private final int REQUEST_ENABLE_BT = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
instance = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
console = (TextView) findViewById(R.id.main_text_console);
if (savedInstanceState != null) {
pendingRequestEnableBt = savedInstanceState.getBoolean(SAVED_PENDING_REQUEST_ENABLE_BT);
}
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(this, "No bluetooth available", Toast.LENGTH_LONG).show();
}
if (mHandler == null) {
mHandler = new BluetoothResponseHandler(this);
} else {
mHandler.setTarget(this);
}
}
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
getActionBar().setSubtitle(deviceName);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(SAVED_PENDING_REQUEST_ENABLE_BT, pendingRequestEnableBt);
outState.putString("device_name", deviceName);
if (console != null) {
final String log = console.getText().toString();
outState.putString("AC", log);
}
}
public boolean isAdapterReady() {
return (bluetoothAdapter != null) && (bluetoothAdapter.isEnabled());
}
private static class BluetoothResponseHandler extends Handler {
private WeakReference<MainActivity> mActivity;
public BluetoothResponseHandler(MainActivity activity) {
mActivity = new WeakReference<MainActivity>(activity);
}
public void setTarget(MainActivity target) {
mActivity.clear();
mActivity = new WeakReference<MainActivity>(target);
}
#Override
public void handleMessage(Message msg) {
MainActivity activity = mActivity.get();
if (activity != null) {
if (msg.what==MessageType.MESSAGE_STATE_CHANGE.getValue()) {
final ActionBar bar = activity.getActionBar();
switch (msg.arg1) {
case DeviceConnector.STATE_CONNECTED:
bar.setSubtitle("Połączono.");
break;
case DeviceConnector.STATE_CONNECTING:
bar.setSubtitle("Łączenie");
break;
case DeviceConnector.STATE_NONE:
bar.setSubtitle("Rozłączono.");
break;
}
} else if (msg.what==MessageType.MESSAGE_READ.getValue()) {
if (msg.obj != null) {
activity.appendLog((String)msg.obj);
}
} else if (msg.what==MessageType.MESSAGE_DEVICE_NAME.getValue()) {
activity.setDeviceName((String) msg.obj);
}
}
}
}
private void startDeviceListActivity() {
stopConnection();
startActivityForResult(new Intent(this, DeviceListActivity.class), REQUEST_CONNECT_DEVICE);
}
private void stopConnection() {
if (connector != null) {
connector.stop();
connector = null;
}
}
#Override
public boolean onSearchRequested() {
if (isAdapterReady()) {
startDeviceListActivity();
}
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.device_control_activity, menu);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE:
if (resultCode == Activity.RESULT_OK) {
String address = data.getStringExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
if (isAdapterReady() && (connector == null)) setupConnector(device);
}
break;
case REQUEST_ENABLE_BT:
pendingRequestEnableBt = false;
if (resultCode != Activity.RESULT_OK) {
Toast.makeText(this, "Bt not enabled", Toast.LENGTH_LONG).show();
}
break;
}
}
private void setupConnector(BluetoothDevice connectedDevice) {
stopConnection();
connector = new DeviceConnector(new DeviceData(connectedDevice, getString(R.string.empty_device_name)), mHandler);
connector.connect();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_search:
if (isAdapterReady()) {
if (isConnected()) {
stopConnection();
} else {
startDeviceListActivity();
}
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void appendLog(String message) {
String msg = message.replaceAll("[\n\t\r ]*", "");
console.append(msg.length() + ": " + msg + "\n");
final int scrollAmount = console.getLayout().getLineTop(console.getLineCount()) - console.getHeight();
console.scrollTo(0, scrollAmount>0?scrollAmount:0);
delete(getCacheDir());
}
private boolean isConnected() {
return (connector != null) && (connector.getState() == DeviceConnector.STATE_CONNECTED);
}
public static MainActivity getInstance() {
return instance;
}
public void delete(File file) {
if (file.exists()) {
if (file.isFile()) {
file.delete();
} else if (file.isDirectory()) {
for (File f:file.listFiles()) {
delete(f);
}
}
}
}
}
this code is downloaded, it isn't mine, I just modified it.
How to write all writeCharacteristics in a loop in ble in android.code is as follows
in this method i pass 3 writecharacteristic() and only one is write and others are ignored.
if (beartoggle.isChecked()) {
if (mDeviceLight.equalsIgnoreCase("on") && mDeviceAlarm.equalsIgnoreCase("on")) {
byte[] val = {1};
if (check_port_1 == 1) {
mBluetoothLeService.writeCharacteristic(val, 1);
}
if (check_port_2 == 1) {
mBluetoothLeService.writeCharacteristic(val, 2);
}
if (find_me == 1) {
mBluetoothLeService.writeCharacteristic(val, 3);
}
}
}
and someone is saying use public void onReliableWriteCompleted() and check if port1 is written then go to port2 and then findme. This method will help me, if yes then how ? Please send me clear details and following is my writeCharacteristic()
public boolean writeCharacteristic(byte value[], int type) {
//check mBluetoothGatt is available
if (mBluetoothGatt == null) {
Log.e(TAG, "lost connection");
return false;
}
BluetoothGattService Service = mBluetoothGatt.getService(UUID_SIMPLESERVICE);
if (Service == null) {
Log.e(TAG, "service not found!");
return false;
}
BluetoothGattCharacteristic charac1 = null;
BluetoothGattCharacteristic charac2 = null;
BluetoothGattCharacteristic charac3 = null;
boolean status1 = false, status2 = false, status3 = false;
Log.v("___TYPE___", "________1______________" + (type == 1));
Log.v("___TYPE___", "________2______________" + (type == 2));
Log.v("___TYPE___", "________3______________" + (type == 3));
onReliableWriteCompleted(status1);
onReliableWriteCompleted(status2);
onReliableWriteCompleted(status3);
if (type == 1) {
charac1 = Service.getCharacteristic(UUID_PORT1);
charac1.setValue(value);
status1 = mBluetoothGatt.writeCharacteristic(charac1);
Log.v("________BLESERVICE____", "___WRITE CHARATERISTICS STATUS:_________" + status1);
onReliableWriteCompleted(status1);
} else if (type == 2) {
charac2 = Service.getCharacteristic(UUID_PORT2);
charac2.setValue(value);
status2 = mBluetoothGatt.writeCharacteristic(charac2);
onReliableWriteCompleted(status2);
Log.v("________BLESERVICE_______", "___WRITE CHARACTERISTICS STATUS_______" + status2);
} else if (type == 3) {
charac3 = Service.getCharacteristic(UUID_FINDME);
charac3.setValue(value);
status3 = mBluetoothGatt.writeCharacteristic(charac3);
onReliableWriteCompleted(status3);
Log.v("__________BLESERVICE_________", "___WRITE CHARACTERISTICS STATUS_____" + status3);
}
if (charac1 == null && charac2 == null && charac3 == null) {
Log.e(TAG, "char not found!");
return false;
}
Log.v("___TYPE___", "______________________" + type);
return status1 && status2 && status3;
}
call BluetoothLeService.getSupportedGattServices(), you will get a list of services. Iterate through it and call BluetoothGattService.getCharacteristics(). You will again get a list, you can iterate through it.
For more info, you can refer this