Is their any way to get click event of keyboard in android? Actually I am developing one app and need the click event of the keyboard. Example, if user press the alphabets 'a' from keyboard in android phone then I want the click event of 'a'. Recently I came across the onKeyListener and used the various KeyCode, but eventually it didn't helped me.
public class KeyCode {
private Context con;
private EditText edt;
private ArrayList<String> array;
public KeyCode(Context con, final ArrayList<String> array, final EditText edt)
{
// TODO Auto-generated constructor stub
this.array=array;
this.con=con;
this.edt=edt;
edt.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if(keyCode==event.KEYCODE_A)
{
if(event.isCapsLockOn())
{
edt.append(array.get(0));
}
else
{
edt.append(array.get(26));
}
}
if(keyCode==event.KEYCODE_B)
{
if(event.isCapsLockOn())
{
edt.append(array.get(1));
}
else
{
edt.append(array.get(27));
}
}
if(keyCode==event.KEYCODE_C)
{
if(event.isCapsLockOn())
{
edt.append(array.get(2));
}
else
{
edt.append(array.get(28));
}
}
if(keyCode==event.KEYCODE_D)
{
if(event.isCapsLockOn())
{
edt.append(array.get(3));
}
else
{
edt.append(array.get(29));
}
}
if(keyCode==event.KEYCODE_E)
{
if(event.isCapsLockOn())
{
edt.append(array.get(4));
}
else
{
edt.append(array.get(30));
}
}
if(keyCode==event.KEYCODE_F)
{
if(event.isCapsLockOn())
{
edt.append(array.get(5));
}
else
{
edt.append(array.get(31));
}
}
if(keyCode==event.KEYCODE_G)
{
if(event.isCapsLockOn())
{
edt.append(array.get(6));
}
else
{
edt.append(array.get(32));
}
}
if(keyCode==event.KEYCODE_H)
{
if(event.isCapsLockOn())
{
edt.append(array.get(7));
}
else
{
edt.append(array.get(33));
}
}
if(keyCode==event.KEYCODE_I)
{
if(event.isCapsLockOn())
{
edt.append(array.get(8));
}
else
{
edt.append(array.get(34));
}
}
if(keyCode==event.KEYCODE_J)
{
if(event.isCapsLockOn())
{
edt.append(array.get(9));
}
else
{
edt.append(array.get(35));
}
}
if(keyCode==event.KEYCODE_K)
{
if(event.isCapsLockOn())
{
edt.append(array.get(10));
}
else
{
edt.append(array.get(36));
}
}
if(keyCode==event.KEYCODE_L)
{
if(event.isCapsLockOn())
{
edt.append(array.get(11));
}
else
{
edt.append(array.get(37));
}
}
if(keyCode==event.KEYCODE_M)
{
if(event.isCapsLockOn())
{
edt.append(array.get(12));
}
else
{
edt.append(array.get(38));
}
}
if(keyCode==event.KEYCODE_N)
{
if(event.isCapsLockOn())
{
edt.append(array.get(13));
}
else
{
edt.append(array.get(39));
}
}
if(keyCode==event.KEYCODE_O)
{
if(event.isCapsLockOn())
{
edt.append(array.get(14));
}
else
{
edt.append(array.get(40));
}
}
if(keyCode==event.KEYCODE_P)
{
if(event.isCapsLockOn())
{
edt.append(array.get(15));
}
else
{
edt.append(array.get(41));
}
}
if(keyCode==event.KEYCODE_Q)
{
if(event.isCapsLockOn())
{
edt.append(array.get(16));
}
else
{
edt.append(array.get(42));
}
}
if(keyCode==event.KEYCODE_R)
{
if(event.isCapsLockOn())
{
edt.append(array.get(17));
}
else
{
edt.append(array.get(43));
}
}
if(keyCode==event.KEYCODE_S)
{
if(event.isCapsLockOn())
{
edt.append(array.get(18));
}
else
{
edt.append(array.get(44));
}
}
if(keyCode==event.KEYCODE_T)
{
if(event.isCapsLockOn())
{
edt.append(array.get(19));
}
else
{
edt.append(array.get(45));
}
}
if(keyCode==event.KEYCODE_U)
{
if(event.isCapsLockOn())
{
edt.append(array.get(20));
}
else
{
edt.append(array.get(46));
}
}
if(keyCode==event.KEYCODE_V)
{
if(event.isCapsLockOn())
{
edt.append(array.get(21));
}
else
{
edt.append(array.get(47));
}
}
if(keyCode==event.KEYCODE_W)
{
if(event.isCapsLockOn())
{
edt.append(array.get(22));
}
else
{
edt.append(array.get(48));
}
}
if(keyCode==event.KEYCODE_X)
{
if(event.isCapsLockOn())
{
edt.append(array.get(23));
}
else
{
edt.append(array.get(49));
}
}
if(keyCode==event.KEYCODE_Y)
{
if(event.isCapsLockOn())
{
edt.append(array.get(24));
}
else
{
edt.append(array.get(50));
}
}
if(keyCode==event.KEYCODE_Z)
{
if(event.isCapsLockOn())
{
edt.append(array.get(25));
}
else
{
edt.append(array.get(51));
}
}
if(keyCode==event.KEYCODE_0)
{
edt.append(array.get(52));
}
if(keyCode==event.KEYCODE_1)
{
edt.append(array.get(53));
}
if(keyCode==event.KEYCODE_2)
{
edt.append(array.get(54));
}
if(keyCode==event.KEYCODE_3)
{
edt.append(array.get(55));
}
if(keyCode==event.KEYCODE_4)
{
edt.append(array.get(56));
}
if(keyCode==event.KEYCODE_5)
{
edt.append(array.get(57));
}
if(keyCode==event.KEYCODE_6)
{
edt.append(array.get(58));
}
if(keyCode==event.KEYCODE_7)
{
edt.append(array.get(59));
}
if(keyCode==event.KEYCODE_8)
{
edt.append(array.get(60));
}
if(keyCode==event.KEYCODE_9)
{
edt.append(array.get(61));
}
/*if(keyCode==event.KEYCODE_DEL)
{
edt.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
edt.setText(s);
}
});
}*/
/*if(keyCode==event.KEYCODE_SPACE)
{
edt.append(" ");
}*/
if(keyCode==event.KEYCODE_COMMA)
{
edt.append(",");
}
if(keyCode==event.KEYCODE_PERIOD)
{
edt.append(".");
}
if(keyCode==event.KEYCODE_EQUALS)
{
edt.append("=");
}
if(keyCode==event.KEYCODE_LEFT_BRACKET)
{
edt.append("(");
}
if(keyCode==event.KEYCODE_RIGHT_BRACKET)
{
edt.append(")");
}
if(keyCode==event.KEYCODE_SEMICOLON)
{
edt.append(";");
}
if(keyCode==event.KEYCODE_APOSTROPHE)
{
edt.append("'");
}
if(keyCode==event.KEYCODE_GRAVE)
{
edt.append("~");
}
if(keyCode==event.KEYCODE_SLASH)
{
edt.append("/");
}
if(keyCode==event.KEYCODE_NUMPAD_DIVIDE)
{
edt.append("/");
}
if(keyCode==event.KEYCODE_NUMPAD_MULTIPLY)
{
edt.append("*");
}
if(keyCode==event.KEYCODE_NUMPAD_SUBTRACT)
{
edt.append("-");
}
if(keyCode==event.KEYCODE_NUMPAD_ADD)
{
edt.append("+");
}
return true;
}
});
}
}
This is what my java class is. I have an array of certain characters and I do pass it to this java file to replace the default characters with characters contained in array. The characters are replaced but when the key is pressed from the laptop keyboard not from the keyboard of the android phone.
public class ChangeFont extends ActionBarActivity {
private EditText edt;
private ImageView img1,img2,img3,img4,img5;
private ListView lst, savelist;
private TextView txtNew,txtSave;
private DataBaseHelper data;
private ArrayList<String> category;
private ArrayList<String> styleArray;
private Cursor c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_change_font);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setTitle("Fonts");
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
data=new DataBaseHelper(this);
edt=(EditText)findViewById(R.id.edit_text);
img1=(ImageView)findViewById(R.id.image1);
img2=(ImageView)findViewById(R.id.image2);
img3=(ImageView)findViewById(R.id.image3);
img4=(ImageView)findViewById(R.id.image4);
img5=(ImageView)findViewById(R.id.image5);
lst=(ListView)findViewById(R.id.list);
savelist=(ListView)findViewById(R.id.savelist);
txtNew=(TextView)findViewById(R.id.textnew);
txtSave=(TextView)findViewById(R.id.textsave);
category=new ArrayList<String>();
styleArray=new ArrayList<String>();
try {
data.createDataBase();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c=data.getSample();
if (c.moveToFirst())
{
while(!c.isAfterLast())
{
String cat = c.getString(c.getColumnIndex(DataBaseUtil.SAMPLE));
category.add(cat);
c.moveToNext();
}
}
/*l=data.getAllLockType();
if (l.moveToFirst())
{
while(!l.isAfterLast())
{
String cat=l.getString(l.getColumnIndex(DataBaseUtil.LOCK_TYPE));
Log.i("String",""+cat);
locktype.add(cat);
l.moveToNext();
}
}
Log.i("Lock Array",""+locktype);*/
SampleStyleAdapter aa=new SampleStyleAdapter(getApplicationContext(), category);
lst.setAdapter(aa);
lst.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
data.openDataBase();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(edt, InputMethodManager.SHOW_IMPLICIT);
final String stylename = category.get(position).toString();
Toast.makeText(getApplicationContext(), "" + stylename + "position" + position, Toast.LENGTH_SHORT).show();
List<DataBaseModel> sy = data.getStyle(position);
styleArray = new ArrayList<String>();
for (DataBaseModel model : sy) {
String vimal = model.getStyle();
styleArray.add(vimal);
}
Log.i("Style Array", "" + styleArray);
KeyCode key=new KeyCode(getApplicationContext(),styleArray,edt);
//Log.i("Called Key Code","Class");
}
});
edt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lst.setVisibility(View.GONE);
savelist.setVisibility(View.GONE);
txtNew.setVisibility(View.VISIBLE);
txtSave.setVisibility(View.VISIBLE);
edt.requestFocus();
edt.setCursorVisible(true);
//InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//imm.showSoftInput(edt, InputMethodManager.SHOW_IMPLICIT);
}
});
img1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
lst.setVisibility(View.VISIBLE);
savelist.setVisibility(View.GONE);
txtNew.setVisibility(View.GONE);
txtSave.setVisibility(View.GONE);
edt.setCursorVisible(false);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edt.getWindowToken(), 0);
}
});
img2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
lst.setVisibility(View.GONE);
txtNew.setVisibility(View.VISIBLE);
txtSave.setVisibility(View.VISIBLE);
edt.requestFocus();
edt.setCursorVisible(true);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(edt, InputMethodManager.SHOW_IMPLICIT);
}
});
img3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(ChangeFont.this, EmojiTabbed.class);
startActivity(i);
}
});
img4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
lst.setVisibility(View.GONE);
savelist.setVisibility(View.VISIBLE);
txtNew.setVisibility(View.GONE);
txtSave.setVisibility(View.GONE);
edt.setCursorVisible(false);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edt.getWindowToken(), 0);
}
});
img5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(ChangeFont.this, Share.class);
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_change_font, menu);
return false;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
Intent i=new Intent(this, Home.class);
NavUtils.navigateUpTo(this, i);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Whether this thing is possible or not?
Click event occur for mouse click or touch down and for you need to capture key down event like this
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (i == KeyEvent.KEYCODE_BACK) {
//back button key up
}
return super.onKeyUp(keyCode, event);
}
and for click event you should use this
yourControl.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// your code
}
});
i hop this will help you
You can get the clicked key characters by keycodes :
List<Key> keys = getKeyboard().getKeys();
for (Key key : keys) {
if (key.codes[0] == 65) { //A
} }
For Reference
http://www.fampennings.nl/maarten/android/09keyboard/index.htm
Related
I want to scroll RecyclerView with 2 or 3 item/sec when setOnLongClickListener on image view. I searched a lot and tried a countdown timer and handler to scroll RecyclerView by specific time. but without any success. any IDEA how to achieve this.
I tried this :
private Runnable runnable = new Runnable() {
#Override
public void run() {
if (minutesCurrentPosition >= 0 && minutesCurrentPosition < minutesArray.length) {
minutesCurrentPosition++;
if (minutesCurrentPosition == minutesArray.length) {
minutesCurrentPosition--;
}
if (minutesCurrentPosition < minutesArray.length) {
rvMinutes.scrollToPosition(minutesCurrentPosition);
}
}
}
};
ivMinutesUp.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
handler.postDelayed(runnable,500);
return false;
}
});
ivMinutesUp.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
handler.postDelayed(runnable,500);
return false;
}
});
ivMinutesUp.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View pView, MotionEvent pEvent) {
// We're only interested in when the button is released.
if (pEvent.getAction() == MotionEvent.ACTION_DOWN) {
// handler.postDelayed(runnable,300);
}
switch (pEvent.getAction()) {
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
handler.removeCallbacks(runnable);
break;
}
pView.onTouchEvent(pEvent);
return false;
}
});
I used this:
private void hoursGoUpFast() {
isButtonReleased = false;
if (thread != null) {
thread.interrupt();
thread = null;
}
thread = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < hoursArray.length; i++) {
if (isButtonReleased) {
break;
} else {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
nextHour();
}
}
}
});
thread.start();
}
private void hoursGoDownFast() {
isButtonReleased = false;
if (thread != null) {
thread.interrupt();
thread = null;
}
thread = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < hoursArray.length; i++) {
if (isButtonReleased) {
break;
} else {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
previousHour();
}
}
}
});
thread.start();
}
on click :
// hours long click
ivHoursUp.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
hoursGoUpFast();
// handler.postDelayed(runnable, 500);
return false;
}
});
ivHoursDown.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
hoursGoDownFast();
// handler.postDelayed(runnable, 500);
return false;
}
});
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
How to solve "'catch' or 'finally' expected" error in android studio..?
a screenshot of the error
public class FragmentRecent extends Fragment {
View root_view, parent_view;
private RecyclerView recyclerView;
private AdapterChannel adapterChannel;
private SwipeRefreshLayout swipeRefreshLayout;
private Call<CallbackChannel> callbackCall = null;
private int post_total = 0;
private int failed_page = 0;
private InterstitialAd interstitialAd;
private OfflineDatabase databaseHelper;
int counter = 3;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root_view = inflater.inflate(R.layout.fragment_recent, null);
parent_view = getActivity().findViewById(R.id.main_content);
loadInterstitialAd();
swipeRefreshLayout = (SwipeRefreshLayout) root_view.findViewById(R.id.swipe_refresh_layout_home);
swipeRefreshLayout.setColorSchemeResources(R.color.orange, R.color.green, R.color.blue, R.color.red);
recyclerView = (RecyclerView) root_view.findViewById(R.id.recyclerViewHome);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setHasFixedSize(true);
//set data and list adapter
adapterChannel = new AdapterChannel(getActivity(), recyclerView, new ArrayList<Channel>());
recyclerView.setAdapter(adapterChannel);
// on item list clicked
adapterChannel.setOnItemClickListener(new AdapterChannel.OnItemClickListener() {
#Override
public void onItemClick(View v, Channel obj, int position) {
Intent intent = new Intent(getActivity(), ActivityDetailChannel.class);
intent.putExtra(Constant.KEY_CHANNEL_CATEGORY, obj.category_name);
intent.putExtra(Constant.KEY_CHANNEL_ID, obj.channel_id);
intent.putExtra(Constant.KEY_CHANNEL_NAME, obj.channel_name);
intent.putExtra(Constant.KEY_CHANNEL_IMAGE, obj.channel_image);
intent.putExtra(Constant.KEY_CHANNEL_URL, obj.channel_url);
intent.putExtra(Constant.KEY_CHANNEL_DESCRIPTION, obj.channel_description);
startActivity(intent);
showInterstitialAd();
}
});
// detect when scroll reach bottom
adapterChannel.setOnLoadMoreListener(new AdapterChannel.OnLoadMoreListener() {
#Override
public void onLoadMore(int current_page) {
if (post_total > adapterChannel.getItemCount() && current_page != 0) {
int next_page = current_page + 1;
requestAction(next_page);
} else {
adapterChannel.setLoaded();
}
}
});
// on swipe list
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
if (callbackCall != null && callbackCall.isExecuted()) callbackCall.cancel();
adapterChannel.resetListData();
requestAction(1);
}
});
requestAction(1);
return root_view;
}
private void displayApiResult(final List<Channel> channels) {
adapterChannel.insertData(channels);
swipeProgress(false);
if (channels.size() == 0) {
showNoItemView(true);
}
}
private void requestListPostApi(final int page_no) {
ApiInterface apiInterface = RestAdapter.createAPI();
callbackCall = apiInterface.getPostByPage(page_no, Config.LOAD_MORE);
callbackCall.enqueue(new Callback<CallbackChannel>() {
#Override
public void onResponse(Call<CallbackChannel> call, Response<CallbackChannel> response) {
CallbackChannel resp = response.body();
if (resp != null && resp.status.equals("ok")) {
post_total = resp.count_total;
displayApiResult(resp.posts);
} else {
onFailRequest(page_no);
}
}
#Override
public void onFailure(Call<CallbackChannel> call, Throwable t) {
if (!call.isCanceled()) onFailRequest(page_no);
}
});
}
private void onFailRequest(int page_no) {
failed_page = page_no;
adapterChannel.setLoaded();
swipeProgress(false);
if (NetworkCheck.isConnect(getActivity())) {
} else {
//showToast("Internet Not");
if (databaseHelper.getOfflineData("FragmentCategory").length() != 0) {
setJson(databaseHelper.getOfflineData("FragmentCategory"), false);
}
}
}
//databaseHelper.removeAll();
private void requestAction(final int page_no) {
showFailedView(false, "");
showNoItemView(false);
if (page_no == 1) {
swipeProgress(true);
} else {
adapterChannel.setLoading();
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
requestListPostApi(page_no);
}
}, Constant.DELAY_TIME);
}
#Override
public void onDestroy() {
super.onDestroy();
swipeProgress(false);
if (callbackCall != null && callbackCall.isExecuted()) {
callbackCall.cancel();
}
}
private void showFailedView(boolean show, String message) {
View lyt_failed = (View) root_view.findViewById(R.id.lyt_failed_home);
((TextView) root_view.findViewById(R.id.failed_message)).setText(message);
if (show) {
recyclerView.setVisibility(View.GONE);
lyt_failed.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_failed.setVisibility(View.GONE);
}
((Button) root_view.findViewById(R.id.failed_retry)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestAction(failed_page);
}
});
}
private void showNoItemView(boolean show) {
View lyt_no_item = (View) root_view.findViewById(R.id.lyt_no_item_home);
((TextView) root_view.findViewById(R.id.no_item_message)).setText(R.string.no_post_found);
if (show) {
recyclerView.setVisibility(View.GONE);
lyt_no_item.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_no_item.setVisibility(View.GONE);
}
}
private void swipeProgress(final boolean show) {
if (!show) {
swipeRefreshLayout.setRefreshing(show);
return;
}
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(show);
}
});
}
public void setJson(String result, Boolean isOnline) {
try {
//inseting result to database
if(isOnline) {
ContentValues offline_data = new ContentValues();
offline_data.put(OfflineDatabase.KEY_OFFLINE_DATA, result);
if(databaseHelper.getOfflineData("FragmentCategory").length()!=0) {
databaseHelper.update("FragmentCategory",offline_data);
} else {
offline_data.put(OfflineDatabase.KEY_ACTIVITY_NAME, "FragmentCategory");
databaseHelper.addOfflineData(offline_data, null);
//handle both exceptions
}
}}}
private void loadInterstitialAd() {
if (Config.ENABLE_ADMOB_INTERSTITIAL_ADS) {
interstitialAd = new InterstitialAd(getActivity());
interstitialAd.setAdUnitId(getResources().getString(R.string.admob_interstitial_unit_id));
interstitialAd.loadAd(new AdRequest.Builder().build());
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
interstitialAd.loadAd(new AdRequest.Builder().build());
}
});
} else {
Log.d("AdMob", "AdMob Interstitial is Enabled");
}
}
private void showInterstitialAd() {
if (Config.ENABLE_ADMOB_INTERSTITIAL_ADS) {
if (interstitialAd != null && interstitialAd.isLoaded()) {
if (counter == Config.ADMOB_INTERSTITIAL_ADS_INTERVAL) {
interstitialAd.show();
counter = 1;
} else {
counter++;
}
} else {
Log.d("AdMob", "Interstitial Ad is Disabled");
}
} else {
Log.d("AdMob", "AdMob Interstitial is Disabled");
}
}}
there you start with try:
public void setJson(String result, Boolean isOnline) {
try {
...
}
...
}
which has to continue with:
try {
...
} catch(Exception e) {
} finally {
}
where either catch or finally are optional (depending where the Exception shall be handled).
in my app i want to offer the user a option to set an animation as live wallpaper using WallpaeprService, also my app include a Radio player (playing in the backgroud) if app is open so you can navigate in other apps while music is playing.
my problem :
if live wallpaper is working and user try to close the app by (Swipe to exit / Recent Task),the music keeps playing although app is closed.
i tried to stop music like this ,but doesn't work :
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
#SuppressLint({"CommitPrefEdits", "Assert"})
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, KillNotificationService.class));
trackSelector = new DefaultTrackSelector();
loadControl = new DefaultLoadControl();
exoPlayer = ExoPlayerFactory.newSimpleInstance(new DefaultRenderersFactory(getApplicationContext()), trackSelector, loadControl);
MusicButton.setVisibility(View.INVISIBLE);
MusicButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (Build.VERSION.SDK_INT > 15) {
if (started && MusicButton.isChecked()) {
started = false;
exoPlayer.setPlayWhenReady(false);
MusicButton.setChecked(true);
releaseAudioFocusForMyApp(MainActivity.this);
} else {
boolean gotFocus = requestAudioFocusForMyApp(MainActivity.this);
if (gotFocus) {
started = true;
exoPlayer.setPlayWhenReady(true);
MusicButton.setChecked(false);
}
}
} else {
if (started && MusicButton.isChecked()) {
started = false;
mediaPlayer.pause();
MusicButton.setChecked(true);
releaseAudioFocusForMyApp(MainActivity.this);
} else {
boolean gotFocus = requestAudioFocusForMyApp(MainActivity.this);
if (gotFocus) {
started = true;
mediaPlayer.start();
MusicButton.setChecked(false);
}
}
}
}
});
private void playRadio(String url) {
Uri audioUri = Uri.parse(url);
DefaultHttpDataSourceFactory dataSourceFactory = new DefaultHttpDataSourceFactory("ExoPlayerDemo");
ExtractorsFactory extractor = new DefaultExtractorsFactory();
MediaSource audioSource = new ExtractorMediaSource.Factory(dataSourceFactory).setExtractorsFactory(extractor).createMediaSource(audioUri);
exoPlayer.prepare(audioSource);
prepared = true;
exoPlayer.setPlayWhenReady(true);
exoPlayer.addListener(new Player.EventListener() {
#Override
public void onTimelineChanged(Timeline timeline, #Nullable Object manifest, int reason) {
}
#Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
}
#Override
public void onLoadingChanged(boolean isLoading) {
}
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if (isPreparing && playbackState == ExoPlayer.STATE_READY) {
MusicButton.setVisibility(View.VISIBLE);
MusicButton.setChecked(true);
isPreparing = false;
isReady = true;
}
}
#Override
public void onRepeatModeChanged(int repeatMode) {
}
#Override
public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {
}
#Override
public void onPlayerError(ExoPlaybackException error) {
}
#Override
public void onPositionDiscontinuity(int reason) {
}
#Override
public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
}
#Override
public void onSeekProcessed() {
}
});
}
#Override
protected void onResume() {
super.onResume();
try {
MApplication.sBus.register(this);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
MApplication.sBus.unregister(this);
} catch (Exception e) {
e.printStackTrace();
}
MApplication.sBus.post(PlaybackEvent.PAUSE);
}
#Override
protected void onStart() {
super.onStart();
}
#Subscribe
public void handlePlaybackEvent(PlaybackEvent event) {
switch (event) {
case PAUSE:
if (Build.VERSION.SDK_INT > 15) {
if (exoPlayer.getPlayWhenReady()) {
exoPlayer.setPlayWhenReady(false);
MusicButton.setChecked(true);
}
} else {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
MusicButton.setChecked(true);
}
}
break;
case PLAY:
if (Build.VERSION.SDK_INT > 15) {
if (!exoPlayer.getPlayWhenReady()) {
exoPlayer.setPlayWhenReady(true);
MusicButton.setChecked(false);
}
} else {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
MusicButton.setChecked(false);
}
}
break;
}
}
#Override
public void onPause() {
super.onPause();
}
}
}
problem solved by checking if live wallpaper are running in the backgroud or not:
#Override
protected void onDestroy() {
super.onDestroy();
try {
WallpaperManager wpm = WallpaperManager.getInstance(this);
WallpaperInfo info = wpm.getWallpaperInfo();
if (info != null && info.getPackageName().equals(this.getPackageName())) {
/*stop music*/
} else {
Log.d(TAG, "We're not running");
}
} catch (Exception e) {
e.printStackTrace();
}
}
I have a problem with SpeechRecognizer on android. Here's my code:
public class MyRecognizerListener implements RecognitionListener {
String id;
MyRecognizerListener(String id){
this.id = id;
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onBeginningOfSpeech() {
Log.d("Speech", "Inizia ad Ascoltare");
}
#Override
public void onReadyForSpeech(Bundle params) {
Log.d("Speech", "E' pronto ad Ascoltare");
}
#Override
public void onPartialResults(Bundle results) {
matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if(matches.size() > 1) {
Log.d("Speech", "Risultati Parziali = " + Integer.toString(matches.size()));
for (int i = 0; i < matches.size(); i++) {
Log.d("Speech", matches.get(i));
}
if (matches.contains("si") || matches.contains("sì") || matches.contains("Sì")
|| matches.contains("yes") || matches.contains("ES")) {
Opera opera = createOpera(id);
startAudio(opera);
}
matches = null;
turnSpeechOff = false;
speechRecognizer.cancel();
speechRecognizer.destroy();
speechRecognizer = null;
}
}
#Override
public void onEvent(int eventType, Bundle params) {
}
#Override
public void onError(int error) {
if(turnSpeechOff) {
Log.d("Speech", Integer.toString(error));
turnSpeechOff = false;
speechRecognizer.cancel();
speechRecognizer.destroy();
speechRecognizer = null;
}
}
#Override
public void onRmsChanged(float rmsdB) {
}
#Override
public void onBufferReceived(byte[] buffer) {
}
#Override
public void onResults(Bundle results) {
matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
for (int i = 0; i < matches.size(); i++){
Log.d("Parole", matches.get(i));
}
if(matches.contains("si") || matches.contains("sì") || matches.contains("Sì")
|| matches.contains("yes") || matches.contains("ES")){
Opera opera = createOpera(id);
startAudio(opera);
}
matches = null;
turnSpeechOff = false;
speechRecognizer.cancel();
speechRecognizer.destroy();
speechRecognizer = null;
}
}
public void startAudioAsk(final String art_id){
if(speechRecognizer != null) {
return;
}
if(audioPlayer == null || !audioPlayer.isPlaying() ) {
if(operaAudioAsk != null && operaAudioAsk.equals(art_id)){
return;
}
operaAudioAsk = art_id;
if(language.equals("IT")) {
audioPlayer = MediaPlayer.create(this, R.raw.chiedi);
} else {
audioPlayer = MediaPlayer.create(this, R.raw.ask);
}
audioPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
audioPlayer.reset();
audioPlayer.release();
int audioTitle;
if(language.equals("IT")){
audioTitle = getResources().getIdentifier(art_id + "_title" + "_it", "raw", getPackageName());
audioPlayer = MediaPlayer.create(MainActivity.this, audioTitle);
} else {
audioTitle = getResources().getIdentifier(art_id + "_title" + "_en", "raw", getPackageName());
audioPlayer = MediaPlayer.create(MainActivity.this, audioTitle);
}
audioPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
askVoice(art_id);
audioPlayer.reset();
audioPlayer.release();
audioPlayer = null;
}
});
audioPlayer.start();
}
});
audioPlayer.start();
}
}
public void askVoice(String art_id){
if(speechRecognizer == null) {
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
speechRecognizer.setRecognitionListener(new MyRecognizerListener(art_id));
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getPackageName());
intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3);
intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
if(language.equals("IT")){
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "it");
} else {
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en_US");
}
speechRecognizer.startListening(intent);
voiceTimer = new Timer();
voiceTimer.schedule(new StopVoiceManager(), 2000);
Log.d("Speech", "Starta");
}
}
public void stopVoice(){
if(speechRecognizer != null){
Log.d("Speech", "Cancello");
turnSpeechOff = true;
speechRecognizer.stopListening();
}
}
public class StopVoiceManager extends TimerTask{
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
stopVoice();
Log.d("Speech", "Prova a Cancellare");
}
});
}
}
As you can see, there's also a task that, after 2 seconds, calls speechRecognizer.stoplistening().
The first listening is ok, I say "yes" and it recognizes it, but the second listening raises the ERROR_CLIENT and it doesn't recognize anything, then the third listening returns to be ok, the fourth doesn't recognize anything and so.
How can i fix this bug?
while playing music using this mediaplayer, whenever a call comes, home button is pressed and lockscreen appears and on return to the app after the above problems...the play button in the app doesnt respond....I want to pause the music untill I return to the app and should continue playing from where it had stopped......plz help...
ekdanta.java
public class ekdanta extends AppCompatActivity implements Runnable,View.OnClickListener,SeekBar.OnSeekBarChangeListener {
TextView tv4;
Button b9, b10,but19;
int count = 0;
MediaPlayer play;
SeekBar seek_bar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ekdanta);
tv4 = (TextView) findViewById(R.id.textView9);
tv4.setTextSize((float)21.5);
tv4.setText(Html.fromHtml(getString(R.string.thirteen)));
b9 = (Button) findViewById(R.id.b9);
b10 = (Button) findViewById(R.id.b10);
seek_bar = (SeekBar) findViewById(R.id.seekBar);
seek_bar.setOnSeekBarChangeListener(this);
seek_bar.setEnabled(false);
but19 = (Button) findViewById(R.id.button19);
but19.setOnClickListener(this);
}
public void run() {
int currentPosition= play.getCurrentPosition();
int total = play.getDuration();
while (play!=null && currentPosition<total) {
try {
Thread.sleep(1000);
currentPosition= play.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seek_bar.setProgress(currentPosition);
}
}
public void onClick(View v) {
if (v.equals(but19)) {
if (play == null) {
play = MediaPlayer.create(getApplicationContext(), R.raw.ekadanta);
seek_bar.setEnabled(true);
}
if (play.isPlaying()) {
play.pause();
but19.setText("Play");
} else {
play.start();
but19.setText("Pause");
seek_bar.setMax(play.getDuration());
new Thread(this).start();
}
}
}
#Override
protected void onPause() {
if(play!=null){
play.stop();
}
super.onPause();
}
public void increase(View inc) {
count++;
if (count == 1) {
tv4.setTextSize(25);
} else if (count == 2) {
tv4.setTextSize(30);
} else if (count >= 3) {
count = 3;
tv4.setTextSize(40);
}
}
public void decrease(View dec) {
count--;
if (count <= 0) {
tv4.setTextSize((float)21.5);
count = 0;
}
if (count == 1) {
tv4.setTextSize(25);
} else if (count == 2) {
tv4.setTextSize(30);
} else if (count == 3) {
tv4.setTextSize(40);
}
}
#Override
public void onProgressChanged(SeekBar seek_bar, int progress, boolean fromUser) {
try{
if(play.isPlaying()||play!=null){
if (fromUser)
play.seekTo(progress);
}
else if(play==null){
Toast.makeText(getApplicationContext(),"First Play",Toast.LENGTH_SHORT).show();
seek_bar.setProgress(0);
}
}
catch(Exception e){
Log.e("seek bar",""+e);
seek_bar.setEnabled(false);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
#Override
protected void onPause()
{
super.onPause();
if (play3!= null)
{
play3.pause();
}
}
#Override
protected void onResume()
{
super.onResume();
if ((play3 != null) && (!play3.isPlaying())) {
but32.setText("Play");
but32.setOnClickListener(this);
}
}
This helped me to overcome my problems.....I'm able to play the music which gets paused when home button/lockscreen/calls appears...from where it had stopped