Crashing when switching on vibrate, silent and normal - java

My app crashing when I try to toggle phone modes. For example when I'm in ring mode end I try to switch on silent is crashing, but when I try to toggle vibrate is working fine. Exactly the same thing is happening when I try to change from vibrate to ring. Check status is working fine, there is not crash.
Here is the logcat line:
at com.example.lab3_1.MainActivity.onSilent(MainActivity.java:56)
That involved the code line:
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
Here is the main:
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private AudioManager myAudioManager;
NotificationManager notificationManager;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
NotificationManager notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
if(notificationManager.isNotificationPolicyAccessGranted())
{
Intent intent = new
Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
startActivity(intent);
}
}
public void onMode(View v)
{
int mod=myAudioManager.getRingerMode();
if(mod==AudioManager.RINGER_MODE_VIBRATE){
Toast.makeText(this,"Now in Vibrate Mode",Toast.LENGTH_LONG).show();
}
else if(mod==AudioManager.RINGER_MODE_NORMAL){
Toast.makeText(this,"Now in Ringing Mode",Toast.LENGTH_LONG).show();
}
else if(mod==AudioManager.RINGER_MODE_SILENT)
{
Toast.makeText(this,"Now in Silent Mode",Toast.LENGTH_LONG).show();
}
}
public void onRing(View v)
{
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Toast.makeText(this,"Now in Ringing Mode",Toast.LENGTH_LONG).show();
}
public void onSilent(View v)
{
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
Toast.makeText(this,"Now in silent Mode",Toast.LENGTH_LONG).show();
}
public void onVibrate(View v)
{
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
Toast.makeText(this,"Now in Vibrate Mode",Toast.LENGTH_LONG).show();
}
}
Here is the xml file:
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="100dp"
android:id="#+id/bt1"
android:text="CURRENT MODE CHECK"
android:onClick="onMode"/>
<Button
android:layout_width="match_parent"
android:layout_height="100dp"
android:id="#+id/bt2"
android:text="RINGER MODE"
android:onClick="onRing"/>
<Button
android:layout_width="match_parent"
android:layout_height="100dp"
android:id="#+id/bt3"
android:text="SILENT MODE"
android:onClick="onSilent"/>
<Button
android:layout_width="match_parent"
android:layout_height="100dp"
android:id="#+id/bt4"
android:text="VIBRATE MODE"
android:onClick="onVibrate"/>
</LinearLayout>

Related

Android w/ Java: Using Seekbar to adjust volume

I'm new to Android App development (on android studio) and to start off I'm creating a simple 'bonk' soundboard app, and testing it using the Pixel 2 android emulator. The goal of the app is to play the bonk noise whenever someone presses the BONK button on my main screen. I also wanted to implement a seekbar that adjusts the volume when you slide it. To do this I followed a simple implementation I found here on StackOverflow (shown below).
Even though the rest of my app works fine, for some reason my volume won't adjust whenever I slide the seekbar. Here is my code:
MainActivity.java
package com.example.bonk;
import androidx.appcompat.app.AppCompatActivity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
public class MainActivity extends AppCompatActivity {
Button bonkButton;
SeekBar volumeSeekBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bonkButton = (Button)findViewById(R.id.bonkButton);
volumeSeekBar = (SeekBar)findViewById(R.id.volumeSeekBar);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.bonksound);
bonkButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mp.start();
}
});
}
}
Volumizer.java
package com.example.bonk;
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class Volumizer extends Activity {
//Called when the activity is first created.
private SeekBar volumeSeekbar = null;
private AudioManager audioManager = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
setContentView(R.layout.activity_main);
initControls();
}
private void initControls() {
try {
volumeSeekbar = findViewById(R.id.volumeSeekBar);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
volumeSeekbar.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
}
#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean arg2) {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
progress, 0);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
Activity_main.xml
<?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=".MainActivity">
<Button
android:id="#+id/bonkButton"
android:layout_width="296dp"
android:layout_height="232dp"
android:text="#string/bonk"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<SeekBar
android:id="#+id/volumeSeekBar"
android:layout_width="276dp"
android:layout_height="26dp"
android:layout_marginBottom="116dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.496"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Please let me know if you have any ideas as of what I may be doing wrong. Thank you!
I was able to solve the problem by moving my initControls() function definition into my MainActivity.java class and calling it onCreate.

