I have already scanned all of the related questons&answers here, but I still couldn't find the solution.
the service class file:
public class otser extends Service {
private WindowManager windowManager;
private ImageView chatHead;
#Override public IBinder onBind(Intent intent) {
return null;
}
#Override public void onCreate() {
super.onCreate();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
chatHead = new ImageView(this);
chatHead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
FileObserver observer = new FileObserver(android.os.Environment.getExternalStorageDirectory().toString() + "/Pictures/Screenshots") {
#Override
public void onEvent(int event, String file) {
event &= FileObserver.ALL_EVENTS;
if(event == FileObserver.CREATE){
Toast.makeText(getApplicationContext(), "screenshot taken",
Toast.LENGTH_LONG).show();
}
}
};
observer.startWatching(); // start the observer
Toast.makeText(getApplicationContext(), "service: OK",
Toast.LENGTH_SHORT).show();
}}
According to other posts, I double checked the path, via creating a file programatically, it does exist, and correct.
The Activity class:
public class Home extends Activity {
Button showChatHead;
Button stopService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
showChatHead = (Button) findViewById(R.id.gomb);
stopService= (Button) findViewById(R.id.gomb2);
showChatHead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), ChatHeadService.class);
startService(i);
}
});
stopService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), ChatHeadService.class);
stopService(i);
}
});
}}
The service class linked well, the last Toast message pops up, as a conclusion only the observer is being skipped.
Any ideas?
Thanks in advance!
newer release:
FileObserver fileObserver = new FileObserver(android.os.Environment.getExternalStorageDirectory().toString() + "/Pictures/Screenshots") {
#Override
public void onEvent(int event, String path) {
Toast.makeText(getApplicationContext(), "method entered", Toast.LENGTH_SHORT).show();
if (event == FileObserver.CREATE) {
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "File created", Toast.LENGTH_SHORT).show();
}
});
}
}
};
fileObserver.startWatching();
The onEvent method is not entered, the "method entered" Toast didn't appear.
in documentation of the onEvent-Method is mentioned, that it will run at another thread and you should consider this. using a handler, the Toast message should appear, like this:
private Handler handler = new Handler();
#Override
public void onCreate() {
fileObserver = new FileObserver("path") {
#Override
public void onEvent(int event, String path) {
if (event == FileObserver.CREATE) {
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(FileWatcher.this, "File created", Toast.LENGTH_SHORT).show();
}
});
}
}
};
fileObserver.startWatching();
Related
hello i have created the webview in mail activity of the android studio and now i am in scanner activity and when the APP scans any QR code having the link it just writs the link but what i want to do is to open the link in the web view already created in mail activity.
let me place my scanner file here
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scanner);
scannView = findViewById(R.id.scannerView);
codeScanner = new CodeScanner(this,scannView);
resultData = findViewById(R.id.resultsOfQr);
codeScanner.setDecodeCallback(new DecodeCallback() {
#Override
public void onDecoded(#NonNull final Result result) {
runOnUiThread(new Runnable() {
#Override
public void run() {
resultData.setText(result.getText());
// Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(result.getText()));
// startActivity(browserIntent);
Intent intent = new Intent(getBaseContext(), MainActivity.class);
intent.putExtra("myurl1", result.getText());
startActivity(intent);
}
});
}
});
scannView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
codeScanner.startPreview();
}
});
}
scannView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
codeScanner.startPreview();
}
});
}
WEBVIEW in Mailactivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scanBtn = findViewById(R.id.scanBtn);
MywebView = (WebView) findViewById(R.id.view2);
WebSettings webSettings = MywebView.getSettings();
webSettings.setJavaScriptEnabled(true);
MywebView.loadUrl("https://google.com/APP/");
MywebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("tel:")) {
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(url));
startActivity(intent);
return true;
}else{
return false;
}
}
});
scanBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),Scanner.class));
}
});
String myrul = getIntent().getStringExtra("myurl1");
runOnUiThread(new Runnable() {
#Override
public void run() {
MywebView.loadUrl(myrul);
}
});
}
Any idea how can i do this, any help is appreciated.
Thankx
In you CodeScanner Callback Load the WebView
runOnUiThread(new Runnable() {
#Override
public void run() {
resultData.setText(result.getText());
MywebView.loadUrl(result.getText());
}
});
Actually i have 2 activities , in the main activity i am displaying all the songs using recycler view and setup an onClickListner on it, and when someone taps on it , it launches a new activity(MediaPlayer Activity) and start playing the song along with media controls like (paly, pause and seekBar).
But when i get back to the main activity and click on a button (which basically takes to the MediaPlayer activity again) all the mediaPlayer and seekBar progress are gone also the (play, pause, next and previous buttons) are not responding to the clicks.
This is from where i am starting the MediaPlayer activity :
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.Song.setText(mData.get(position).title);
holder.Artist.setText(mData.get(position).artist);
Glide.with(mcontext).load(mData.get(position).imagePath).
placeholder(R.drawable.unknown_art).into(holder.PhotoId);
holder.Options.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mcontext, "You clicked on options", Toast.LENGTH_SHORT).show();
}
});
holder.RL.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mcontext, MediaPlayerActivity.class);
intent.putExtra("songPosition",position);
mcontext.startActivity(intent);
}
});
These are the codes in the MediaPlayerActivity :
public class MediaPlayerActivity extends AppCompatActivity {
static MediaPlayer mediaPlayer=null;
static int pos=0;
SeekBar seekBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media_player);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Intent intent = getIntent();
pos = intent.getIntExtra("songPosition",pos);
seekBar = (SeekBar)findViewById(R.id.seekBar);
Button next = (Button)findViewById(R.id.button_1);
Button previous = (Button)findViewById(R.id.button_2);
final Button play_pause = (Button)findViewById(R.id.button_3);
final TextView info = (TextView)findViewById(R.id.songInfo);
info.setText(VerticalRecyclerViewAdapter.mData.get(pos).title);
if(mediaPlayer!=null&&mediaPlayer.isPlaying()){
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
}
playMedia(pos);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
playMedia(++pos);
info.setText(VerticalRecyclerViewAdapter.mData.get(pos).title);
}catch (IndexOutOfBoundsException e){
Toast.makeText(MediaPlayerActivity.this,"Already the last song!!!",Toast.LENGTH_SHORT).show();
}
}
});
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
playMedia(--pos);
info.setText(VerticalRecyclerViewAdapter.mData.get(pos).title);
}catch (IndexOutOfBoundsException e){
Toast.makeText(MediaPlayerActivity.this,"Already the first song!!!",Toast.LENGTH_SHORT).show();
}
}
});
play_pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mediaPlayer!=null&&mediaPlayer.isPlaying()){
play_pause.setText(R.string.mp_play);
mediaPlayer.pause();
}
else{
play_pause.setText(R.string.mp_Pause);
mediaPlayer.start();
}
}
});
}
public void playMedia(int pos){
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(VerticalRecyclerViewAdapter.mData.get(pos).songPath);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
seekBar.setProgress(0);
seekBar.setMax(mp.getDuration());
mediaPlayer.start();
}
});
} catch (IOException e) {
e.printStackTrace();
}
setSeekbarProgress();
onSeekbarChange();
playNext();
}
public void playNext(){
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
try {
mediaPlayer.release();
playMedia(++MediaPlayerActivity.pos);
}catch (IndexOutOfBoundsException e){
Toast.makeText(MediaPlayerActivity.this, "Already the last song", Toast.LENGTH_SHORT).show();
}
}
});
}
public void setSeekbarProgress(){
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
try {
if (mediaPlayer != null) {
seekBar.setProgress(mediaPlayer.getCurrentPosition());
}
}
catch (RuntimeException e){
Log.i("CRASH",""+e.getMessage());
}
}
},0,1000);
}
public void onSeekbarChange(){
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
if(b) {
mediaPlayer.seekTo(i);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
}
And this is where from i wanted to go back to the MediaPlayer Activity (on button click ) :
mFloatingToolbar.setClickListener(new FloatingToolbar.ItemClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.music:
Intent intent = new Intent(getActivity(),MediaPlayerActivity.class);
startActivity(intent);
break;
case R.id.pause :
break;
case R.id.next :
Toast.makeText(getContext(), "Next", Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(getContext(), "Back", Toast.LENGTH_SHORT).show();
verticalRecyclerViewAdapter.notifyDataSetChanged();
break;
}
}
#Override
public void onItemLongClick(MenuItem item) {
}
});
I am an absolute beginner working on my first android app. I am working on an audio stream app and i implemented the mediaPlayer inside a service. There is a play-pause button that toggles if bound or not. The issue i have is that when isPlaying, and i change the screen orientation, though the service continues, the activity is recreated which makes the play button appear rather than the pause button. I know for me to retain the pause button, i need to override two methods - onSaveInstanceState and onRestoreInstanceState but i dont know the right logic to use in order to retain mainActivity's state.
Pls help me because the examples i saw didnt solve my problem.
This is my main activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//.......
if(savedInstanceState != null) {
boolean isPlaying = savedInstanceState.getBoolean("isPlaying");
if(!isPlaying){
imageButton2.setImageResource(R.drawable.stop);
} else {
imageButton2.setImageResource(R.drawable.play);
}
}
#Override
protected void onStart() {
// bind to the radio service
Intent intent = new Intent(this, RadioService.class);
startService(intent);
bindService(intent, mConnection, BIND_AUTO_CREATE);
super.onStart();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onStop() {
// unbind the radio
// service
if (boundToRadioService) {
unbindService(mConnection);
boundToRadioService = false;
}
super.onStop();
}
#Override
protected void onDestroy() {
radioService.hideNotification();
if (boundToRadioService) {
unbindService(mConnection);
boundToRadioService = false;
}
super.onDestroy();
}
public void setupMediaPlayer(View view) {
if (boundToRadioService) {
boundToRadioService = false;
imageButton2.setImageResource(R.drawable.stop);
radioService.play();
} else {
boundToRadioService = true;
imageButton2.setImageResource(R.drawable.play);
radioService.pause();
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean("isPlaying", boundToRadioService);
super.onSaveInstanceState(outState);
}
}
This is my Service
// Binder given to clients
private final IBinder mBinder = new RadioBinder();
}
public void pause() {
audioManager.abandonAudioFocus(audioFocusChangeListener);
unregisterReceiver(audioBecomingNoisy);
mediaPlayer.pause();
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(this, "Oops! Error Occured, Check your network connection", Toast.LENGTH_SHORT).show();
mediaPlayer.reset();
return false;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
#Override
public void onPrepared(MediaPlayer mp) {
{
mp.start();
}
}
public class RadioBinder extends Binder {
RadioService getService() {
// Return this instance of RadioBinder so clients can call public methods
return RadioService.this;
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "onBind: ");
return mBinder;
}
public void play() {
registerReceiver(audioBecomingNoisy, noisyIntentFilter);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
new PlayerTask().execute(stream);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.reset();
showNotification();
Toast.makeText(this, "loading... please wait", Toast.LENGTH_LONG).show();
Log.i(TAG, "onCreate, Thread name " + Thread.currentThread().getName());
}
class PlayerTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... strings) {
try {
mediaPlayer.setDataSource(stream);
mediaPlayer.prepareAsync();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
}
return prepared;
}
}
try this,
public class MainActivity extends AppCompatActivity {
private boolean boundToRadioService = false;
private ImageButton imageButton2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageButton2 = (ImageButton) findViewById(R.id.my_button);
if(savedInstanceState != null){
boundToRadioService = savedInstanceState.getBoolean("isPlaying", false);
if(boundToRadioService){
imageButton2.setImageResource(R.drawable.stop);
} else {
imageButton2.setImageResource(R.drawable.play);
}
} else {
// bind to the radio service
Intent intent = new Intent(this, RadioService.class);
startService(intent);
bindService(intent, mConnection, BIND_AUTO_CREATE);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putBoolean("isPlaying", boundToRadioService);
super.onSaveInstanceState(outState);
}
public void setupMediaPlayer(View view){
if (boundToRadioService) {
boundToRadioService = false;
imageButton2.setImageResource(R.drawable.play);
radioService.pause();
} else {
boundToRadioService = true;
imageButton2.setImageResource(R.drawable.stop);
radioService.play();
}
}
}
and add android:src="#drawable/play" to the imagebutton in your xml file.
I have a method that takes lat/lng from mysql and puts the markers on the map.
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
myMethod();
}
});
Everything in this way works.
But when i try to put this method with ProgressDialog markers do not appear. After push the button i see only "loading..." and "Done".
This is a way that does not work:
I
pg = new ProgressDialog(this);
pg.setMessage("wait...");
II
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
pg.show();
new BackgroundJob().execute();
Toast.makeText(MapsActivity.this, "loading...", Toast.LENGTH_SHORT).show();
}
});
III
private class BackgroundJob extends AsyncTask<Void, Void, Void>
{
#Override
protected Void doInBackground(Void... params) {
myMethod();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
Toast.makeText(MapsActivity.this, "Done", Toast.LENGTH_SHORT).show();
pg.cancel();
}
}
what is wrong here?
The following code keeps throwing null pointer exception...
public class MainActivity extends Activity implements OnClickListener{
Button but;
Button but2;
LocalBinder binder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
but = (Button) findViewById(R.id.button1);
but.setOnClickListener(this);
but = (Button) findViewById(R.id.button2);
}
ServiceConnection connection = new ServiceConnection(){
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
Log.d("D1", "connecting");
binder = (LocalBinder) arg1;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
Log.d("D1", "disconnecting");
}
};
public static class ServiceTest extends Service{
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return new LocalBinder();
}
public class LocalBinder extends Binder{
public void toast(){
Toast.makeText(getApplicationContext(), "hope this works", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), ServiceTest.LocalBinder.class);
bindService(i, connection, Context.BIND_AUTO_CREATE);
Toast.makeText(getApplicationContext(), "bind completed", Toast.LENGTH_LONG).show();
}
public void binderMethod(View v){
binder.toast();
}
}
I guess that the reason is that onServiceConnected does not execute, which causes binder to stay null. (The but button binds the service to the activity while but2 executes binder.toast(); - the exception is thrown when but2 is pressed)
Basicly the question is : why doesnt onServiceConnected execute ?
I think, that intent should lead to service, not binder in service: Intent i = new Intent(getApplicationContext(), ServiceTest.class);