activity that plays video and exit app when video is finished - java

For the last 18 Months I have been building simple apps in android studio and I am really stuck trying to work this out so any help would be great
So far my app works great, open the app on the first activity and press the play button and the 2nd activity opens and plays the video, at the end of the video it returns back to the first activity, but I am trying to exit the app
guessing I should be able to add something like
public void onCompletion(MediaPlayer player) {
onStop();
onDestroy();
}
public class PlayVideo extends Activity {
boolean videoPlayed ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_video);
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_FULLSCREEN |
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
);
videoPlayed = true;
playvideo();
FinishVideo();
}
public void playvideo() {
VideoView videoview = (VideoView) findViewById(R.id.videoview);
Uri uri = Uri.parse("android.resource://" + getPackageName()
+ "/"+ R.raw.sound_2);
videoview.setVideoURI(uri);
videoview.start();
}
public void FinishVideo() {
VideoView videoView = (VideoView) findViewById(R.id.videoview);
videoView.setOnCompletionListener
(newMediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer player) {
//Log.i("VideoView", "onCompletion()");
//Intent intent = new Intent
(PlayVideo.this,MainActivity.class);
//startActivity(intent);
System.exit(0);
}
});
}
}
----------------------------------------------------------------------------
<RelativeLayout xmlns:android=
"http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".PlayVideo">
<VideoView
android:id="#+id/videoview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
/>
</RelativeLayout>

try this, it works for me, and you do not need to add finish(); function it will close the app if the FirstActivity is the MainActivity
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(intent);
and in Second Activity add this
videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
onBackPressed();
}
});

You have to finish() the first activity while starting the second activity,
startActivity(new Intent(FirstActivity.this, SecondActivity.class));
finish();
and when the video play is completed in the second activity you have to call onBackPressed()
videoview.setVideoURI(uri);
videoview.start();
videoview.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
onBackPressed();
}
});
and you don't have to call FinishVideo() method, you can set setOnCompletionListener in playvideo() method itself

Related

YoutubePlayer API endless loading issue

