save url when re rotate screen from landscape to protrit - java

I'm trying to play video on player and the video is url that I fetch from an api
so I have a channels in recycleview1 and when I click on one channel the channel start play in new activity
in that activity the player take half of screen and the rest is for recycleview2 which contain some channels for easy and fast navigate between channels
so when I open the channel from recycleview1 and it start playing then I rotate the screen to landscape it work fine then restore the screen to portrate again the channel still working
but the problem is when I click on channel from recycleview2 which lead to update the url that already played and start the new one
so each time I click on channel from recycleview2 the videoview updated to new channel url that clicked
I face problem when I rotate the screen after played channel from recycleview2 the videoview start play a channel that I clicked from recyclewview1 before clicking on new channel from recycleview2 because it return to onCreate method which build the url depend on the information passed with on click
so I used to save the instance state of url so when I rotate the screen to landscape the vidoeview still played the last channel that played
but the problem is when I re rotate the screen to portrate again the videoview here return to the first channel played when start the activity
I tried to save instance state too but it doesn't working
this is the code:
public class TVChannel extends AppCompatActivity implements
TVAdapter.TVAdapterOnClickHandler {
private VideoView videoView;
private int position = 0;
private String video;
private MediaController mediaController;
String mChannelTitle;
String mChannelApp;
String mChannelStreamname;
String mChannelCat;
TVAdapter mAdapter;
RecyclerView mSportsList;
private TextView mCategory;
private TextView mErrorMessageDisplay;
private ProgressBar mLoadingIndicator;
Context mContext ;
public TVItem channelObject;
Uri vidUri;
String myBoolean;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.activity_tv_channel);
ButterKnife.bind(this);
mSportsList = (RecyclerView) findViewById(R.id.rv_channel);
mErrorMessageDisplay = (TextView) findViewById(R.id.tv_error_message_display);
mContext = this;
channelObject = getIntent().getParcelableExtra("TVChannel");
if (channelObject != null) {
mChannelTitle = String.valueOf(channelObject.getTitle());
mChannelApp = String.valueOf(channelObject.getApp());
mChannelStreamname = String.valueOf(channelObject.getStreamName());
mChannelCat = String.valueOf(channelObject.getCat());
}
mCategory = (TextView) findViewById(R.id.category);
videoView = (VideoView) findViewById(R.id.videoView);
String host = "http://ip/";
String app = mChannelApp;
String streamname = mChannelStreamname;
String playlist = "playlist.m3u8";
vidUri = Uri.parse(host).buildUpon()
.appendPath(app)
.appendPath(streamname)
.appendPath(playlist)
.build();
videoView.setVideoURI(vidUri);
final PlayerControlView playerControlView = (PlayerControlView) findViewById(R.id.player_control_view);
playerControlView.setAlwaysShow(true);
PlayerControlView.ViewHolder viewHolder = playerControlView.getViewHolder();
viewHolder.pausePlayButton.setPauseDrawable(ContextCompat.getDrawable(this, R.drawable.pause));
viewHolder.pausePlayButton.setPlayDrawable(ContextCompat.getDrawable(this, R.drawable.play));
viewHolder.controlsBackground.setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));
viewHolder.currentTimeText.setTextColor(ContextCompat.getColor(this, R.color.colorAccent));
// viewHolder.totalTimeText.setTextSize(18);
playerControlView.setNextListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TVChannel.this, "onClick Next", Toast.LENGTH_SHORT).show();
}
});
playerControlView.setPrevListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TVChannel.this, "onClick Prev", Toast.LENGTH_SHORT).show();
}
});
mediaController = playerControlView.getMediaControllerWrapper();
videoView.setMediaController(mediaController);
videoView.seekTo(position);
videoView.start();
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
playerControlView.show();
}
});
GridLayoutManager LayoutManagerSports = new GridLayoutManager(this, 3);
mSportsList.setLayoutManager(LayoutManagerSports);
mSportsList.setHasFixedSize(true);
mAdapter = new TVAdapter(this, mContext);
mSportsList.setAdapter(mAdapter);
mLoadingIndicator = (ProgressBar) findViewById(R.id.pb_loading_indicator);
String sortchannels = mChannelCat.toLowerCase() + ".php";
loadTVData(sortchannels);
} else {
setContentView(R.layout.activity_tv_channel2);
ButterKnife.bind(this);
mSportsList = (RecyclerView) findViewById(R.id.rv_channel);
mErrorMessageDisplay = (TextView) findViewById(R.id.tv_error_message_display);
mContext = this;
channelObject = getIntent().getParcelableExtra("TVChannel");
if (channelObject != null) {
mChannelTitle = String.valueOf(channelObject.getTitle());
mChannelApp = String.valueOf(channelObject.getApp());
mChannelStreamname = String.valueOf(channelObject.getStreamName());
mChannelCat = String.valueOf(channelObject.getCat());
}
mCategory = (TextView) findViewById(R.id.category);
videoView = (VideoView) findViewById(R.id.videoView);
if (savedInstanceState != null){
myBoolean = savedInstanceState.getString("video");
Toast.makeText(this, "This is my Toast message!",
Toast.LENGTH_LONG).show();
videoView.setVideoURI(Uri.parse(myBoolean));
}
else {
String host = "http://ip/";
String app = mChannelApp;
String streamname = mChannelStreamname;
String playlist = "playlist.m3u8";
vidUri = Uri.parse(host).buildUpon()
.appendPath(app)
.appendPath(streamname)
.appendPath(playlist)
.build();
videoView.setVideoURI(vidUri);
}
final PlayerControlView playerControlView = (PlayerControlView) findViewById(R.id.player_control_view);
playerControlView.setAlwaysShow(false);
PlayerControlView.ViewHolder viewHolder = playerControlView.getViewHolder();
viewHolder.pausePlayButton.setPauseDrawable(ContextCompat.getDrawable(this, R.drawable.pause));
viewHolder.pausePlayButton.setPlayDrawable(ContextCompat.getDrawable(this, R.drawable.play));
viewHolder.controlsBackground.setBackgroundColor(ContextCompat.getColor(this, R.color.controlBackground));
viewHolder.currentTimeText.setTextColor(ContextCompat.getColor(this, R.color.colorAccent));
// viewHolder.totalTimeText.setTextSize(18);
playerControlView.setNextListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TVChannel.this, "onClick Next", Toast.LENGTH_SHORT).show();
}
});
playerControlView.setPrevListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TVChannel.this, "onClick Prev", Toast.LENGTH_SHORT).show();
}
});
mediaController = playerControlView.getMediaControllerWrapperFullScreen();
videoView.setMediaController(mediaController);
videoView.seekTo(position);
videoView.start();
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
playerControlView.show();
}
});
GridLayoutManager LayoutManagerSports = new GridLayoutManager(this, 3);
mSportsList.setLayoutManager(LayoutManagerSports);
mSportsList.setHasFixedSize(true);
mAdapter = new TVAdapter(this, mContext);
mSportsList.setAdapter(mAdapter);
mLoadingIndicator = (ProgressBar) findViewById(R.id.pb_loading_indicator);
String sortchannels = mChannelCat.toLowerCase() + ".php";
loadTVData(sortchannels);
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Store current position.
savedInstanceState.putString("video", String.valueOf(vidUri));
videoView.start();
}
// After rotating the phone. This method is called.
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Get saved position.
video = savedInstanceState.getString("video");
videoView.start();
}
private void loadTVData(String sortChannels) {
showTVDataView();
new FetchTVTask().execute(sortChannels);
}
#Override
public void onClick(TVItem channel, View view) {
if (channel != null) {
mChannelTitle = String.valueOf(channel.getTitle());
mChannelApp = String.valueOf(channel.getApp());
mChannelStreamname = String.valueOf(channel.getStreamName());
}
String host = "http://ip/";
String app = mChannelApp;
String streamname = mChannelStreamname;
String playlist = "playlist.m3u8";
vidUri = Uri.parse(host).buildUpon()
.appendPath(app)
.appendPath(streamname)
.appendPath(playlist)
.build();
videoView.setVideoURI(vidUri);
final PlayerControlView playerControlView = (PlayerControlView) findViewById(R.id.player_control_view);
playerControlView.setAlwaysShow(true);
PlayerControlView.ViewHolder viewHolder = playerControlView.getViewHolder();
viewHolder.pausePlayButton.setPauseDrawable(ContextCompat.getDrawable(this, R.drawable.pause));
viewHolder.pausePlayButton.setPlayDrawable(ContextCompat.getDrawable(this, R.drawable.play));
viewHolder.controlsBackground.setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));
viewHolder.currentTimeText.setTextColor(ContextCompat.getColor(this, R.color.colorAccent));
// viewHolder.totalTimeText.setTextSize(18);
playerControlView.setNextListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TVChannel.this, "onClick Next", Toast.LENGTH_SHORT).show();
}
});
playerControlView.setPrevListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TVChannel.this, "onClick Prev", Toast.LENGTH_SHORT).show();
}
});
videoView.setMediaController(playerControlView.getMediaControllerWrapper());
//
videoView.seekTo(position);
videoView.start();
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
playerControlView.show();
}
});
}
private void showTVDataView() {
mErrorMessageDisplay.setVisibility(View.INVISIBLE);
mSportsList.setVisibility(View.VISIBLE);
}
private void showErrorMessage() {
mSportsList.setVisibility(View.INVISIBLE);
mErrorMessageDisplay.setVisibility(View.VISIBLE);
}
public class FetchTVTask extends AsyncTask<String, Void, ArrayList<TVItem>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mLoadingIndicator.setVisibility(View.VISIBLE);
}
#Override
protected ArrayList<TVItem> doInBackground(String... params) {
if (params.length == 0) {
return null;
}
String sortChannels = params[0];
URL channelRequestUrl = NetworkTV.buildUrl(sortChannels);
try {
String jsonTVResponse = NetworkTV.getResponseFromHttpUrl(channelRequestUrl);
ArrayList<TVItem> simpleJsonTVData = JsonTV.getSimpleTVStringsFromJson(TVChannel.this, jsonTVResponse);
return simpleJsonTVData;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(ArrayList<TVItem> TVData) {
mLoadingIndicator.setVisibility(View.INVISIBLE);
mCategory.setText(TVData.get(0).getCat());
if (TVData != null) {
showTVDataView();
mAdapter.setTVData(TVData);
} else {
showErrorMessage();
}
}
}
}
you can see that I use:
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
}
else{
}
to set content view for portrait and landscape
and inside else this is the code that I use to save the url in landscape mode:
if (savedInstanceState != null){
myBoolean = savedInstanceState.getString("video");
Toast.makeText(this, "This is my Toast message!",
Toast.LENGTH_LONG).show();
videoView.setVideoURI(Uri.parse(myBoolean));
}
else {
String host = "http://ip/";
String app = mChannelApp;
String streamname = mChannelStreamname;
String playlist = "playlist.m3u8";
vidUri = Uri.parse(host).buildUpon()
.appendPath(app)
.appendPath(streamname)
.appendPath(playlist)
.build();
videoView.setVideoURI(vidUri);
}
and if savedInstanceState null so build url like this from on click information that I pass in portrait mode:
channelObject = getIntent().getParcelableExtra("TVChannel");
if (channelObject != null) {
mChannelTitle = String.valueOf(channelObject.getTitle());
mChannelApp = String.valueOf(channelObject.getApp());
mChannelStreamname = String.valueOf(channelObject.getStreamName());
mChannelCat = String.valueOf(channelObject.getCat());
}
how can I save the url channel when I re rotate screen from landscape to portrait mode again?