Sudden error about not resolving some methods and symbols

I'm a beginner programmer and I'm working on an app where I want to have a Settings activity with 2 switch buttons (one to turn on/off notifications in status bar and one to turn on/off notification sound).Yesterday everything went fine with the compiling but today suddenly I got all these errors about not resolving some methods or symbols. What happened and how can I fix it?
In particular the errors where the following:
cannot resolve method: onCreate,setContentView,getSystemService, findViewById
cannot resolve symbol: OnCheckedChangeListener, simpleswitch1, simpleswitch2, arg0, view
Override: Annotations are not allowed here
onClick and onCheckedChanged do not work properly.
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Switch;
import androidx.annotation.RequiresApi;
import static android.app.PendingIntent.getActivity;
import static android.content.Context.NOTIFICATION_SERVICE;
public class Settings extends AppCompatActivity {
Switch simpleSwitch1, simpleSwitch2;
NotificationManager manager;
Notification myNotication;
private Notification notification;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
simpleswitch1 = (Switch) findViewById(R.id.simpleswitch1);
simpleswitch2 = (Switch) findViewById(R.id.simpleswitch2);
simpleSwitch1.setOnCheckedChangeListener(new View.OnCheckedChangeListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public void onCheckedChanged(CompoundButton simpleswitch1, boolean isChecked) {
if (isChecked) {
#Override
public void onClick(View arg0) {
//API level 11
Intent intent = new Intent("com.rj.notitfications.SECACTIVITY");
PendingIntent pendingIntent = PendingIntent.getActivity(Settings.this, 1, intent, 0);
Notification.Builder builder = new Notification.Builder(Settings.this);
builder.setAutoCancel(false);
builder.setTicker("this is ticker text");
builder.setContentTitle("WhatsApp Notification");
builder.setContentText("You have a new message");
builder.setSmallIcon(R.drawable.notification);
builder.setContentIntent(pendingIntent);
builder.setOngoing(true);
builder.setSubText("This is subtext..."); //API level 16
builder.setNumber(100);
builder.build();
myNotication = builder.getNotification();
manager.notify(11, myNotication);
}
}
else{
simpleSwitch1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
manager.cancel(11);
}
});
}
}});
public void onClick(View view) {
public void onCheckedChanged(CompoundButton simpleswitch2, boolean isChecked) {
if (isChecked){
notification.defaults |= Notification.DEFAULT_SOUND;
}}}}}
XML File
<?xml version="1.0" encoding="utf-8"?>
<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=".Settings">
<TextView
android:id="#+id/textView16"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:text="SETTINGS"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Headline"
android:textColor="#color/design_default_color_primary_dark"
android:textColorHighlight="#color/design_default_color_primary"
android:textStyle="bold" />
<Switch
android:id="#+id/simpleswitch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView16"
android:layout_centerHorizontal="true"
android:layout_marginTop="55dp"
android:text="NOTIFICATIONS"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textColor="#color/colorPrimary"
android:textStyle="normal"
android:checked="true"
/>
<Switch
android:id="#+id/simpleswitch2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/simpleswitch1"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:text="SOUNDS"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textColor="#color/colorPrimary"
android:checked="true" />
<ImageView
android:id="#+id/imageView3"
android:layout_width="61dp"
android:layout_height="44dp"
android:layout_marginLeft="280dp"
android:layout_marginTop="30dp"
app:srcCompat="#drawable/ic_menu_manage" />
</RelativeLayout>
From you java you are placing methods inside other methods this is not possible in java
Also
Try setting listeners as such
// set default state on/off
simpleSwitch1.setChecked(false);
simpleSwitch2.setChecked(false);
simpleSwitch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
// prepare your notification and display
}else{
// do something
}
}
});
simpleSwitch2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
// prepare your notification and display
}else{
// do something
}
}
});
hope this helps, your java code was quite hard to understand.

