I am newbie so please forgive me for anything wrong that I am doing or if I am asking the question in the wrong way.
I recently created a simple media player on android studio and used Java Service to play the media when I closed the app and it works fine. Now I have created a simple web browser app using WebView and I want to use the same "Java Service" to keep my web browser app running even when it is minimized but I have no idea how to convert the media player code to use on the web browser app. I have researched a lot and nobody else seems to want to create a browser that keeps running in the background. Please can you assist me in solving this?
Because I am new to Java, it is difficult for me to try and convert the code from media player to web browser
So here is my media player code:
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button start, stop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.buttonStartService);
stop = (Button) findViewById(R.id.buttonStopService);
start.setOnClickListener(this);
stop.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view == start){
startService(new Intent(this, MyService.class));
}else if(view == stop){
stopService(new Intent(this, MyService.class));
}
}
}
MyService.java
public class MyService extends Service {
private MediaPlayer player;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
player = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
player.setLooping(true);
player.start();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
player.stop();
}
}
Here is my MainActivity for the Webbrowser that I have created:
public class MainActivity extends AppCompatActivity {
WebView browser;
EditText link;
Button btn_visit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
browser = (WebView) findViewById(R.id.webview);
link = (EditText) findViewById(R.id.editTextLink);
btn_visit = (Button) findViewById(R.id.btn_view);
browser.setWebViewClient(new myWebViewClient());
btn_visit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String url = link.getText().toString();
browser.getSettings().setLoadsImagesAutomatically(true);
browser.getSettings().setJavaScriptEnabled(true);
browser.loadUrl(url);
}
});
}
private class myWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
```
So now I need to create another MyService that will allow the webbrowser to run in the
background but dont know how to go about it:
```
public class MyService extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
}
#Override
public void onDestroy() {
}
}
As I said, there no errors that I am getting on the media player app. I just want to be able to use the same code on the internet browser app but don't know how to convert it.
Related
I have created an app with android webview. It loads google chrome website. How can I restrict it to open other links in the same browser app and not go to phone's default browser? Also with the below code I am able to open and download random pdf by search on google(webview). I need to be able to open in same webview and also be able to download pdf in the same webview app. How?
public class WebViewPage extends AppCompatActivity {
WebView webView;
Button closeweb;
WebViewClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view_page);
webView =findViewById(R.id.webview);
closeweb = findViewById(R.id.closeweb);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
WebViewClientImpl webViewClient = new WebViewClientImpl(this);
webView.setWebViewClient(webViewClient);
webView.loadUrl("https://www.google.in");
closeweb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(WebViewPage.this, HomePage.class);
startActivity(intent);
}
});
}
#Override
public void onBackPressed() {
}
}
WebViewClientImpl.class
public class WebViewClientImpl extends WebViewClient {
private Activity activity = null;
public WebViewClientImpl(Activity activity) {
this.activity = activity;
}
#Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
if(url.indexOf("https://www.google.in") > -1 ) return false;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
activity.startActivity(intent);
return true;
}
}
I want to play music in the background of my application:
public class BackgroundSoundService extends Service {
MediaPlayer mediaPlayer;
#Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(this, R.raw.airport_lounge);
mediaPlayer.setLooping(true);
mediaPlayer.setVolume(100,100);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mediaPlayer.start();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
mediaPlayer.release();
}
#Override
public void onLowMemory() {
super.onLowMemory();
}
#Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Then in my MainActivity :
public static Intent musicIntent;
//Start music service
musicIntent = new Intent(this, BackgroundSoundService.class);
startService(musicIntent);
#Override
protected void onPause() {
super.onPause();
stopService(musicIntent);
}
#Override
protected void onResume() {
super.onResume();
startService(musicIntent);
}
I stop it in my onPause the service because if the user switches the Application and doesn't close it the music would continue to play. The problem is that when we change Activity the onPaused is also called but I want the music to continue playing through the entire application.
So in my another Activity :
//start music
startService(MainActivity.musicIntent);
But the music restarts and it's not very good to hear. Any solutions?
You can use ActivityLifecycleCallbacks in your application class.
public class MusicApplication extends Application implements ActivityLifecycleCallbacks {
int activitiesOnTop = 0;
#Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(this);
}
#Override
public void onActivityResumed(Activity activity) {
// one of application activities is visible
activitiesOnTop ++;
}
#Override
public void onActivityStopped(Activity activity) {
activitiesOnTop --;
if(activitiesOnTop == 0){
// none of activities are on foreground
}
}
}
There are other solutions mentioned in the How to check if activity is in foreground or in visible background?.
It depends on the application structure, for example, if you build some tab or navigationDrawer based navigation, you will likely build some fragments and your MainActivity will be your only activity, so it's onPause method will only be called if user closes your application. But this scenario won't hold as your application grows (unless it's quite simple).
So another approach is to launch your service in your application instance, in case you use it.
I want to play my ringtone in my android app in background(for version O and above) even if application is closed and stop playing if i stop from my app.
I used service in my application but the music is stopped when i closed my app.
How can i achieve this ??
Here is my Service class:
public class MyService extends Service {
MediaPlayer player;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
player=MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
player.setLooping(true);
player.setVolume(100,100);
player.start();
player.start();
return START_STICKY;
}
#Override
public void onDestroy() {
player.stop();
player.release();
super.onDestroy();
}
}
and here is my MainActivity class from where I'm starting and stopping the service:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void Start(View view) {
startService(new Intent(this,MyService.class));
}
public void Stop(View v){
stopService(new Intent(this,MyService.class));
}
public void go(View view) {
startActivity(new Intent(MainActivity.this,NotActivity.class ));
}
}
From the code that you submitted, you have never invoked the service of the player. call the functions that you have created in oncreate method that should do the trick.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//button objects
private Button buttonStart;
private Button buttonStop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//getting buttons from xml
buttonStart = (Button) findViewById(R.id.buttonStart);
buttonStop = (Button) findViewById(R.id.buttonStop);
//attaching onclicklistener to buttons
buttonStart.setOnClickListener(this);
buttonStop.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view == buttonStart) {
//starting service
startService(new Intent(this, MyService.class));
} else if (view == buttonStop) {
//stopping service
stopService(new Intent(this, MyService.class));
}
}
}
note: Create two buttons to start and stop the service
For more info check out: https://www.simplifiedcoding.net/android-service-example/
I'm developing a game, I have used services to play music on all activities.
I want to stop the music when we hit the home key, it shouldn't stop playing music when moving from one activity to another.
public class backService extends Service {
private MediaPlayer mp;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
mp.stop();
mp.release();
}
#Override
public void onCreate() {
super.onCreate();
mp = MediaPlayer.create(this, R.raw.all);
mp.setLooping(true);
mp.start();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
and my main activity file
public class Home extends AppCompatActivity {
private AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
hide();
setContentView(R.layout.activity_home);
Intent i = new Intent(this, backService.class);
adv();
}
#Override
protected void onResume(){
super.onResume();
Intent i = new Intent(this, backService.class);
startService(i);
}
#Override
protected void onStop() {
super.onStop();
Intent i = new Intent(this, backService.class);
stopService(i);
}
#Override
protected void onDestroy(){
super.onDestroy();
Intent i = new Intent(this, backService.class);
stopService(i);
}
}
How can I stop the music when I hit the home key and keep playing the music when we switch between other activities
TIA
Please remove the stopService(i) inside onStop() method in Activity coz whenever you are going one Activity to Another Activity then onStop() method will be called, that's why your service is killing.
If you want to pause or stop music while press home button then implements ComponentCallbacks2 interface to Activity like this
#Override
public void onTrimMemory(final int level) {
if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
if(mService != null){
mService.pauseMusic();
}
}
}
Try to stop the service in
#Override
public void onPause()
{
super.onPause();
// Check if app is in foreground
if(!isAppOnForeground(context))
{
stop music here
}
}
below is the method to check if the app is in foreground or not . just replace your package here "your package name here";
public static boolean isAppOnForeground(Context context)
{
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses == null) {
return false;
}
final String packageName = "your package name here";
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
return true;
}
}
return false;
}
I want to implement Google Tag Manager to track the user interacts with my app, I have followed the guide from Google Docs but I faced some issues.
This is my Main Activity
public class MainActivity extends AppCompatActivity {
private static final String CONTAINER_ID = "GTM-TRFZVD5";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TagManager tagManager = TagManager.getInstance(this);
tagManager.setVerboseLoggingEnabled(true);
PendingResult<ContainerHolder> pendingResult =
tagManager.loadContainerPreferNonDefault(CONTAINER_ID, R.raw.gtm_trfzvd5);
pendingResult.setResultCallback(new ResultCallback<ContainerHolder>() {
#Override
public void onResult(#NonNull ContainerHolder containerHolder) {
ContainerHolderSingleton.setContainerHolder(containerHolder);
Container container = containerHolder.getContainer();
if(!containerHolder.getStatus().isSuccess()){
Log.e(MainActivity.class.getSimpleName(), "Failure loading container");
return;
}
ContainerLoadedCallback.registerCallbackForContainer(container);
containerHolder.setContainerAvailableListener(new ContainerLoadedCallback());
startAnotherActivity();
}
}, 2, java.util.concurrent.TimeUnit.SECONDS);
}
private void startAnotherActivity(){
Intent intent = new Intent(MainActivity.this, AnotherActivity.class);
startActivity(intent);
}
This is the Activity that user will interact
public class AnotherActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another);
Button btn = (Button) findViewById(R.id.btn);
GTMUtils.pushOpenScreenEvent(getApplicationContext(), AnotherActivity.class.getSimpleName());
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GTMUtils.pushClickButtonEvent(getApplicationContext(),
"btn");
}
});
}
And these are two methods to push the event to Google Analytics
public static void pushOpenScreenEvent(Context context, String screenName){
DataLayer dataLayer = TagManager.getInstance(context).getDataLayer();
dataLayer.push(DataLayer.mapOf("event", "openScreen", "screenName", screenName));
}
public static void pushClickButtonEvent(Context context, String btnEventName){
DataLayer dataLayer = TagManager.getInstance(context).getDataLayer();
dataLayer.push(DataLayer.mapOf("event", "videoPlay", "videoName", btnEventName));
}
I copied exactly from Google Guide but I when I ran the app, it only pushed the first event ("open screen") and the click button didn't send anything.
So did I do something wrong?