Related

Service not registered

I am trying to setup minimized player in my music player app after setup complete now facing this service not registered problem. When I try to play song it will happen again and again.
here is my code
public class PlayingBottomFragment extends Fragment implements ServiceConnection {
private static final String TAG = PlayingBottomFragment.class.getSimpleName();
RoundedImageView img_song_art;
ImageView img_next_song;
FloatingActionButton fab_pause_play;
TextView tv_song_name, tv_artist_name;
View view;
MusicService musicService;
public PlayingBottomFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_playing_bottom, container, false);
img_song_art = view.findViewById(R.id.img_song_art);
img_next_song = view.findViewById(R.id.img_next_song);
fab_pause_play = view.findViewById(R.id.fab_pause_play);
tv_song_name = view.findViewById(R.id.tv_song_name);
tv_artist_name = view.findViewById(R.id.tv_artist_name);
tv_song_name.setSelected(true);
img_next_song.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (musicService != null){
musicService.nextClicked();
if (getActivity() != null);{
MPPreferenceManager.setString(MPConstants.MUSIC_FILE, musicService.songsModels.get(musicService.position).getPath());
MPPreferenceManager.setString(MPConstants.SONG_NAME, musicService.songsModels.get(musicService.position).getTitle());
MPPreferenceManager.setString(MPConstants.ARTIST_NAME, musicService.songsModels.get(musicService.position).getArtist());
String path = MPPreferenceManager.getString(MPConstants.MUSIC_FILE, null);
String song = MPPreferenceManager.getString(MPConstants.SONG_NAME, null);
String artist = MPPreferenceManager.getString(MPConstants.ARTIST_NAME, null);
if (path != null){
SHOW_MINI_PLAYER = true;
PATH_TO_FLAG = path;
SONG_NAME_TO_FLAG = song;
ARTIST_TO_FLAG = artist;
}else{
SHOW_MINI_PLAYER = false;
PATH_TO_FLAG = null;
SONG_NAME_TO_FLAG = null;
ARTIST_TO_FLAG = null;
}
if (SHOW_MINI_PLAYER){
if (PATH_TO_FLAG != null){
byte[] art = getAlbumArt(PATH_TO_FLAG);
if (art != null) {
Glide.with(getContext()).load(art).into(img_song_art);
}else{
Glide.with(getContext()).load(R.drawable.profile).into(img_song_art);
}
tv_song_name.setText(SONG_NAME_TO_FLAG);
tv_artist_name.setText(ARTIST_TO_FLAG);
}
}
}
}
}
});
fab_pause_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
musicService.playPauseClicked();
if (musicService.isPlaying()){
fab_pause_play.setImageResource(R.drawable.ic_round_pause_24);
}else{
fab_pause_play.setImageResource(R.drawable.ic_round_play_arrow_24);
}
}
});
return view;
}
#Override
public void onResume() {
super.onResume();
if (SHOW_MINI_PLAYER){
if (PATH_TO_FLAG != null){
byte[] art = getAlbumArt(PATH_TO_FLAG);
if (art != null) {
Glide.with(getContext()).load(art).into(img_song_art);
}else{
Glide.with(getContext()).load(R.drawable.profile).into(img_song_art);
}
Log.e(TAG, "onResume: path to flag: " + PATH_TO_FLAG );
Log.e(TAG, "onResume: path to flag: " + ARTIST_TO_FLAG );
tv_song_name.setText(SONG_NAME_TO_FLAG);
tv_artist_name.setText(ARTIST_TO_FLAG);
Intent intent = new Intent(getContext(), MusicService.class);
if (getContext() != null){
getContext().bindService(intent, this, Context.BIND_ABOVE_CLIENT);
}
}
}
}
#Override
public void onPause() {
super.onPause();
if (getContext() != null){
getContext().unbindService(this);
}
}
public byte[] getAlbumArt(String uri){
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(uri);
byte[] art = retriever.getEmbeddedPicture();
retriever.release();
return art;
}
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
MusicService.MyBinder binder = (MusicService.MyBinder) iBinder;
musicService = binder.getService();
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
musicService = null;
}
}
Here is my logcat image