Notifications don't show [duplicate]

This question already has an answer here:
Notifications don't appear
(1 answer)
Closed 2 years ago.
I'm new to programming and app development and I'm trying to develop an app that shows events and notifies the user when a new event is up.I'm trying to create a settings activity with 2 switch buttons, 1 for notifications on status bar and 1 for notification sound. When I turn on the switches, I don't get any notification nor sound.
How can I fix that?
JAVA FILE
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.V;
public class Settings extends AppCompatActivity {
Switch simpleSwitch1, simpleSwitch2;
NotificationManager manager;
Notification myNotication;
private Notification notification;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
simpleswitch1 = (Switch) findViewById(R.id.simpleswitch1);
simpleswitch2 = (Switch) findViewById(R.id.simpleswitch2);
if (simpleSwitch1.isChecked()){
simpleSwitch1.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onClick(View arg0) {
//API level 11
Intent intent = new Intent("com.rj.notitfications.SECACTIVITY");
PendingIntent pendingIntent = PendingIntent.getActivity(Settings.this, 1, intent, 0);
Notification.Builder builder = new Notification.Builder(Settings.this);
builder.setAutoCancel(false);
builder.setTicker("this is ticker text");
builder.setContentTitle("WhatsApp Notification");
builder.setContentText("You have a new message");
builder.setSmallIcon(R.drawable.notification);
builder.setContentIntent(pendingIntent);
builder.setOngoing(true);
builder.setSubText("This is subtext..."); //API level 16
builder.setNumber(100);
builder.build();
myNotication = builder.getNotification();
manager.notify(11, myNotication);
/*
//API level 8
Notification myNotification8 = new Notification(R.drawable.ic_launcher, "this is ticker text 8", System.currentTimeMillis());
Intent intent2 = new Intent(MainActivity.this, SecActivity.class);
PendingIntent pendingIntent2 = PendingIntent.getActivity(getApplicationContext(), 2, intent2, 0);
myNotification8.setLatestEventInfo(getApplicationContext(), "API level 8", "this is api 8 msg", pendingIntent2);
manager.notify(11, myNotification8);
*/
}
});}
else{
simpleSwitch1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
manager.cancel(11);
}
});
}
}
public void onClick(View v) {
simpleSwitch2 = (Switch) findViewById(R.id.simpleswitch2);
String statusSwitch2;
if (simpleSwitch2.isChecked())
notification.defaults |= Notification.DEFAULT_SOUND;
}}
XML FILE
<?xml version="1.0" encoding="utf-8"?>
<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=".Settings">
<TextView
android:id="#+id/textView16"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:text="SETTINGS"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Headline"
android:textColor="#color/design_default_color_primary_dark"
android:textColorHighlight="#color/design_default_color_primary"
android:textStyle="bold" />
<Switch
android:id="#+id/simpleswitch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView16"
android:layout_centerHorizontal="true"
android:layout_marginTop="55dp"
android:text="NOTIFICATIONS"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textColor="#color/colorPrimary"
android:textStyle="normal"
android:checked="true"
/>
<Switch
android:id="#+id/simpleswitch2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/simpleswitch1"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:text="SOUNDS"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"
android:textColor="#color/colorPrimary"
android:checked="true" />
<ImageView
android:id="#+id/imageView3"
android:layout_width="61dp"
android:layout_height="44dp"
android:layout_marginLeft="280dp"
android:layout_marginTop="30dp"
app:srcCompat="#drawable/ic_menu_manage" />
</RelativeLayout>
A couple of stuff here:
For switches, you probably want OnCheckedChangeListener, not
OnClickListener.
You want to set the OnCheckedChangeListener once in your onCreate() and check for the Switch's state
inside this listener:
simpleswitch1 = (Switch) findViewById(R.id.simpleswitch1);
simpleswitch2 = (Switch) findViewById(R.id.simpleswitch2);
simpleSwitch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// show notification
} else {
// cancel notification
}
}
});`
// Similarly for switch2`