I am starting a new intent whenever a new geofence transition happens.
In GeofenceTransitionService.java:
Intent intent = new Intent(GeofenceTransitionService.this, VideoActivity.class);
intent.putExtra("videoID", videoURLS[i]);
startActivity(intent);
And I am initializing the fragment like this,
in VideoActivity.java:
public class VideoActivity extends AppCompatActivity implements YouTubePlayer.OnInitializedListener {
private String videoID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
videoID = getIntent().getStringExtra("videoID");
YouTubePlayerFragment youTubePlayerFragment = (YouTubePlayerFragment) getFragmentManager()
.findFragmentById(R.id.youtubePlayerFragment);
youTubePlayerFragment.initialize("APIKEY", this);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) {
youTubePlayer.setFullscreenControlFlags(YouTubePlayer.FULLSCREEN_FLAG_CONTROL_ORIENTATION |
YouTubePlayer.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE);
if(!wasRestored) {
youTubePlayer.cueVideo(videoID);
}
youTubePlayer.setFullscreenControlFlags(0);
youTubePlayer.setFullscreen(true);
youTubePlayer.setShowFullscreenButton(false);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult error) {
final int REQUEST_CODE = 1;
if(error.isUserRecoverableError()) {
error.getErrorDialog(this,REQUEST_CODE).show();
} else {
String errorMessage = String.format("There was an error initializing the YoutubePlayer (%1$s)", error.toString());
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
}
activity_video.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".VideoActivity">
<fragment
android:id="#+id/youtubePlayerFragment"
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</androidx.appcompat.widget.LinearLayoutCompat>
But the video will never load. It works fine on other activities though. I have checked the manifest but couldn't find anything that differentiates this activity from the other one that works. I use the same code for the other activity to initialize the other fragment.
I forgot to split the video url to get the videoID.
intent.putExtra("videoID", videoURLS[i].split("=")[1]);

How to create Settings with toolbar in android

I have a Settings Preference screen.It has a ListPreference and a CheckBoxPreference. I want to change my app's date format when I choose an item of ListPreference. Also, by the CheckBoxPreference I want to show/hide notification on the status bar. Can anyone tell what I have to do to achieve that.
Also, how can I add a toolbar to the preference screen? I am stuck here. Please help. Thanks in advance.
I am stuck here. Please help.
Thanks in advance.
MainActivity.java
public void setCurrentDateOnView() {
String dateFormat = "dd - MM - yyyy";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat, Locale.US);
tv_Current_Date.setText(simpleDateFormat.format(calendar_now.getTime()));
String short_weekday = new DateFormatSymbols().getShortWeekdays()[day_of_current_week];
tv_Current_weekday.setText(short_weekday);
til_Current_Date.setError(null);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent_settings = new Intent(this, SettingsActivity.class);
startActivity(intent_settings);
Toast.makeText(this, "You have clicked on settings action menu.", Toast.LENGTH_SHORT).show();
break;
}
return super.onOptionsItemSelected(item);
}
SettingsActivity.java
public class SettingsActivity extends PreferenceActivity
implements SharedPreferences.OnSharedPreferenceChangeListener {
NotificationManager mNotifyManager;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Display the fragment as the main content.
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean notifyEnabled = sharedPreferences.getBoolean("pref_cb_notification", true);
mNotifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (notifyEnabled) {
//Show notification
showNotification();
}
else {
//Hide notification
hideNotification();
}
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
boolean isChecked = sharedPreferences.getBoolean("pref_cb_notification", false);
if (isChecked) {
//Show notification
showNotification();
}
else {
//Hide notification
hideNotification();
}
}
public static class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener{
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
}
}
//Method to show notification
public void showNotification() {
NotificationCompat.Builder mBuilder = (NotificationCompat.Builder)
new NotificationCompat.Builder(SettingsActivity.this)
.setSmallIcon(R.drawable.ic_notifications_white_24dp)
.setContentTitle("My Application")
.setSubText("Tap to start");
Intent resultIntent = new Intent(SettingsActivity.this, MainActivity.class);
PendingIntent resultPendingIntent = PendingIntent
.getActivity(SettingsActivity.this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//System.currentTimeMillis();
mBuilder.setContentIntent(resultPendingIntent);
Notification notification = mBuilder.build();
notification.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
//notification.flags |= Notification.FLAG_AUTO_CANCEL;
mNotifyManager.notify(1, notification);
}
//Method to hide notification
public void hideNotification() {
mNotifyManager.cancel(1);
}
}
Settings image
for adding toolbar you just need to use the coordinator layout in the layout file of your activity. Preference activity has simple layout like others and you just inflate preference fragments inside a container.
add appcompact design support library to your build.gradle
compile 'com.android.support:appcompat-v7:21.0.3'
Add toolbar.xml to your layout folder
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/ColorPrimary"
android:elevation="4dp"
>
</android.support.v7.widget.Toolbar>
Then include toolbar in your activity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<include
android:id="#+id/tool_bar"
layout="#layout/tool_bar"
></include>
<TextView
android:layout_below="#+id/tool_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/TextDimTop"
android:text="#string/hello_world" />
</RelativeLayout>
then you need to set up it in your activity
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
and then by using onCreateOptionsMenu you can add settings menu on it.

SplashScreen skip on Touch event

I'm developing an android app, it has a Splash Screen that runs for 2500ms.
I want to add the functionality for a User touch screen and skip this Activity.
I could made it with a button, but for pretty objective I just want to add a screen touch listener (Don't know how.)
My SplashScreen:
public class Splash extends Activity {
// Splash screen timer
private static int SPLASH_TIME_OUT = 2500;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashactivity);
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(Splash.this, MainActivity.class));
finish();
}
}, SPLASH_TIME_OUT);
//Skip this intro
RelativeLayout root_layout = (RelativeLayout) findViewById(R.id.root_splash);
root_layout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
startActivity(new Intent(Splash.this, MainActivity.class));
finish();
return true;
}
});
}
}
My splashactivity layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/root_splash"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/splash_screen">
</RelativeLayout>
Add a full screen view named ll_root in R.layout.splashactivity,then in Splash Activity using findViewById and setOnTouchListener for ll_root.
Delete the splash screen. That's so 2007.
Add onTouchListener on Splash screen layout and call your class on the event.
Hope it will work for you
Thanks..

how can save current state of activity and reload that in any time