Scanning for bluetooth devices programmatically don't find anything in android 6+

I created an application which pairs a cellphone to a bluetooth module.
i tested this application with a 4.2 android cellphone and it worked quite well but in cellphones with android higher than 6 the device is not fidning anything when i press " Scan for new devices " button.
but when i go through my phone bluetooth itself, i can find the module i was looking for..
Bluetooth connection class :
public class BluetoothConnectionActivity extends AppCompatActivity {
private ProgressDialog mProgressDlg;
private ArrayList<BluetoothDevice> mDeviceList = new ArrayList<BluetoothDevice>();
private BluetoothAdapter mBluetoothAdapter;
BluetoothDevice device ;
private MediaPlayer mediaplayer = null ;
private Button bluetoothOnOff;
private Button viewpairedDevices;
private Button scanfornewDevices;
private Button blue2;
ImageView unMute;
View view1;
View view2;
private Activity context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bluetoothconnectionlayout);
bluetoothOnOff = (Button) findViewById(R.id.bluetoothOnOff);
viewpairedDevices = (Button) findViewById(R.id.viewpairedDevicesButton);
scanfornewDevices = (Button) findViewById(R.id.scanfornewDevicesButton);
blue2 = (Button) findViewById(R.id.bluetoothOnOff2);
view1 = findViewById(R.id.viewFader);
view2 = findViewById(R.id.viewFader2);
unMute = (ImageView) findViewById(R.id.settingStartupSecondary);
mediaplayer = MediaPlayer.create(getApplicationContext(),R.raw.sfxturnon);
Handler startup1 = new Handler();
startup1.postDelayed(new Runnable() {
#Override
public void run() {
view1.animate().alpha(1f).setDuration(500);
view2.animate().alpha(1f).setDuration(500);
}
},1000);
Handler startup2 = new Handler();
startup2.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothOnOff.animate().alpha(1f).setDuration(500);
viewpairedDevices.animate().alpha(1f).setDuration(500);
scanfornewDevices.animate().alpha(1f).setDuration(500);
unMute.animate().alpha(1f).setDuration(100);
}
},1000);
//
// settingBtn.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
//
//
// AudioManager amanager=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
// amanager.setStreamMute(AudioManager.STREAM_NOTIFICATION, true);
//
//// settingBtn.setEnabled(false);
//// settingBtn.animate().alpha(0f);
//
// unMute.animate().alpha(1f);
// unMute.setEnabled(true);
//
//
// Toast.makeText(getApplicationContext(), " Application muted. ", Toast.LENGTH_SHORT).show();
//
//
// }
// });
Handler dawg = new Handler();
dawg.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothOnOff.animate().alpha(1f).setDuration(1500);
viewpairedDevices.animate().alpha(1f).setDuration(2500);
scanfornewDevices.animate().alpha(1f).setDuration(3000);
}
},500);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mProgressDlg = new ProgressDialog(this);
mProgressDlg.setMessage("Scanning, Please wait...");
mProgressDlg.setCancelable(false);
mProgressDlg.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mBluetoothAdapter.cancelDiscovery();
}
});}
if (mBluetoothAdapter.isEnabled()){
bluetoothOnOff.setText("Bluetooth is On");
blue2.setText("Bluetooth is On");
}else {
blue2.setText("Bluetooth is Off");
bluetoothOnOff.setText("Bluetooth is Off");
}
if (mBluetoothAdapter == null) {
showUnsupported();
} else {
viewpairedDevices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices == null || pairedDevices.size() == 0) {
Toast toast = Toast.makeText(getApplicationContext()," No paired device found.", Toast.LENGTH_SHORT);
View view3 = toast.getView();
view3.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view3.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
} else {
ArrayList<BluetoothDevice> list = new ArrayList<BluetoothDevice>();
list.addAll(pairedDevices);
Intent intent = new Intent(BluetoothConnectionActivity.this, DeviceList.class);
intent.putParcelableArrayListExtra("device.list", list);
startActivity(intent);
}
}
});
scanfornewDevices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mBluetoothAdapter.startDiscovery();
}
});
bluetoothOnOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
showDisabled();
bluetoothOnOff.setText("Bluetooth is OFF");
final Handler handler6 = new Handler();
handler6.postDelayed(new Runnable() {
#Override
public void run() {
mediaplayer.start();
}
}, 500);
final Handler handler3 = new Handler();
handler3.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothOnOff.animate().translationY(-1f).setDuration(5000);
blue2.animate().translationY(-1f).setDuration(5000);
bluetoothOnOff.animate().alpha(1f).setDuration(3000);
blue2.animate().alpha(0f).setDuration(3000);
}
}, 500);
} else {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1000);
}}
});
blue2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
showDisabled();
bluetoothOnOff.setText("Bluetooth is OFF");
final Handler handler6 = new Handler();
handler6.postDelayed(new Runnable() {
#Override
public void run() {
mediaplayer.start();
}
}, 500);
final Handler handler3 = new Handler();
handler3.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothOnOff.animate().translationY(-1f).setDuration(5000);
blue2.animate().translationY(-1f).setDuration(5000);
bluetoothOnOff.animate().alpha(1f).setDuration(3000);
blue2.animate().alpha(0f).setDuration(3000);
}
}, 500);
} else {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1000);
}}
});
if (mBluetoothAdapter.isEnabled()) {
showEnabled();
} else {
showDisabled();
}
}
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
}
#Override
public void onPause() {
if (mBluetoothAdapter != null) {
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
}
super.onPause();
}
#Override
public void onBackPressed() {
}
#Override
public void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
private void showEnabled() {
bluetoothOnOff.setEnabled(true);
viewpairedDevices.setEnabled(true);
viewpairedDevices.setBackgroundResource(R.drawable.selectorstylish);
scanfornewDevices.setEnabled(true);
scanfornewDevices.setBackgroundResource(R.drawable.selectorstylish);
}
private void showDisabled() {
bluetoothOnOff.setEnabled(true);
viewpairedDevices.setEnabled(false);
viewpairedDevices.setBackgroundResource(R.drawable.selectorstylish);
scanfornewDevices.setEnabled(false);
scanfornewDevices.setBackgroundResource(R.drawable.selectorstylish);
}
private void showUnsupported() {
Toast toast = Toast.makeText(getApplicationContext()," Bluetooth is not supported by this device.", Toast.LENGTH_SHORT);
View view3 = toast.getView();
view3.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view3.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
bluetoothOnOff.setEnabled(false);
viewpairedDevices.setEnabled(false);
viewpairedDevices.setBackgroundResource(R.drawable.selectorstylish);
scanfornewDevices.setEnabled(false);
scanfornewDevices.setBackgroundResource(R.drawable.selectorstylish);
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
if (state == BluetoothAdapter.STATE_ON) {
bluetoothOnOff.setText("Bluetooth is On");
blue2.setText("Bluetooth is On");
showEnabled();
final Handler handler5 = new Handler();
handler5.postDelayed(new Runnable() {
#Override
public void run() {
mediaplayer.start();
}
}, 500);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
bluetoothOnOff.animate().translationY(150f).setDuration(5000);
blue2.animate().translationY(150f).setDuration(5000);
bluetoothOnOff.animate().alpha(0f).setDuration(3000);
blue2.animate().alpha(1f).setDuration(3000);
}
}, 500);
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
mDeviceList = new ArrayList<BluetoothDevice>();
mProgressDlg.show();
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
mProgressDlg.dismiss();
// Intent newIntent = new Intent(BluetoothConnectionActivity.this, DeviceList.class);
//
// newIntent.putParcelableArrayListExtra("device.list", mDeviceList);
//
// startActivity(newIntent);
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device);
Toast toast = Toast.makeText(getApplicationContext()," Found device" + device.getName(), Toast.LENGTH_SHORT);
View view3 = toast.getView();
view3.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view3.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
}
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.optionmenu,menu);
return super.onCreateOptionsMenu(menu);
}
}
Device list Class :
public class DeviceList extends AppCompatActivity {
private ListView mListView;
private AdapterClassBluetooth mAdapterClassBluetooth;
private ArrayList<BluetoothDevice> mDeviceList;
private BluetoothDevice device ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_list);
mDeviceList = getIntent().getExtras().getParcelableArrayList("device.list");
mListView = (ListView) findViewById(R.id.lv_paired);
mAdapterClassBluetooth = new AdapterClassBluetooth(this);
mAdapterClassBluetooth.setData(mDeviceList);
mAdapterClassBluetooth.setListener(new AdapterClassBluetooth.OnPairButtonClickListener() {
#Override
public void onPairButtonClick(int position) {
BluetoothDevice device = mDeviceList.get(position);
if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
unpairDevice(device);
} else {
Toast toast = Toast.makeText(getApplicationContext(), "Pairing..." , Toast.LENGTH_SHORT);
View view = toast.getView();
view.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
pairDevice(device);
}
}
});
mListView.setAdapter(mAdapterClassBluetooth);
registerReceiver(mPairReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));
}
#Override
public void onDestroy() {
unregisterReceiver(mPairReceiver);
super.onDestroy();
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private void pairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
private void unpairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("removeBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
final int prevState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);
if (state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING) {
Toast toast = Toast.makeText(getApplicationContext()," Device are paired, please wait...", Toast.LENGTH_SHORT);
View view = toast.getView();
view.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
Handler delaying = new Handler();
delaying.postDelayed(new Runnable() {
#Override
public void run() {
Intent communicate = new Intent(DeviceList.this,Security.class);
startActivity(communicate);
finish();
}
},1500);
} else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED){
Toast toast = Toast.makeText(getApplicationContext(),"Unpaired.", Toast.LENGTH_SHORT);
View view = toast.getView();
view.setBackgroundColor(Color.parseColor("#ffff5b"));
TextView text = (TextView) view.findViewById(android.R.id.message);
text.setTextColor(Color.parseColor("#000000"));
toast.show();
}
mAdapterClassBluetooth.notifyDataSetChanged();
}
}
};}
Adapter class :
public class AdapterClassBluetooth extends BaseAdapter{
private LayoutInflater mInflater;
private List<BluetoothDevice> mData;
private OnPairButtonClickListener mListener;
public AdapterClassBluetooth(){
}
public AdapterClassBluetooth(Context context) {
super();
mInflater = LayoutInflater.from(context);
}
public void setData(List<BluetoothDevice> data) {
mData = data;
}
public void setListener(OnPairButtonClickListener listener) {
mListener = listener;
}
public int getCount() {
return (mData == null) ? 0 : mData.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.adapterlist, null);
holder = new ViewHolder();
holder.nameTv = (TextView) convertView.findViewById(R.id.tv_name);
holder.addressTv = (TextView) convertView.findViewById(R.id.tv_address);
holder.pairBtn = (Button) convertView.findViewById(R.id.btn_pair);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
BluetoothDevice device = mData.get(position);
holder.nameTv.setText(device.getName());
holder.addressTv.setText(device.getAddress());
holder.pairBtn.setText((device.getBondState() == BluetoothDevice.BOND_BONDED) ? "Unpair" : "Pair");
holder.pairBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mListener != null) {
mListener.onPairButtonClick(position);
}
}
});
return convertView;
}
static class ViewHolder {
TextView nameTv;
TextView addressTv;
TextView pairBtn;
}
public interface OnPairButtonClickListener {
public abstract void onPairButtonClick(int position);
}
}
in an article i studied about this issue and find out that with this code :
if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(context,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
1);
i can make the application to support phones with android more than 6 so i can discover all nearby devices and pair with them,
The issue is, i don't know where should i exactly use this code..
i would really appreciate if you could tell me where to use it within the codes i showed here.
or simply tell me how to overcome this problem with any other code you may know.
In your AndroidManifest.xml file add this:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Then, instead of calling registerReceiver call this function:
private tryRegisterReceiver() {
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Here, permission is not granted
// after calling requestPermissions, the result must be treated in onRequestPermissionResult
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
1000); // 100 or other desired code
} else {
// Permission has already been granted
// continue registering your receiver
registerReceiver();
}
}
To treat the result of the permission request
#Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] grantResults) {
switch (requestCode) {
case 1000: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted
// continue registering your receiver
registerReceiver();
} else {
// permission denied
// show a message or finish your activity
}
return;
}
// other 'case' for other permissions if needed
}
}