App seems like launching more than once in landscape mode after splash screen?

I have a splash screen and after that my main activity starts. This works fine in portrait mode but if in case i tilt my phone in landscape mode, the main activity can be seen launching more than once after splash screen.
I tried using android:launchMode="singleInstance" but in that case i am not able to attach files in feedback alert-box.
Following is my code:
MainActivity.java
package com.example.android.tel;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.crashlytics.android.Crashlytics;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends AppCompatActivity {
Toolbar mActionBarToolbar;
TextView toolbar_title_mainActivity, main_textView, disclaimer_txtView;
CardView SearchDept, SearchName, disclaimer, feedback;
ImageView back;
ArrayList<Uri> arrayUri = new ArrayList<Uri>();
ArrayAdapter<Uri> myFileListAdapter;
ListView listViewFiles;
Dialog alertDialog;
final int RQS_LOADIMAGE = 0;
final int RQS_SENDEMAIL = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.activity_main);
} else {
setContentView(R.layout.activity_main);
}
mActionBarToolbar = (Toolbar) findViewById(R.id.tool_bar_main_activity);
toolbar_title_mainActivity = (TextView) findViewById(R.id.toolbar_title);
main_textView = (TextView) findViewById(R.id.main_textView);
main_textView.setPaintFlags(main_textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
setSupportActionBar(mActionBarToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar_title_mainActivity.setText("Hry. Govt. Telephone Directory");
back = (ImageView) findViewById(R.id.back);
back.setVisibility(View.INVISIBLE);
disclaimer = (CardView) findViewById(R.id.disclaimer);
feedback = (CardView) findViewById(R.id.feedback);
SearchDept = (CardView) findViewById(R.id.cardView1_mainActivity);
SearchName = (CardView) findViewById(R.id.cardView2_mainActivity);
SearchDept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, CardViewActivity.class);
startActivity(i);
}
});
SearchName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent j = new Intent(MainActivity.this, ByNameListActivity.class);
startActivity(j);
}
});
disclaimer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Dialog alertDialog = new Dialog(MainActivity.this);
alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
alertDialog.setContentView(R.layout.disclaimer);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
alertDialog.show();
}
});
feedback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog = new Dialog(MainActivity.this);
alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
alertDialog.setContentView(R.layout.feedback);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
alertDialog.setCanceledOnTouchOutside(true);
ImageView send_btn=(ImageView)alertDialog.findViewById(R.id.send);
ImageView attach_btn=(ImageView)alertDialog.findViewById(R.id.attachment);
final TextView to_email_add=(TextView)alertDialog.findViewById(R.id.email_address);
to_email_add.setText("tel#gmail.com");
final EditText email_subject=(EditText)alertDialog.findViewById(R.id.email_subject);
final EditText email_text=(EditText)alertDialog.findViewById(R.id.email_text);
final EditText mobile_no=(EditText)alertDialog.findViewById(R.id.mobile_text);
email_subject.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
}
}
});
email_text.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
}
}
});
myFileListAdapter = new ArrayAdapter<Uri>(
MainActivity.this,
android.R.layout.simple_list_item_1,
arrayUri);
listViewFiles = (ListView)alertDialog.findViewById(R.id.filelist);
listViewFiles.setAdapter(myFileListAdapter);
listViewFiles.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
myFileListAdapter.remove(arrayUri.get(position));
myFileListAdapter.notifyDataSetChanged();
Toast.makeText(view.getContext(), "You unattached one item", Toast.LENGTH_LONG).show();
return false;
}
});
attach_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RQS_LOADIMAGE);
}
});
send_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email_add=to_email_add.getText().toString();
String email_sub=email_subject.getText().toString();
String email_txt=email_text.getText().toString();
String emailAddressList[] = {email_add};
String mobileNo=mobile_no.getText().toString();
String info=email_txt+"\n\nPhone Number :"+mobileNo;
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_EMAIL, emailAddressList);
intent.putExtra(Intent.EXTRA_SUBJECT, email_sub);
intent.putExtra(Intent.EXTRA_TEXT,info);
if(arrayUri.isEmpty()&& isValidPhone(mobileNo)&& !(mobileNo.isEmpty())){
//send email without photo attached
intent.setAction(Intent.ACTION_SEND);
intent.setType("plain/text");
new Handler().postDelayed(new Runnable() {
public void run() {
alertDialog.dismiss();
}
}, 5000);
}else if(arrayUri.size() == 1 && isValidPhone(mobileNo)&& !(mobileNo.isEmpty())){
//send email with ONE photo attached
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, arrayUri.get(0));
intent.setType("image/*");
new Handler().postDelayed(new Runnable() {
public void run() {
alertDialog.dismiss();
}
}, 5000);
}else if(arrayUri.size()>1&& isValidPhone(mobileNo)&& !(mobileNo.isEmpty())){
//send email with MULTI photo attached
intent.setAction(Intent.ACTION_SEND_MULTIPLE);
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, arrayUri);
intent.setType("image/*");
new Handler().postDelayed(new Runnable() {
public void run() {
alertDialog.dismiss();
}
}, 5000);
}
else {
Toast.makeText(v.getContext(), "Phone number is not valid", Toast.LENGTH_LONG).show();
}
startActivity(Intent.createChooser(intent, "Please provide valid details"));
}
});
alertDialog.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
switch(requestCode){
case RQS_LOADIMAGE:
Uri imageUri = data.getData();
arrayUri.add(imageUri);
myFileListAdapter.notifyDataSetChanged();
break;
case RQS_SENDEMAIL:
break;
}
}
}
public static boolean isValidPhone(String phone)
{
String expression = "^([0-9\\+]|\\(\\d{1,3}\\))[0-9\\-\\. ]{3,15}$";
CharSequence inputString = phone;
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(inputString);
if (matcher.matches())
{
return true;
}
else{
return false;
}
}
public void hideKeyboard(View view) {
InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int orientation;
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
// or = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
}else {
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
}
// Add code if needed
// listViewFiles.setAdapter(myFileListAdapter);
// myFileListAdapter.notifyDataSetChanged();
setRequestedOrientation(orientation);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:weightSum="14"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
tools:context="com.example.android.tel.MainActivity">
<include
android:id="#+id/tool_bar_main_activity"
layout="#layout/toolbar">
</include>
<TextView
android:id="#+id/main_textView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
android:layout_marginTop="10dp"
android:text="How would you like to search?"
android:textStyle="bold"
android:textSize="14sp"
android:textColor="#1A237E"
android:gravity="center_horizontal"/>
<RelativeLayout
android:id="#+id/searchby_btns"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="4"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:gravity="center_vertical">
<android.support.v7.widget.CardView
android:id="#+id/cardView1_mainActivity"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center"
card_view:cardCornerRadius="4dp"
android:layout_marginTop="10dp"
card_view:cardBackgroundColor="#e97c1d">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search By Department.."
android:textColor="#android:color/white"
android:textStyle="bold"
android:textSize="18sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="#+id/cardView2_mainActivity"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center"
android:layout_below="#id/cardView1_mainActivity"
card_view:cardCornerRadius="4dp"
android:layout_marginTop="20dp"
card_view:cardBackgroundColor="#e97c1d">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search By Name.."
android:textColor="#android:color/white"
android:textStyle="bold"
android:textSize="18sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:layout_weight="8.5">
<ImageView
android:id="#+id/map_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/hry_map"
android:elevation="4dp"
android:layout_gravity="center"/>
</RelativeLayout>
<RelativeLayout
android:layout_below="#id/map_image"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:paddingRight="16dp"
android:paddingLeft="16dp"
android:layout_marginTop="2dp"
android:gravity="center_horizontal"
android:layout_alignParentBottom="true">
<android.support.v7.widget.CardView
android:id="#+id/disclaimer"
android:layout_width="150dp"
android:layout_height="30dp"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="4dp"
android:layout_marginRight="8dp"
card_view:cardBackgroundColor="#424242">
<TextView
android:layout_width="150dp"
android:layout_height="30dp"
android:text="Disclaimer"
android:gravity="center"
android:layout_gravity="center_vertical"
android:textColor="#FFFFFF"
android:textStyle="bold"/>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="#+id/feedback"
android:layout_toRightOf="#id/disclaimer"
android:layout_width="150dp"
android:layout_height="30dp"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="4dp"
card_view:cardBackgroundColor="#424242">
<TextView
android:layout_width="150dp"
android:layout_height="30dp"
android:text="Feedback"
android:gravity="center"
android:layout_gravity="center_vertical"
android:textColor="#FFFFFF"
android:textStyle="bold"/>
</android.support.v7.widget.CardView>
</RelativeLayout>
</LinearLayout>
SplashScreenActivity.java
package com.example.android.telephonedirectory;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ProgressBar;
import com.felipecsl.gifimageview.library.GifImageView;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
public class SplashScreenActivity extends AppCompatActivity {
// private GifImageView gifimageview;
private ProgressBar progressBarSplashScreen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.activity_splash_screen);
} else {
setContentView(R.layout.activity_splash_screen);
}
// gifimageview=(GifImageView)findViewById(R.id.gifSplashscreenImage);
progressBarSplashScreen=(ProgressBar)findViewById(R.id.progressbarSplashscreen);
progressBarSplashScreen.setVisibility(progressBarSplashScreen.VISIBLE);
//set GifImageView Resource
/*try {
InputStream inputStream=getAssets().open("splash_Screen.png");
byte[] bytes= IOUtils.toByteArray(inputStream);
gifimageview.setBytes(bytes);
gifimageview.startAnimation();
}catch (IOException ex){
}*/
//Wait for 4 seconds and start activity main
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
SplashScreenActivity.this.startActivity(new Intent(SplashScreenActivity.this,MainActivity.class));
SplashScreenActivity.this.finish();
}
},2000);
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int orientation;
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
// or = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
}else {
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
}
// Add code if needed
// listViewFiles.setAdapter(myFileListAdapter);
// myFileListAdapter.notifyDataSetChanged();
setRequestedOrientation(orientation);
}
}
Dont use android:launchMode="singleInstance"
Launch mode you should use "singleTask" for this .
Because singleInstance creates separate task stack for Activity and do not check activity in current Task Stack.
while "singleTask" check each time if an Activity exist in Task Stack it can not create new one.