have 4 activity with names : main , p1 , p2 ,p3
want if user was in p1 or p2 or p3 when come out with exit button and relaunch app again in main activity with resume button can go to the same activity was .
there is my code : main activity :
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page);
Button button2=(Button)findViewById(R.id.btn2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this,p1.class);
startActivity(intent);
}
});
}
}
xml :
<Button
android:text="resume"
android:layout_width="wrap_content"
android:id="#+id/btn1"
android:layout_height="wrap_content" />
<Button
android:text="next"
android:id="#+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
activity p1:
public class p1 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.p1);
Button button = (Button) findViewById(R.id.btne);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(p1.this,p2.class);
startActivity(intent);
}
});
Button button1=(Button)findViewById(R.id.btne2);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(p1.this,MainActivity.class);
startActivity(intent);
}
});
}
}
xml:
<Button
android:text="next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btne"/>
<Button
android:text="go in main"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btne2"/>
and p2,p3 like p1 . please help if any one can
If your main activity starts all the rest then you only need to call finish(); to finish them, and your main activity will be back on top. So instead of writing for example in p1:
Intent intent=new Intent(p1.this,MainActivity.class);
startActivity(intent);
write:
p1.this.finish();
If on the other hand you want to close all the activities opened until your main activity (ie. you have MainActivity -> p1 -> p2, and you want only MainActivity to be left, p1 and p2 finished) then use this code:
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
In your MainActivity, declare a global variable resumeIntent:
public static Intent resumeIntent = null;
When you click the Resume button (in MainActivity) it should go to the previous activity, implement the click event as follows:
if (resumeIntent != null) {
startActivity(resumeIntent);
} else {
Toast.makeText(MainActivity.this, "No Intent to resume !", Toast.LENGTH_SHORT).show();
}
In those activities P1, P2 and P3, the code for Go To Main button is like below:
btnGoToMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MainActivity.resumeIntent = getIntent();
finish();
}
});
Hope it helps !

Android dialog with TextView As link

Hi guys I have a problem regarding the android dialog box.What I am trying to do is set few lines of description in a dialog box which I am able to do it fine but at last i need a link called "see more" which will redirect the user to other activity.I am very new to android and these is the first of some things what I am trying to do any help will be appreciated..my code onStart()
protected void onStart()
{
super.onStart();
/*final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.main);
dialog.setTitle("About Service One");
Button button = (Button) dialog.findViewById(R.id.button12);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
protected void onStart()
{
super.onStart();
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.main);
dialog.setTitle("About Service One");
Button button = (Button) dialog.findViewById(R.id.button12);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
TextView showMore= (TextView ) dialog.findViewById(R.id.tvShowMore);
showMore.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(getApplicationContext(),ShowMoreActivity.class);
startActivity(intent);
}
});
dialog.show();
}
And add in xml showmore TextView Which set text from string.xml
i.e <string name="show_more"><u>Show More </u></string> use this for set linkable text
main.xml
...........
<TextView
android:id="#+id/tvShowMore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/show_more"
android:textAppearance="?android:attr/textAppearanceMedium"
>
</TextView>
............
Create a custom Dialod layout>> create a text view as show more >> set OnClick Listener on it as ..
You can set the click handler in xml with these attribute:
android:onClick="onClick"
android:clickable="true"
Don't forget the clickable attribute, without it, the click handler isn't called.
dailog.xml
...
<TextView
android:id="#+id/click"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="show more"
android:textSize="55sp"
android:onClick="onClick"
android:clickable="true"/>
...
MyActivity.java
public class MyActivity extends Activity {
public void onClick(View v) {
// ... start show more activity here
}
}
OR... find the view using dialog and set OnClick Listener on it..
showmore = (TextView)dialog.findViewById(R.id.click);
showmore..setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// ... start show more activity here
}
});
Try this:
<TextView
android:id="#+id/yourId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show more"
android:onClick="showMore"
android:clickable="true"/>
Inside your activity, get that textView :
TextView showMoreView=(TextView)findViewById(R.id.yourId);
Add this showMoreView inside your text in the dialog and
Inside your activity, define the methode "showMore"
public void showMore(View view)
{
Intent intent =new Intent(YourCurrrentActivity.this,NextActivity.class);
startActivity(intent);
}
This will take you to NextActivity on clicking the "show more" text.

Categories