App is not responding after running this activity

New Activity UI load but does not respond, After running onStop() which trigger submit()
List View with the checkbox is bound by a custom adapter. On touch of the Submit button, an intent is triggered which takes me to HomeActivity and onStop() method is triggered which in return call submit method. All submit method is created under a new thread which interfere with UI.
package com.example.cadur.teacher;
public class Attendace extends AppCompatActivity {
DatabaseReference dref;
ArrayList<String> list=new ArrayList<>();
ArrayList<DeatailAttandance> deatailAttandances;
private MyListAdapter myListAdapter;
private ProgressDialog pb;
String year,branch,subject,emailId,pre,abs,rollno,file_name,dat,dat1,roll_str,rollno_present="",rollno_absent="";
int pre_int,abs_int;
ListView listview;
FirebaseDatabase database;
DatabaseReference myRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sp=getSharedPreferences("login",MODE_PRIVATE);
final String s=sp.getString("Password","");
final String s1=sp.getString("username","");
year=sp.getString("Year","");
branch=sp.getString("Branch","");
subject=sp.getString("Subject","");
final String attend="Attandence";
emailId=sp.getString("emailId","");
if (s!=null&&s!="" && s1!=null&&s1!="") {
setContentView(R.layout.activity_attendace);
deatailAttandances=new ArrayList<>();
listview = findViewById(R.id.list);
TextView detail=findViewById(R.id.lay);
detail.setText(year+" "+branch+" "+" "+subject);
pb =new ProgressDialog(Attendace.this);
pb.setTitle("Connecting Database");
pb.setMessage("Please Wait....");
pb.setCancelable(false);
pb.show();
database=FirebaseDatabase.getInstance();
myRef=database.getReference(year+"/"+branch);
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds:dataSnapshot.getChildren()) {
try {
abs = ds.child("Attandence").child(subject).child("Absent").getValue().toString();
pre = ds.child("Attandence").child(subject).child("Present").getValue().toString();
rollno = ds.getKey().toString();
deatailAttandances.add(new DeatailAttandance(rollno,pre,abs));
myListAdapter=new MyListAdapter(Attendace.this,deatailAttandances);
listview.setAdapter(myListAdapter);
pb.dismiss();
}catch (NullPointerException e){
pb.dismiss();
Intent intent=new Intent(Attendace.this, Login.class);
startActivity(intent);
finish();
}
}
count();
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
}
});
Button selectAll=findViewById(R.id.selectall);
selectAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myListAdapter.setCheck();
count();
}
});
Button submit_attan=findViewById(R.id.submit_attan);
submit_attan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent =new Intent(Attendace.this,HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
});
Button count=findViewById(R.id.count);
count.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View parentView = null;
int counter=0;
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
counter++;
}
}
Toast.makeText(Attendace.this,""+counter,Toast.LENGTH_SHORT).show();
}
});
}else{
SharedPreferences.Editor e = sp.edit();
e.putString("Password", "");
e.putString("username", "");
e.commit();
Intent i=new Intent(Attendace.this,MainActivity.class);
startActivity(i);
finish();
}
}
#Override
protected void onStop() {
Attendace.this.runOnUiThread(new Runnable() {
#Override
public void run() {
submit();
}
});
finish();
super.onStop();
}
public void submit(){
View parentView = null;
final Calendar calendar = Calendar.getInstance();
dat=new SimpleDateFormat("dd_MMM_hh:mm").format(calendar.getTime());
dat1=new SimpleDateFormat("dd MM yy").format(calendar.getTime());
file_name=year+"_"+branch+"_"+dat;
rollno_present=rollno_present+""+year+" "+branch+" "+subject+"\n "+dat+"\n\nList of present Students\n";
rollno_absent=rollno_absent+"\n List of absent Students\n";
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
roll_str = ((TextView) parentView.findViewById(R.id.text1)).getText().toString();
String pre_str = ((TextView) parentView.findViewById(R.id.text22)).getText().toString();
String abs_str = ((TextView) parentView.findViewById(R.id.text33)).getText().toString();
pre_int=Integer.parseInt(pre_str);
abs_int=Integer.parseInt(abs_str);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
pre_int++;
myRef.child(roll_str).child("Attandence").child(subject).child("Present").setValue(""+pre_int);
myRef.child(roll_str).child("Attandence").child(subject).child("Date").child(dat1).setValue("P");
rollno_present=rollno_present+"\n"+roll_str+"\n";
}else{
abs_int++;
myRef.child(roll_str).child("Attandence").child(subject).child("Absent").setValue(""+abs_int);
myRef.child(roll_str).child("Attandence").child(subject).child("Date").child(dat1).setValue("A");
rollno_absent=rollno_absent+"\n"+roll_str+"\n";
}
}
// Toast.makeText(Attendace.this,"Attendance Updated Successfully",Toast.LENGTH_SHORT).show();
AsyncTask.execute(new Runnable() {
#Override
public void run() {
generateNoteOnSD(Attendace.this,file_name,rollno_present+""+rollno_absent);
}
});
}
public void count(){
View parentView = null;
int counter=0;
for (int i = 0; i < listview.getCount(); i++) {
parentView = getViewByPosition(i, listview);
CheckBox checkBox=parentView.findViewById(R.id.ch);
if(checkBox.isChecked()){
counter++;
}
}
Toast.makeText(Attendace.this,""+counter,Toast.LENGTH_SHORT).show();
}
private View getViewByPosition(int pos, ListView listview1) {
final int firstListItemPosition = listview1.getFirstVisiblePosition();
final int lastListItemPosition = firstListItemPosition + listview1.getChildCount() - 1;
if (pos < firstListItemPosition || pos > lastListItemPosition) {
return listview1.getAdapter().getView(pos, null, listview1);
} else {
final int childIndex = pos - firstListItemPosition;
return listview1.getChildAt(childIndex);
}
}
public void generateNoteOnSD(Context context, String sFileName, String sBody) {
try
{
File root = new File(Environment.getExternalStorageDirectory(),year+"_"+branch+"_Attendance");
if (!root.exists())
{
root.mkdirs();
}
File gpxfile = new File(root, file_name+".doc");
FileWriter writer = new FileWriter(gpxfile,true);
writer.append(sBody+"\n");
writer.flush();
writer.close();
// Toast.makeText(Attendace.this,"File Generated",Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Just use
submit();
instead of using
Attendace.this.runOnUiThread(new Runnable() {
#Override
public void run() {
submit();
}
});
and remove finish()

Android Exoplayer save state

Hi I am using ExoPlayer to display video content in my VideoActivity. I am using three variables to save state defined in official docs: playbackPosition,currentWindow, playWhenReady
I am displaying video in full screen when device is in landscape mode so i have 2 layouts one for portrait mode and one for landscape mode:
This is the code for my VideoActivity and I have checked values are properly saved and are properly retrieved:
Video starts from starting when I rotate the device and not from saved position.
public class VideoActivity extends AppCompatActivity {
private SimpleExoPlayerView playerView;
private ExoPlayer player;
private int position;
private ArrayList<RecipeStep> steps;
private boolean playWhenReady;
private int currentWindow;
private long playbackPosition;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if(savedInstanceState == null){
playWhenReady = true;
currentWindow = 0;
playbackPosition = 0;
}else {
playWhenReady = savedInstanceState.getBoolean("playWhenReady");
currentWindow = savedInstanceState.getInt("currentWindow");
playbackPosition = savedInstanceState.getLong("playBackPosition");
}
if(getIntent().getExtras() != null) {
position = getIntent().getIntExtra("position", 0);
steps = getIntent().getParcelableArrayListExtra("steps");
}
playerView = findViewById(R.id.video_view);
if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
setStepTexts(position);
}
private void setStepTexts(int pos){
((TextView) findViewById(R.id.step_short_description)).setText(steps.get(pos-1).getShort_description());
((TextView) findViewById(R.id.step_description)).setText(steps.get(pos-1).getDescription());
}
private void initializePayer(){
player = ExoPlayerFactory.newSimpleInstance(
new DefaultRenderersFactory(this),
new DefaultTrackSelector(), new DefaultLoadControl());
playerView.setPlayer(player);
player.setPlayWhenReady(playWhenReady);
player.seekTo(currentWindow, playbackPosition);
passVideoUri(position);
}
private void passVideoUri(int pos){
Uri uri = Uri.parse(steps.get(pos-1).getVideo_url());
MediaSource mediaSource = buildMediaSource(uri);
player.prepare(mediaSource, true, false);
}
private MediaSource buildMediaSource(Uri uri){
return new ExtractorMediaSource.Factory(
new DefaultHttpDataSourceFactory("exoplayer-codelab")).createMediaSource(uri);
}
#Override
protected void onStart() {
super.onStart();
initializePayer();
}
#Override
protected void onStop() {
super.onStop();
releasePlayer();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
playbackPosition = player.getCurrentPosition();
currentWindow = player.getCurrentWindowIndex();
playWhenReady = player.getPlayWhenReady();
outState.putBoolean("playWhenReady", playWhenReady);
outState.putInt("currentWindow", currentWindow);
outState.putLong("playBackPosition", playbackPosition);
super.onSaveInstanceState(outState);
}
public void previous(View view){
if(position > 1) {
position--;
setStepTexts(position);
passVideoUri(position);
}
}
public void next(View view){
if(position < steps.size()) {
position++;
setStepTexts(position);
passVideoUri(position);
}
}
private void releasePlayer(){
playbackPosition = player.getCurrentPosition();
currentWindow = player.getCurrentWindowIndex();
playWhenReady = player.getPlayWhenReady();
player.release();
player = null;
}
}
Please have a look and see what I am doing wrong.
First you need to prepare the player and then you can seek to desired place. So your code would be like
passVideoUri(position);
playerView.setPlayer(player);
player.setPlayWhenReady(playWhenReady);
player.seekTo(currentWindow, playbackPosition);

I want to smiley providing app to whatsapp

I'm looking to create an app to whatsapp in which i need to launch a window with smileyset (like chathead in facebook messenger) .I did it but when i opened whatsapp conversation a small button of smiley set will displayed and it wont disappear when I close the whatsapp.
how i can implement this?
this is the service which uses for input smilies
public class SmileyInputService extends Service {
private WindowManager windowManager;
private List<View> chatHeads;
int f=0;
private LayoutInflater inflater;
#Override
public void onCreate() {
super.onCreate();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
inflater = LayoutInflater.from(this);
chatHeads = new ArrayList<View>();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_PHONE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT);
if(chatHeads.isEmpty()) {
final View chatHead = inflater.inflate(R.layout.service_smile_head, null);
chatHead.findViewById(R.id.btn_dismiss).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
removeChatHead(chatHead);
}
});
chatHead.findViewById(R.id.txt_title).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(f==0) {
chatHead.findViewById(R.id.smilieylisting).setVisibility(LinearLayout.VISIBLE);
f=1;
}
else {
chatHead.findViewById(R.id.smilieylisting).setVisibility(LinearLayout.GONE);
f=0;
}} };
chatHead.findViewById(R.id.happyhead).setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onClick(View view) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label","[happy]");
clipboard.setPrimaryClip(clip);
}
});
chatHead.findViewById(R.id.kisshead).setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onClick(View view) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label","[kiss]");
clipboard.setPrimaryClip(clip);
}
});
params.gravity=Gravity.LEFT|Gravity.TOP;
addChatHead(chatHead, params);
}
return super.onStartCommand(intent, flags, startId);
}
public void addChatHead(View chatHead, WindowManager.LayoutParams params) {
chatHeads.add(chatHead);
windowManager.addView(chatHead, params);
}
public void removeChatHead(View chatHead) {
chatHeads.remove(chatHead);
windowManager.removeView(chatHead);
}
#Override
public void onDestroy() {
super.onDestroy();
for (View chatHead : chatHeads) {
removeChatHead(chatHead);
}
}
}
here is my accessibility service for listening event
Public class ListeningSmileyService extends AccessibilityService {
AccessibilityServiceInfo info = new AccessibilityServiceInfo();
public static String currentsmiley;
#Override
public void onServiceConnected() {
info.eventTypes = AccessibilityEvent.TYPE_VIEW_CLICKED| AccessibilityEvent.TYPE_VIEW_FOCUSED| AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED |AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED;
info.packageNames = new String[]
{"com.whatsapp"};
info.feedbackType = AccessibilityServiceInfo.FEEDBACK_ALL_MASK;
info.notificationTimeout = 100;
this.setServiceInfo(info);
}
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
Log.i("event!","clix");
final int eventType = event.getEventType();
String eventText = null;
switch(eventType) {
case AccessibilityEvent.TYPE_VIEW_CLICKED:
if(!event.getClassName().equals("android.widget.EditText"))
stopService(new Intent(getApplicationContext(),SmileyInputService.class));
eventText = "Clix: ";
break;
case AccessibilityEvent.TYPE_VIEW_FOCUSED |AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED:
stopService(new Intent(getApplicationContext(),SmileyInputService.class));
eventText = "Focused: ";
break;
case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED:
stopService(new Intent(getApplicationContext(),SmileyInputService.class));
break;
}
if(event.getClassName().equals("android.widget.EditText")){
Log.i("sha","log");
Intent i=new Intent(getApplicationContext(),SmileyInputService.class);
startService(i);
}
}
}

Categories

Resources