How to get time for splashscreen

How to get time for splashcreen?
I want to add about 15 second time? How can I integrate it into the code?
For example, to direct activity after about 15 seconds.
package com.trees.activities;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
public class MainSlider extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
SharedPreferences settings=getSharedPreferences("prefs",0);
boolean firstRun=settings.getBoolean("firstRun",false);
if(firstRun==false)//if running for first time
//Splash will load for first time
{
SharedPreferences.Editor editor=settings.edit();
editor.putBoolean("firstRun",true);
editor.commit();
Intent i=new Intent(MainSlider.this,MaterialIntro.class);
startActivity(i);
finish();
}
else
{
Intent a=new Intent(MainSlider.this,MainActivity.class);
startActivity(a);
finish();
}
}
}
HOW TO: Simple spash screen
First you need to define the spash screen in your layout.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView android:id="#+id/splashscreen" android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:src="#drawable/splash"
android:layout_gravity="center"/>
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, splash"/>
</LinearLayout>
And your activity:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
public class Splash extends Activity {
/** Duration of wait **/
private final int SPLASH_DISPLAY_LENGTH = 1000;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.splashscreen);
/* New Handler to start the Menu-Activity
* and close this Splash-Screen after some seconds.*/
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
/* Create an Intent that will start the Menu-Activity. */
Intent mainIntent = new Intent(Splash.this,Menu.class);
Splash.this.startActivity(mainIntent);
Splash.this.finish();
}
}, SPLASH_DISPLAY_LENGTH);
}
}

Categories

Resources