I am setting a repeated alarm in the Android, which fires the activity.
This activity is having two buttons: "stop" and "snooze". When I click on "snooze" alarm is postponed to 10 minutes.
But the alarm is in slider window, i.e it is in onresume state.
I want to stop the alarm completely on both the buttons.
public class RingAlarm extends Activity {
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ring_alarm);
Intent in;
in = getIntent();
String s=in.getStringExtra("habbit_id");
int col= in.getIntExtra("habbit_Color",0);
ScrollView sv = (ScrollView)findViewById(R.id.sv_ra);
if(col<0)
{
sv.setBackgroundResource(R.color.red);
}
if(col>0) {
sv.setBackgroundResource(R.color.green);
}
if(col==0)
{
sv.setBackgroundResource(R.color.yellow);
}
System.out.println("alarm string" + s);
TextView tv = (TextView)findViewById(R.id.habbit_ra);
tv.setText(s);
// mp = MediaPlayer.create(getApplicationContext(), R.raw.song1);
//mp.start();
}
public void onthecancelringclicked(View view){
//mp.stop();
int id=Process.myPid();
finish();
Process.killProcess(id);
//System.exit(0);
}
public void onthesnoozeringclicked(View view){
//mp.stop();
long l=System.currentTimeMillis();
Intent i = this.getIntent();
Random r = new Random();
int ri =r.nextInt(1000000)+64;
PendingIntent pi = PendingIntent.getActivity(this,ri,i,0 );
AlarmManager am = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP,l+600000,pi);
finish();
Process.killProcess(Process.myPid());
}
}
And my XML file is:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical"
android:background="#color/background"
>
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="#string/app_name"
android:gravity="left|center"
android:padding="7dp"
android:background="#color/user_profile"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="#+id/sv_ra">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_gravity="center"
android:id="#+id/habbit_ra"
android:text="habbit_name"/>
<AnalogClock
android:text="time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:layout_gravity="center"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="bsy your self"
android:layout_marginTop="20dp"
android:gravity="center"
android:id="#+id/habbit_message_ra"/>
</LinearLayout>
</ScrollView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_weight="0"
android:background="#color/user_profile">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="stop"
android:background="#color/user_profile"
android:onClick="onthecancelringclicked"/>
<Button
android:background="#color/user_profile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="snooze 10 min"
android:onClick="onthesnoozeringclicked"/>
</LinearLayout>
As you can see I have implemented Process.killProcess(pid) method. Still my alarm is getting saved into the navigation drawer. I want to remove the activity from everywhere.
i am using same intent for 32 alarms so i can not put the id of the pending intent to the intent as putExtra.
Hopefully this will give you an idea of how to cancel/stop the alarm:
Intent intent = new Intent(context, MyClass.class);
PendingIntent recurring = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarms = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if(active) { //If alarm is active
alarms.cancel(recurring);
recurring.cancel();
} else {
// Do something..
}
I copied it from one of my projects and it works for me.
add the following lines in the entry of the activity that is fired in the menifest file.
android:excludeFromRecents="true"
this will not let the activity go into recents and calling finish will lead to end of the activity.
Related
I'm a beginner in android app making and I'm trying to do an app for a project. I found this tutorial and I'm currently trying to put to apps together in android studio. Both are reminders apps, however the second one (the food one), the FAB is not working it register the touch but when it does it says APP keeps stopping. If anybody can help me I'll appreciated.
First Reminder .java
public class MedicineActivity extends AppCompatActivity {
#BindView(R.id.compactcalendar_view)
CompactCalendarView mCompactCalendarView;
#BindView(R.id.date_picker_text_view)
TextView datePickerTextView;
#BindView(R.id.date_picker_button)
RelativeLayout datePickerButton;
#BindView(R.id.toolbar)
Toolbar toolbar;
#BindView(R.id.collapsingToolbarLayout)
CollapsingToolbarLayout collapsingToolbarLayout;
#BindView(R.id.app_bar_layout)
AppBarLayout appBarLayout;
#BindView(R.id.contentFrame)
FrameLayout contentFrame;
#BindView(R.id.fab_add_task)
FloatingActionButton fabAddTask;
#BindView(R.id.coordinatorLayout)
CoordinatorLayout coordinatorLayout;
#BindView(R.id.date_picker_arrow)
ImageView arrow;
private MedicinePresenter presenter;
private SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd", /*Locale.getDefault()*/Locale.ENGLISH);
private boolean isExpanded = false;
public ImageButton imageButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medicine);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
imageButton = (ImageButton) findViewById(R.id.image2button);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent= new Intent(MedicineActivity.this,dashboard_screen.class);
startActivity(intent);
}
});
mCompactCalendarView.setLocale(TimeZone.getDefault(), /*Locale.getDefault()*/Locale.ENGLISH);
mCompactCalendarView.setShouldDrawDaysHeader(true);
mCompactCalendarView.setListener(new CompactCalendarView.CompactCalendarViewListener() {
#Override
public void onDayClick(Date dateClicked) {
setSubtitle(dateFormat.format(dateClicked));
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateClicked);
int day = calendar.get(Calendar.DAY_OF_WEEK);
if (isExpanded) {
ViewCompat.animate(arrow).rotation(0).start();
} else {
ViewCompat.animate(arrow).rotation(180).start();
}
isExpanded = !isExpanded;
appBarLayout.setExpanded(isExpanded, true);
presenter.reload(day);
}
#Override
public void onMonthScroll(Date firstDayOfNewMonth) {
setSubtitle(dateFormat.format(firstDayOfNewMonth));
}
});
setCurrentDate(new Date());
MedicineFragment medicineFragment = (MedicineFragment) getSupportFragmentManager().findFragmentById(R.id.contentFrame);
if (medicineFragment == null) {
medicineFragment = MedicineFragment.newInstance();
ActivityUtils.addFragmentToActivity(getSupportFragmentManager(), medicineFragment, R.id.contentFrame);
}
//Create MedicinePresenter
presenter = new MedicinePresenter(Injection.provideMedicineRepository(MedicineActivity.this), medicineFragment);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.medicine_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_stats) {
Intent intent = new Intent(this, MonthlyReportActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
public void setCurrentDate(Date date) {
setSubtitle(dateFormat.format(date));
mCompactCalendarView.setCurrentDate(date);
}
public void setSubtitle(String subtitle) {
datePickerTextView.setText(subtitle);
}
#OnClick(R.id.date_picker_button)
void onDatePickerButtonClicked() {
if (isExpanded) {
ViewCompat.animate(arrow).rotation(0).start();
} else {
ViewCompat.animate(arrow).rotation(180).start();
}
isExpanded = !isExpanded;
appBarLayout.setExpanded(isExpanded, true);
}
}
First Reminder XML File
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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:id="#+id/coordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/app_bar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:theme="#style/AppTheme.AppBarOverlay"
app:expanded="false"
app:layout_behavior="com.gautam.medicinetime.utils.ScrollingCalendarBehavior">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:id="#+id/collapsingToolbarLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:minHeight="?attr/actionBarSize"
app:contentScrim="?attr/colorPrimary"
app:titleEnabled="false"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:statusBarScrim="?attr/colorPrimaryDark">
<LinearLayout
android:id="#+id/compactcalendar_view_container"
android:layout_width="match_parent"
android:layout_height="250dp"
android:paddingTop="?attr/actionBarSize"
app:layout_collapseMode="parallax"
app:layout_collapseParallaxMultiplier="1.0">
<com.github.sundeepk.compactcalendarview.CompactCalendarView
android:id="#+id/compactcalendar_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
app:compactCalendarBackgroundColor="?attr/colorPrimary"
app:compactCalendarCurrentDayBackgroundColor="#FFC107"
app:compactCalendarCurrentSelectedDayBackgroundColor="#BBDEFB"
app:compactCalendarTextColor="#fff"
app:compactCalendarTextSize="12sp" />
</LinearLayout>
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
style="#style/ToolbarStyle"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/AppTheme.PopupOverlay">
<RelativeLayout
android:id="#+id/date_picker_button"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?android:selectableItemBackground"
android:gravity="center_vertical"
android:clickable="true"
android:focusable="true"
android:orientation="vertical">
<TextView
android:id="#+id/date_picker_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="1"
android:textStyle="bold"
android:textSize="18sp"
android:textColor="#android:color/white" />
<ImageView
android:id="#+id/date_picker_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#id/date_picker_text_view"
android:layout_toRightOf="#id/date_picker_text_view"
app:srcCompat="#drawable/ic_arrow_drop_down"
tools:ignore="ContentDescription,RtlHardcoded" />
</RelativeLayout>
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
<RelativeLayout
android:id="#+id/relativeLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#color/design_default_color_background">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="#+id/image2button"
android:layout_width="48dp"
android:layout_height="50dp"
android:background="#drawable/roundbutton"
android:src="#drawable/menu_icon"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.046"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.976" />
</androidx.constraintlayout.widget.ConstraintLayout>
</RelativeLayout>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab_add_task"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/sixteen_dp"
app:fabSize="normal"
app:layout_anchor="#+id/relativeLayout2"
app:layout_anchorGravity="end|bottom"
app:srcCompat="#drawable/ic_add" />
<FrameLayout
android:id="#+id/contentFrame"
android:layout_width="match_parent"
android:layout_height="674dp"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Second Remider .java
public class FoodActivity extends AppCompatActivity {
FloatingActionButton mCreateRem;
RecyclerView mRecyclerview;
ArrayList<Model> dataholder = new ArrayList<Model>();
//Array list to add reminders and display in recyclerview
myAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food);
mRecyclerview = (RecyclerView) findViewById(R.id.recyclerView_food);
mRecyclerview.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
mCreateRem = (FloatingActionButton) findViewById(R.id.create_reminder);
//Floating action button to change activity
mCreateRem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), FoodAddReminder.class);
startActivity(intent);
//Starts the new activity to add Reminders
}
});
Cursor cursor = new dbManager(getApplicationContext()).readallreminders();
//Cursor To Load data From the database
while (cursor.moveToNext()) {
Model model = new Model (cursor.getString(1), cursor.getString(2), cursor.getString(3));
dataholder.add(model);
}
adapter = new myAdapter(dataholder);
mRecyclerview.setAdapter(adapter);
//Binds the adapter with recyclerview
}
#Override
public void onBackPressed() {
finish();
//Makes the user to exit from the app
super.onBackPressed();
}
}
Second Reminder XML file
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".FoodActivity"
android:id="#+id/Food_Container">
<androidx.appcompat.widget.Toolbar
android:id="#+id/FoodToolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/yellow_light"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:title="What's on you firdge?" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView_food"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="8dp"
android:visibility="invisible"
app:layout_constraintBaseline_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#id/FoodToolbar"
tools:layout_editor_absoluteX="-4dp" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="No food reminder added\n + Add now"
android:textAlignment="center"
android:textSize="18dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/recyclerView_food"
app:layout_constraintStart_toStartOf="#+id/recyclerView_food"
app:layout_constraintTop_toBottomOf="#+id/FoodToolbar"
app:layout_constraintVertical_bias="0.523"
android:visibility="gone"
/>
<ImageView
android:layout_width="379dp"
android:layout_height="46dp"
android:src="#drawable/food_icon"
app:layout_constraintBottom_toTopOf="#+id/textView4"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/FoodToolbar"
app:layout_constraintVertical_bias="0.966"
android:visibility="gone"
/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/create_reminder"
android:layout_width="65dp"
android:layout_height="56dp"
android:src="#drawable/ic_baseline_add_24"
app:backgroundTint="#color/yellow_light"
app:layout_anchorGravity="right|bottom"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.928"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.961" />
</androidx.constraintlayout.widget.ConstraintLayout>
You can not use applicationcontext in here, but if you want you need to add flags to the intent. So easier method for you to use "this" instead:
mCreateRem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(this, FoodAddReminder.class);
startActivity(intent);
//Starts the new activity to add Reminders
}
});
We can only "guess" why, but "not working" and "app keeps stopping" could mean a lot of things and you didn't provide any Log information or an Exception stacktrace. Its also hard to guess what FoodAddReminder.class is, if its an activity, make sure its declared in your AndroidManifest.xml
mCreateRem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(this, FoodAddReminder.class); // <-- is this an activity?
startActivity(intent);
//Starts the new activity to add Reminders
}
});
Check your AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.me.my.project">
<application >
<activity
android:name=".FoodAddReminder"/> <!-- here -->
</application>
</manifest>
If that is not the issue, I suspect that using getApplicationContext(), you're having this crash log
AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this
really what you want?
You should then tell the system you want to start a new task,
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), FoodAddReminder.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
But I would suggest not doing it, instead use your FoodActivity as your calling activity to FoodReminder in this case, and pay attention to this, it should be prefixed with FoodActivity otherwise it will refer to its enclosing anonymous OnClickListener instance.
#Override
public void onClick(View v) {
Intent intent = new Intent(FoodActivity.this, FoodAddReminder.class);
startActivity(intent);
}
If none of these solved your "not working" issue, please provide a more specific Log information and reduce your code to something that is copy-and-paste-able.
I have an app that switches between two different activities (Main Activity with a simple text and Second Activity with two TextViews) in Android with different layouts every 10 seconds.
I want in Second Activity at the first time display only the first textView A, then return to the MainActivity and again lead to the Second Activity but display only the second textView B.
activity_second.xml:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="255dp"
android:layout_weight="1"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#android:color/holo_purple"
android:orientation="horizontal">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:text="A"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textSize="65sp" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#android:color/holo_orange_light"
android:orientation="horizontal">
<TextView
android:id="#+id/textViewB"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:text="B"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textSize="65sp" />
</LinearLayout>
</LinearLayout>
And java code that switches between two Activities provided bellow.
Second_activity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
Intent intent = new Intent(SecondActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}, 10000);
........
}
My problem is how to change the visibility of the two textViews for every time that switches between two activities.
To do it You can just pass a variable (if there are only 2 TextViews it can be boolean) to second activity. If it is true show 1st TextView if it is false show 2nd TextView.
To pass value with intent use this:
Boolean value = true; //set this if You want to show 1st or 2nd textbox
Intent i = new Intent(CurrentActivity.this, NewActivity.class);
i.putExtra("key", value);
startActivity(i);
To retrieve the value:
Bundle extras = getIntent().getExtras();
if (extras != null) {
Boolean value = extras.getBoolean("key");
//The key argument here must match that used in the other activity
}
When You have that value just set visibility of TextViews:
if (value)
{
textView1.setVisibility(TextView.VISIBLE);
textView2.setVisibility(TextView.GONE);
}
else
{
textView1.setVisibility(TextView.GONE);
textView2.setVisibility(TextView.VISIBLE);
}
I am currently creating an app on Android Studio.
I use different buttons (in the same activity) that go to different activities. The problem is that, with one button, it all works, but when I add another one the emulator crashes.
Here is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
defineButtons();
}
public void defineButtons() {
findViewById(R.id.next1).setOnClickListener(buttonClickListener);
findViewById(R.id.next2).setOnClickListener(buttonClickListener);
findViewById(R.id.next3).setOnClickListener(buttonClickListener);
}
private View.OnClickListener buttonClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.next1:
Intent Next1 = new Intent (Start.this, Next1.class);
startActivity(Next1);
break;
case R.id.next2:
Intent Next2 = new Intent (Start.this, Next2.class);
startActivity(Next2);
break;
case R.id.next3:
Intent Next3 = new Intent (Start.this, Next3.class);
startActivity(Next3);
break;
}
}
};
And here the XML:
<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=".Start"
android:background="#drawable/background">
<TextView
android:layout_width="match_parent"
android:layout_height="700px"
android:id="#+id/statement"
android:text="TEXT1"
android:background="#drawable/button_border"
android:textColor="#000000"
android:alpha="0.95"
android:layout_marginHorizontal="70px"
android:layout_marginTop="180px"
android:gravity="center"
android:paddingHorizontal="50px"
android:textSize="16sp"
/>
<Button
android:id="#+id/next1"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="match_parent"
android:layout_height="150px"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="160dp"
android:layout_marginHorizontal="70px"
android:alpha="0.9"
android:background="#drawable/button_border"
android:text="TEXT2"
android:textColor="#android:color/black"
android:textSize="16sp"
android:textAllCaps="false"/>
<Button
android:id="#+id/next2"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="match_parent"
android:layout_height="150px"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="90dp"
android:layout_marginHorizontal="70px"
android:alpha="0.9"
android:background="#drawable/button_border"
android:text="TEXT3"
android:textColor="#android:color/black"
android:textSize="16sp"
android:textAllCaps="false"/>
<Button
android:id="#+id/next3"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="match_parent"
android:layout_height="150px"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp"
android:layout_marginHorizontal="70px"
android:alpha="0.9"
android:background="#drawable/button_border"
android:text="TEXT4"
android:textColor="#android:color/black"
android:textSize="16sp"
android:textAllCaps="false"/>
</RelativeLayout>
I know this is messy, I'm new at programming.
Your code is perfectly fine you just need to declare your Next2, and Next3 activities in manifest file like this
<activity android:name=".Next2"
android:screenOrientation="portrait"/>
<activity android:name=".Next3"
android:screenOrientation="portrait"/>
Android reads your app components from manifest file, refer this link for more details https://developer.android.com/guide/topics/manifest/manifest-intro
I'm trying to develop a riddle game with levels. First level is in "OneActivity.java" and "activity_one.xml" 2nd level on "TwoActivity.java" and "activity_two.xml" and so on. After the user types the answer to the question in level one, a toast display with "Correct" is displayed if the answer is correct and "Wrong" if it's incorrect. Now, how do I automatically go to next level if the answer is correct but remain on same level until the user inputs the correct answer. Here's my OneActivity.java and activity_one.xml
OneActivity.java:
package com.golo.user.gaunkhanekatha;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class OneActivity extends Activity {
public Button check;
public EditText typeh;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one);
check = (Button)findViewById(R.id.check); //R.id.button is the id on your xml
typeh = (EditText)findViewById(R.id.typeh); //this is the EditText id
check.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
//Here you must get the text on your EditText
String Answer = (String) typeh.getText().toString(); //here you have the text typed by the user
//You can make an if statement to check if it's correct or not
if(Answer.equals("4") || (Answer.equals("four")))
{
//Create a Toast because it's correct
Toast.makeText(OneActivity.this, "Correct!",
Toast.LENGTH_LONG).show();
}
else{
//It's not the correct answer
Toast.makeText(OneActivity.this, "Wrong! Try Again",
Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_aboutus, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_one.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
android:weightSum="1"
android:textAlignment="center"
android:id="#+id/oneque">
<TextView
android:layout_width="300dp"
android:layout_height="200dp"
android:text="What is 2+2?"
android:id="#+id/que"
android:width="255dp"
android:textSize="30dp"
android:layout_margin="50dp"
android:textStyle="italic"
android:gravity="center" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/typeh"
android:layout_gravity="center_horizontal"
android:text="Type Here" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check Answer"
android:id="#+id/check"
android:layout_gravity="center_horizontal" />
</LinearLayout>
activity_level.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal">
<Button
android:id="#+id/button1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dp"
android:layout_weight="1"
android:onClick="moveToOneActivity"
android:background="#drawable/one" />
<Button
android:id="#+id/button2"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dip"
android:layout_weight="1"
android:onClick="moveToTwoActivity"
android:background="#drawable/two" />
<Button
android:id="#+id/button3"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dip"
android:layout_weight="1"
android:onClick="moveToThreeActivity"
android:background="#drawable/three" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal">
<Button
android:id="#+id/button4"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dp"
android:layout_weight="1"
android:onClick="moveToFourActivity"
android:background="#drawable/four" />
<Button
android:id="#+id/button5"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dip"
android:layout_weight="1"
android:onClick="moveToFiveActivity"
android:background="#drawable/five" />
<Button
android:id="#+id/button6"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dip"
android:layout_weight="1"
android:onClick="moveToSixActivity"
android:background="#drawable/six" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal">
<Button
android:id="#+id/button7"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dp"
android:layout_weight="1"
android:onClick="moveToSevenActivity"
android:background="#drawable/seven" />
<Button
android:id="#+id/button8"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dip"
android:layout_weight="1"
android:onClick="moveToEightActivity"
android:background="#drawable/eight" />
<Button
android:id="#+id/button9"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dip"
android:layout_weight="1"
android:onClick="moveToNineActivity"
android:background="#drawable/nine" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal">
<Button
android:id="#+id/button10"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dp"
android:layout_weight="1"
android:onClick="moveToTenActivity"
android:background="#drawable/ten" />
<Button
android:id="#+id/button11"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dip"
android:layout_weight="1"
android:onClick="moveToElevenActivity"
android:background="#drawable/eleven" />
<Button
android:id="#+id/button12"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="30dip"
android:layout_weight="1"
android:onClick="moveToTwelveActivity"
android:background="#drawable/twelve" />
</LinearLayout>
</LinearLayout>
if(Answer.equals("4") || (Answer.equals("four")))
{
//Create a Toast because it's correct
Toast.makeText(OneActivity.this, "Correct!",
Toast.LENGTH_LONG).show();
//Here create intent to the new activity - for example
//If you wish the user will have time to see the toast, you can use a Handler with post delayed
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent newLevel= new Intent(OneActivity.this, TwoActivity.class);
startActivity(newLevel);
finish(); //finish the activity of the current level
}
}, 3000); //the code inside run() will be executed after 3 seconds so the user can see the toast
}
else
{
//It's not the correct answer
Toast.makeText(OneActivity.this, "Wrong! Try Again",
Toast.LENGTH_LONG).show();
}
To go to the second level you should add this Intent inside your correct Toast as follows :
Intent i = new Intent(OneActivity.this, TwoActivity.class);
startActivity(i);
finish();
This should be your code :
check.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
//Here you must get the text on your EditText
String Answer = (String) typeh.getText().toString(); //here you have the text typed by the user
//You can make an if statement to check if it's correct or not
if(Answer.equals("4") || (Answer.equals("four")))
{
//Create a Toast because it's correct
Toast.makeText(OneActivity.this, "Correct! Going to Level 2...",
Toast.LENGTH_LONG).show();
Intent i = new Intent(OneActivity.this, TwoActivity.class);
startActivity(i);
finish();
}
else{
//It's not the correct answer
Toast.makeText(OneActivity.this, "Wrong! Try Again",
Toast.LENGTH_LONG).show();
}
}
});
EDIT
This edit will cancel the Toast when you are on your TwoActivity.class, you have to change some stuff, I'll exaplain to you.
1.- Create a global Toast variable.
private Toast toast;
2.- Initialize it on your onCreate() like this :
toast = Toast.makeText(OneActivity.this, "", Toast.LENGTH_SHORT);
3.- Then change your two Toast messages to this :
//Correct Toast
toast.setText("Correct! Going to Level 2...");
toast.show();
//Incorrect Toast
toast.setText("Wrong! Try Again");
toast.show();
4.- You want to make a finish() to avoid the back button to return to OneActivity() so you will call it, and it calls onDestroy() so you have to add this method aswell to cancel the Toast
#Override
protected void onDestroy() {
super.onDestroy();
if(toast!= null) {
toast.cancel();
}
}
You can use intents to switch to another activity.
Intent myIntent = new Intent(this, MyActivity.class);
startActivity(myIntent);
You could simply have an if statement. If the answer is correct, create an intent and start activity two, otherwise reloop in activity one or do whatever other behaviour you want to do if the answer is wrong.
I've developed a news android app, this app uses a MediaPlayer class to stream newscast tracks from SoundCloud and everything works fine. Now let's say the user pressed the play button from inside the app and the music starts playing. Now the user pressed the hardware home button and the app went to the background or the user pressed the sleep button to turn off the screen. I have managed to let the music playing in the background but i want the user to be able to control the MediaPlayer from outside the app (pause, stop, next, prev actions).
I searched a lot and didn't find anything, How can i do that?
I didn't put my code because i think it's irrelevant Please tell me if you want to see the code.
Thanks in advance.
I've done something similar by adding a custom notification with images/buttons to control the audio play and channel from the Android notification bar.
I think this is what you are after.
Notification code:
public Notification buildNotification()
{
Intent intent = new Intent(mContext, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
setContentView();
Notification.Builder notibuilder = new Notification.Builder(mContext);
notibuilder.setContentTitle(" ");
notibuilder.setContentText(" ");
notibuilder.setSmallIcon(R.drawable.ic_launcher);
notibuilder.setOngoing(true);
notibuilder.setAutoCancel(false);
notibuilder.setContentIntent(pIntent);
notibuilder.setContent(mContentView);
notibuilder.setTicker(null);
mNotification = notibuilder.build();
NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
return mNotification;
}
public void setContentView()
{
mContentView = new RemoteViews(mContext.getPackageName(), R.layout.custom_notification);
mContentView.setTextViewText(R.id.notificaiton_app_title, "");
String currentChannel = " ";
if ( mCurrentChannel != -1)
currentChannel = " " + (mCurrentChannel + 1);
mContentView.setTextViewText(R.id.notificaiton_app_channel, currentChannel);
Intent previousIntent = new Intent(mContext, NotificationButtonIntentService.class);
previousIntent.setAction(NotificationButtonIntentService.Action_Previous);
mContentView.setOnClickPendingIntent(R.id.notification_layout_previous, PendingIntent.getService(mContext, 0, previousIntent, PendingIntent.FLAG_CANCEL_CURRENT));
mContentView.setOnClickPendingIntent(R.id.notification_image_previous, PendingIntent.getService(mContext, 0, previousIntent, PendingIntent.FLAG_CANCEL_CURRENT));
Intent playIntent = new Intent(mContext, NotificationButtonIntentService.class);
if ( mCurrentChannel != -1)
{
playIntent.setAction(NotificationButtonIntentService.Action_Pause);
mContentView.setInt(R.id.notification_image_play_pause, "setBackgroundResource", R.drawable.ic_media_pause);
}
else
{
playIntent.setAction(NotificationButtonIntentService.Action_Play);
mContentView.setInt(R.id.notification_image_play_pause, "setBackgroundResource", R.drawable.ic_media_play);
}
mContentView.setOnClickPendingIntent(R.id.notification_layout_play_pause, PendingIntent.getService(mContext, 0, playIntent, PendingIntent.FLAG_CANCEL_CURRENT));
mContentView.setOnClickPendingIntent(R.id.notification_image_play_pause, PendingIntent.getService(mContext, 0, playIntent, PendingIntent.FLAG_CANCEL_CURRENT));
Intent nextIntent = new Intent(mContext, NotificationButtonIntentService.class);
nextIntent.setAction(NotificationButtonIntentService.Action_Next);
mContentView.setOnClickPendingIntent(R.id.notification_layout_next, PendingIntent.getService(mContext, 0, nextIntent, PendingIntent.FLAG_CANCEL_CURRENT));
mContentView.setOnClickPendingIntent(R.id.notification_image_next, PendingIntent.getService(mContext, 0, nextIntent, PendingIntent.FLAG_CANCEL_CURRENT));
Intent closeIntent = new Intent(mContext, NotificationButtonIntentService.class);
closeIntent.setAction(NotificationButtonIntentService.Action_Close);
mContentView.setOnClickPendingIntent(R.id.notification_layout_close, PendingIntent.getService(mContext, 0, closeIntent, PendingIntent.FLAG_CANCEL_CURRENT));
mContentView.setOnClickPendingIntent(R.id.notification_image_close, PendingIntent.getService(mContext, 0, closeIntent, PendingIntent.FLAG_CANCEL_CURRENT));
}
Layout:
<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" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true" >
<ImageView
android:id="#+id/notification_app_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingLeft="12dp"
android:src="#drawable/ic_stat_zipstreamer" />
<TextView
android:id="#+id/notificaiton_app_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="1" >
<TextView
android:id="#+id/notificaiton_app_channel"
style="#style/notification.channel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:ems="2" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/notification_layout_previous"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="1" >
<ImageButton
android:id="#+id/notification_image_previous"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="#drawable/ic_media_previous" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/notification_layout_play_pause"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="1" >
<ImageButton
android:id="#+id/notification_image_play_pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="#drawable/ic_media_play" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/notification_layout_next"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="1" >
<ImageButton
android:id="#+id/notification_image_next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="#drawable/ic_media_next" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/notification_layout_close"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_weight="1" >
<ImageButton
android:id="#+id/notification_image_close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="#drawable/ic_media_close" />
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
Intent Service:
public class NotificationButtonIntentService extends IntentService
{
public static final String TAG = "NotificationButtonIntentService";
public static final String Action_Play = "play";
public static final String Action_Pause = "pause";
public static final String Action_Previous = "previous";
public static final String Action_Next = "next";
public static final String Action_Close = "close";
public NotificationButtonIntentService()
{
super("");
}
public NotificationButtonIntentService(String name)
{
super(name);
}
#Override
protected void onHandleIntent(Intent intent)
{
String action = intent.getAction();
String realAction = intent.getAction();
if (realAction != null)
{
if (realAction.equals(Action_Play))
{
EventBus.getDefault().post(new PlayControlEvent(PlayControlEvent.PlayAction.PLAY));
}
else if (realAction.equals(Action_Pause))
{
EventBus.getDefault().post(new PlayControlEvent(PlayControlEvent.PlayAction.PAUSE));
}
else if (realAction.equals(Action_Close))
{
EventBus.getDefault().post(new ShutdownEvent());
}
else if ( realAction.equals(Action_Next))
{
EventBus.getDefault().post(new PlayControlEvent(PlayControlEvent.PlayAction.NEXT_CHANNEL));
}
else if ( realAction.equals(Action_Previous))
{
EventBus.getDefault().post(new PlayControlEvent(PlayControlEvent.PlayAction.PREVIOUS_CHANNEL));
}
}
}
}
You need yo access your MediaPlayer object. make it static and create your static pause,start,etc methods. something like this:
public class myMediaPlayer{
static MediaPlayer mediaPlayer = null;
public static void start(final Context context, Uri media){
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(context, media);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MEDIA);
mediaPlayer.prepare();
mediaPlayer.start();
}
public static void stop() {
if(mediaPlayer!=null)
mediaPlayer.release();
}