Android: Control MediaPlayer instance(object) from outside the app? - java

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();
}

Related

Why is second floating action button not working?

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.

How to fetch image path file to one Activity to other Activity

I have an App that verifies the ID card by clicking photos from both sides, after clicking the picture front-side of the id card the user moves to another activity for clicking the picture back-side of the id card after completing those prosses the user redirect to another activity that the user sees both sides of the document into different ImageView but I don't know how to fetch or pass
those images on this Activity that user can see their ID card for confirmation.
Here is my front side-scan activity
public class Front_Scan extends AppCompatActivity {
ActivityResultLauncher<Intent> activityResultLauncher;
private static final int PERMISSION_CODE = 101;
public String currentPhotoPath;
Button frontImgCap;
Button frontImgCapAgain;
Button frontNext;
ImageView frontImg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_front_scan);
frontImg = findViewById(R.id.Image_id_front);
frontImgCap = findViewById(R.id.imgCapture_front);
frontImgCap.setVisibility(VISIBLE);
frontImgCapAgain = findViewById(R.id.Front_imgCapture_again);
frontImgCapAgain.setVisibility(GONE);
frontNext = findViewById(R.id.front_next);
frontNext.setVisibility(INVISIBLE);
activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult()
, new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
File f = new File(currentPhotoPath);
frontImgCapAgain.setVisibility(VISIBLE);
frontImgCap.setVisibility(INVISIBLE);
frontNext.setVisibility(VISIBLE);
frontImg.setImageURI(Uri.fromFile(f));
}
}
});
frontImgCap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//if system os is >= marshmallow, request runtime permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CAMERA) ==
PackageManager.PERMISSION_DENIED ||
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_DENIED) {
//permission not enable, request it
String[] permission = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
//show popup to request permissions
requestPermissions(permission, PERMISSION_CODE);
} else {
//permission already given
dispatchTakePictureIntent();
}
} else {
//system os < marshmallow
dispatchTakePictureIntent();
}
}
});
}
public void next(View view) {
Intent myIntent = new Intent(Front_Scan.this, back_scan.class);
Front_Scan.this.startActivity(myIntent);
finish();
}
public void scanAgain(View view) {
clearMyFiles();
onCreateLayouts();
frontImg.setImageDrawable(getResources().getDrawable(R.drawable.id_front));
}
void clearMyFiles() {
File imgFile = new File(currentPhotoPath);
if (imgFile != null) {
imgFile.delete();
}
}
public void onCreateLayouts() {
frontImgCap.setVisibility(VISIBLE);
frontImgCapAgain.setVisibility(GONE);
frontNext.setVisibility(INVISIBLE);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSION_CODE:
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
dispatchTakePictureIntent();
} else {
Toast.makeText(this, "permission denied...", Toast.LENGTH_SHORT).show();
}
return;
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "FRONT_ID_JPEG" + timeStamp;
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.nyabaapplication.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
activityResultLauncher.launch(takePictureIntent);
}
}
}
}
Front Scan XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:background="#color/background"
android:orientation="vertical"
android:padding="30dp"
tools:context=".Front_Scan">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:gravity="center"
android:text="Scan Front Side"
android:textAlignment="center"
android:textAllCaps="false"
android:textColor="#color/yellow"
android:textSize="28sp"
android:textStyle="bold" />
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_gravity="center"
android:layout_marginTop="60dp"
app:cardBackgroundColor="#color/background"
app:cardCornerRadius="22dp"
app:cardElevation="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center">
<ImageView
android:id="#+id/Image_id_front"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:scaleType="fitXY"
android:src="#drawable/id_front" />
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
<android.widget.Button
android:id="#+id/Front_imgCapture_again"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#drawable/flag_transparent"
android:text="Scan Again"
android:onClick="scanAgain"
android:layout_marginTop="8dp"
android:textAllCaps="false"
android:textColor="#color/yellow"
android:textSize="17sp"
android:visibility="gone" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="Position your document inside the frame. Make sure that all the data is clearly visible."
android:textAlignment="center"
android:textColor="#color/gray"
android:textSize="16sp"/>
<android.widget.Button
android:id="#+id/imgCapture_front"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="60dp"
android:background="#drawable/button_style_ylo"
android:text="Scan Now"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="19sp"
android:textStyle="bold"
android:visibility="visible"/>
<android.widget.Button
android:id="#+id/front_next"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="-50dp"
android:background="#drawable/button_style_ylo"
android:text="Next Step"
android:textAllCaps="false"
android:textColor="#color/white"
android:textSize="19sp"
android:textStyle="bold"
android:onClick="next"
android:visibility="invisible"/>
</LinearLayout>
Here is Back side-scan activity
public class back_scan extends AppCompatActivity {
ActivityResultLauncher<Intent> activityResultLauncher1;
private static final int PERMISSION_CODE = 101;
public String currentPhotoPath1;
Button backImgCap;
Button backImgCapAgain;
Button backNext;
ImageView backImg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_back_scan);
backImg = findViewById(R.id.Image_id_back);
backImgCap = findViewById(R.id.imgCapture_back);
backImgCap.setVisibility(VISIBLE);
backImgCapAgain = findViewById(R.id.Back_imgCapture_again);
backImgCapAgain.setVisibility(GONE);
backNext = findViewById(R.id.back_next);
backNext.setVisibility(INVISIBLE);
activityResultLauncher1 = registerForActivityResult(new ActivityResultContracts.StartActivityForResult()
, new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
File f1 = new File(currentPhotoPath1);
backImgCapAgain.setVisibility(VISIBLE);
backImgCap.setVisibility(INVISIBLE);
backNext.setVisibility(VISIBLE);
backImg.setImageURI(Uri.fromFile(f1));
}
}
});
backImgCap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//if system os is >= marshmallow, request runtime permission
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CAMERA) ==
PackageManager.PERMISSION_DENIED ||
checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_DENIED) {
//permission not enable, request it
String[] permission = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
//show popup to request permissions
requestPermissions(permission, PERMISSION_CODE);
} else {
//permission already given
dispatchTakePictureIntent1();
}
} else {
//system os < marshmallow
dispatchTakePictureIntent1();
}
}
});
}
public void next1(View view) {
Intent myIntent = new Intent(back_scan.this, scanned_copy.class);
back_scan.this.startActivity(myIntent);
finish();
}
public void scanAgainBack(View view) {
clearMyFiles1();
onCreateLayouts1();
backImg.setImageDrawable(getResources().getDrawable(R.drawable.id_back));
}
void clearMyFiles1() {
File imgFile1 = new File(currentPhotoPath1);
if (imgFile1 != null) {
imgFile1.delete();
}
}
public void onCreateLayouts1() {
backImgCap.setVisibility(VISIBLE);
backImgCapAgain.setVisibility(GONE);
backNext.setVisibility(INVISIBLE);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSION_CODE:
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
dispatchTakePictureIntent1();
} else {
Toast.makeText(this, "permission denied...", Toast.LENGTH_SHORT).show();
}
return;
}
}
private File createImageFile1() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "BACK_ID_JPEG_" + timeStamp;
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath1 = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent1() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile1();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.nyabaapplication.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
activityResultLauncher1.launch(takePictureIntent);
}
}
}
}
Back Scan XML file is almost same as front side XML
Here is the activity that shows both sides of the ID Card together
public class scanned_copy extends AppCompatActivity {
Button finishBtn;
ImageView scanIDBack;
ImageView scanIDFront;
String storeFrontScan;
String storeBackScan="BACK_ID_JPEG.jpg";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scanned_copy);
readFrontImgFromFile();
readBackImgFromFile();
scanIDBack = findViewById(R.id.Scan_id_back);
scanIDFront = findViewById(R.id.Scan_id_front);
finishBtn = findViewById(R.id.ScanfinishBtn);
finishBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(scanned_copy.this, WellDone.class);
startActivity(intent);
finish();
}
});
}
public void readFrontImgFromFile()
{
File imgFileFront = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES)+storeFrontScan);
if(imgFileFront.exists())
{
scanIDFront.setImageURI(Uri.fromFile(imgFileFront));
}
}
public void readBackImgFromFile()
{
File imgFileBack = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES)+storeBackScan);
if(imgFileBack.exists())
{
scanIDBack.setImageURI(Uri.fromFile(imgFileBack));
}
}
}
The XML File of this Activity
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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:background="#color/background"
android:scrollbars="none"
tools:context=".scanned_copy">
<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:layout_gravity="center_horizontal"
android:layout_marginTop="16dp"
android:gravity="center"
android:text="Scanned ID Card"
android:textAlignment="center"
android:textAllCaps="false"
android:textColor="#color/yellow"
android:textSize="28sp"
android:textStyle="bold" />
<ProgressBar
android:id="#+id/progressBar4"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="174dp"
android:layout_height="26dp"
android:layout_gravity="center"
android:layout_marginTop="16dp"
android:progress="85"
android:progressTint="#color/yellow" />
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginHorizontal="20dp"
app:cardBackgroundColor="#color/primary_gray"
app:cardCornerRadius="22dp"
app:cardElevation="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:padding="10dp"
android:text="Have a final check if all data is clearly visible and that it matches the information you have entered in previous steps."
android:textAlignment="center"
android:textColor="#color/gray"
android:textSize="16sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_gravity="center_horizontal"
android:text="Front Side"
android:textSize="26dp"
android:textStyle="bold"
android:textColor="#color/light_gray"
android:layout_marginTop="30dp"/>
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:layout_marginHorizontal="10dp"
app:cardBackgroundColor="#color/primary_gray"
app:cardCornerRadius="22dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center">
<ImageView
android:id="#+id/Scan_id_front"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:scaleType="fitXY"
android:src="#drawable/id_front" />
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_gravity="center_horizontal"
android:text="Back Side"
android:textSize="26dp"
android:textStyle="bold"
android:textColor="#color/light_gray"
android:layout_marginTop="30dp"/>
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_marginHorizontal="10dp"
app:cardBackgroundColor="#color/primary_gray"
app:cardCornerRadius="22dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center">
<ImageView
android:id="#+id/Scan_id_back"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:scaleType="fitXY"
android:src="#drawable/id_back" />
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
<android.widget.Button
android:id="#+id/ScanfinishBtn"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginBottom="40dp"
android:background="#drawable/button_style_ylo"
android:text="Finish Verification"
android:textAllCaps="false"
android:textColor="#color/white"
android:layout_gravity="center_horizontal"
android:textSize="19sp"
android:textStyle="bold"/>
</LinearLayout>
</ScrollView>
You have the path to the files that were saved. Pass them through to the last activity as intent extras.
https://developer.android.com/training/basics/firstapp/starting-activity

MaterialCardView is in front of NavigationView. How can I send it behind? [Android Studio]

I added in my activity_main.xml a MaterialCardView button com.google.android.material.card.MaterialCardView & navigation drawer com.google.android.material.navigation.NavigationView.
How can I send MaterialCardView (#+id/cleanButton) behind the NavigationView (#+id/navigation_view)?
Here is how it looks
[This is full 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"
android:id="#+id/main_layout"
tools:context="com.d4rk.cleaner.MainActivity">
<androidx.appcompat.widget.AppCompatImageView
android:id="#+id/clean"
android:layout_width="90dp"
android:layout_height="64dp"
app:srcCompat="#drawable/ic_clean"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"/>
<ScrollView
android:id="#+id/fileScrollView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="24dp"
android:layout_marginTop="16dp"
android:focusable="false"
android:background="#drawable/card"
android:layout_marginEnd="24dp"
android:layout_marginBottom="16dp"
app:layout_constraintBottom_toTopOf="#+id/cleanButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/scanProgress">
<LinearLayout
android:id="#+id/fileListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:orientation="vertical"/>
</ScrollView>
<com.google.android.material.card.MaterialCardView
android:id="#+id/cleanButton"
android:layout_width="152dp"
android:layout_height="50dp"
android:layout_marginBottom="5dp"
android:onClick="clean"
app:cardCornerRadius="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/scanProgress"
app:layout_constraintVertical_bias="0.045"
tools:ignore="UsingOnClickInXml">
<androidx.appcompat.widget.AppCompatImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:srcCompat="#drawable/ic_text_clean" />
</com.google.android.material.card.MaterialCardView>
<androidx.core.widget.ContentLoadingProgressBar
android:id="#+id/scanProgress"
android:layout_width="150dp"
android:layout_height="144dp"
android:indeterminate="false"
android:progressDrawable="#drawable/circular"
app:layout_constraintBottom_toBottomOf="#+id/ScanTextView"
app:layout_constraintEnd_toEndOf="#+id/ScanTextView"
app:layout_constraintStart_toStartOf="#+id/ScanTextView"
app:layout_constraintTop_toTopOf="#+id/ScanTextView"/>
<com.google.android.material.textview.MaterialTextView
android:id="#+id/ScanTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:layout_marginBottom="32dp"
android:text="#string/main_progress"
android:textColor="#color/colorGoogleGreen"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="#+id/statusTextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/statusTextView"
app:layout_constraintVertical_bias="0.0" />
<com.google.android.material.textview.MaterialTextView
android:id="#+id/statusTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/main_status"
android:textColor="#color/colorAccent"
android:textSize="36sp"
android:gravity="center"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.36"/>
<androidx.drawerlayout.widget.DrawerLayout
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:clipToPadding="false"
android:minWidth="15dp">
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="30dp"
android:layout_height="30dp"
android:autoLink="all"
android:clickable="true"
android:focusable="true"
android:text="#string/adfly"
android:textColor="#2E7D32"
android:textColorHighlight="#color/colorPrimary"
android:textColorHint="#color/colorPrimary"
android:textColorLink="#color/colorPrimary"
android:textIsSelectable="false"
app:drawableStartCompat="#drawable/ic_face"
tools:ignore="TextContrastCheck,TouchTargetSizeCheck" />
<androidx.appcompat.widget.AppCompatImageView
android:layout_width="40dp"
android:layout_height="36dp"
android:layout_gravity="center"
android:src="#drawable/ic_toolbar_d4rk"/>
<androidx.appcompat.widget.AppCompatImageView
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
app:srcCompat="#drawable/ic_cleaner"/>
</androidx.appcompat.widget.Toolbar>
<androidx.appcompat.widget.AppCompatImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="4dp"
android:layout_marginEnd="20dp"
android:layout_marginStart="20dp"
app:srcCompat="#drawable/ic_line"
tools:ignore="MissingConstraints"/>
</LinearLayout>
</ScrollView>
<com.google.android.material.navigation.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/header"
app:menu="#menu/drawer_menu">
</com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Here is my ActivityMain.java
public class MainActivity extends AppCompatActivity {
final ConstraintSet constraintSet = new ConstraintSet();
static boolean running = false;
SharedPreferences prefs;
LinearLayout fileListView;
ScrollView fileScrollView;
DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
NavigationView navigationView;
ProgressBar scanPBar;
TextView progressText;
TextView statusText;
ConstraintLayout layout;
#SuppressLint("NonConstantResourceId")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fileListView = findViewById(R.id.fileListView);
fileScrollView = findViewById(R.id.fileScrollView);
scanPBar = findViewById(R.id.scanProgress);
progressText = findViewById(R.id.ScanTextView);
statusText = findViewById(R.id.statusTextView);
layout = findViewById(R.id.main_layout);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
constraintSet.clone(layout);
setUpToolbar();
navigationView = findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(menuItem -> {
switch (menuItem.getItemId())
{
case R.id.nav_home:
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
break;
case R.id.nav_drawer_settings:
intent = new Intent (MainActivity.this, SettingsActivity.class);
startActivity(intent);
break;
case R.id.nav_drawer_changelog:
intent = new Intent (MainActivity.this, ChangelogActivity.class);
startActivity(intent);
break;
case R.id.nav_drawer_whitelist:
intent = new Intent (MainActivity.this, WhitelistActivity.class);
startActivity(intent);
break;
case R.id.nav_drawer_clipboard_cleaner:
intent = new Intent (MainActivity.this, ClipboardActivity.class);
startActivity(intent);
break;
case R.id.nav_drawer_about:
intent = new Intent (MainActivity.this, AboutActivity.class);
startActivity(intent);
break;
case R.id.nav_share:{
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "https://play.google.com/store/apps/details?id=com.d4rk.cleaner";
String shareSub = "Try now";
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, shareSub);
sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share using"));
}
break;
}
return false;
});
}
public void setUpToolbar() {
drawerLayout = findViewById(R.id.drawerLayout);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setTitle(null);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.app_name, R.string.app_name);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
}
public final void clean(View view) {
requestWriteExternalPermission();
if (!running) {
if (!prefs.getBoolean("one_click", false))
new AlertDialog.Builder(this,R.style.MyAlertDialogTheme)
.setTitle(R.string.main_select_task)
.setMessage(R.string.main_select_task_description)
.setPositiveButton(R.string.main_clean, (dialog, whichButton) -> new Thread(()-> scan(true)).start())
.setNegativeButton(R.string.main_analyze, (dialog, whichButton) -> new Thread(()-> scan(false)).start()).show();
else new Thread(()-> scan(true)).start();
}
}
public void animateBtn() {
TransitionManager.beginDelayedTransition(layout);
constraintSet.clear(R.id.cleanButton,ConstraintSet.TOP);
constraintSet.clear(R.id.statusTextView,ConstraintSet.BOTTOM);
constraintSet.setMargin(R.id.statusTextView,ConstraintSet.TOP,50);
constraintSet.applyTo(layout);
}
#SuppressLint("SetTextI18n")
private void scan(boolean delete) {
Looper.prepare();
running = true;
reset();
File path = Environment.getExternalStorageDirectory();
FileScanner fs = new FileScanner(path);
fs.setEmptyDir(prefs.getBoolean("empty", false));
fs.setAutoWhite(prefs.getBoolean("auto_white", true));
fs.setDelete(delete);
fs.setCorpse(prefs.getBoolean("corpse", false));
fs.setGUI(this);
fs.setUpFilters(prefs.getBoolean("generic", true),
prefs.getBoolean("aggressive", false),
prefs.getBoolean("apk", false));
if (path.listFiles() == null) {
TextView textView = printTextView(printTextView(), Color.RED);
runOnUiThread(() -> fileListView.addView(textView));
}
runOnUiThread(() -> {
animateBtn();
statusText.setText(getString(R.string.main_status_running));
});
long kilobytesTotal = fs.startScan();
runOnUiThread(() -> {
scanPBar.setProgress(scanPBar.getMax());
progressText.setText("100%");
});
runOnUiThread(() -> {
if (delete) {
statusText.setText(getString(R.string.main_freed) + " " + convertSize(kilobytesTotal));
} else {
statusText.setText(getString(R.string.main_found) + " " + convertSize(kilobytesTotal));
}
});
fileScrollView.post(() -> fileScrollView.fullScroll(ScrollView.FOCUS_DOWN));
running = false;
Looper.loop();
}
private String printTextView() {
return null;
}
private synchronized TextView printTextView(String text, int color) {
TextView textView = new TextView(MainActivity.this);
textView.setTextColor(color);
textView.setText(text);
textView.setPadding(3,3,3,3);
return textView;
}
private String convertSize(long length) {
final DecimalFormat format = new DecimalFormat("#.##");
final long MiB = 1024 * 1024;
final long KiB = 1024;
if (length > MiB) {
return format.format(length / MiB) + " MB";
}
if (length > KiB) {
return format.format(length / KiB) + " KB";
}
return format.format(length) + " B";
}
synchronized TextView displayPath(File file) {
TextView textView = printTextView(file.getAbsolutePath(), getResources().getColor(R.color.colorAccent));
runOnUiThread(() -> fileListView.addView(textView));
fileScrollView.post(() -> fileScrollView.fullScroll(ScrollView.FOCUS_DOWN));
return textView;
}
private synchronized void reset() {
prefs = PreferenceManager.getDefaultSharedPreferences(this);
runOnUiThread(() -> {
fileListView.removeAllViews();
scanPBar.setProgress(0);
scanPBar.setMax(1);
});
}
public synchronized void requestWriteExternalPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.MANAGE_EXTERNAL_STORAGE},
1);
if (!Environment.isExternalStorageManager()) {
Toast.makeText(this, "Permission needed!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE},
1);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1 &&
grantResults.length > 0 &&
grantResults[0] != PackageManager.PERMISSION_GRANTED)
prompt();
}
public final void prompt() {
Intent intent = new Intent(this, PromptActivity.class);
startActivity(intent);
}
}
The root layout should be DrawerLayout, and you need to move the current ConstraintLayout within the DrawerLayout
The skeleton of the layout should be something like:
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout 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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Main screen layout -->
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<!-- Drawer layout -->
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/navigation_header_layout"
app:menu="#menu/navigation_menu" />
</androidx.drawerlayout.widget.DrawerLayout>
And you can build views on the main screen within the ConstraintLayout

android repeating alam is not getting stopped when stop button is clicked

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.

how to Sending sms in android

I am developing an application using sms, my requirement is 1) send sms with static values 2)whenever we click on edit button we can change values and send sms , I can do both of them successfully but my third requirement is to send sms only when click on edit and change values click on submit buttons, without change value I do not want send sms. I want when click on edit button then only send sms, i tried with if(editBtn.isSelected) but it is not working. please tell any solution
my code is
xml file
<LinearLayout 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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:orientation="vertical" >
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editBtn"
android:text="EDIT"
android:textColor="#00FF00"
android:onClick="editListener"/>
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="NUMBER"
android:textSize="20dip"/>
<EditText android:layout_width="150dip"
android:layout_height="wrap_content"
android:id="#+id/numberEdit"
android:text="8989897979"
android:clickable="false"
android:cursorVisible="false"
android:focusable="false"
android:focusableInTouchMode="false"
/>
</LinearLayout>
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MESSAGE"
android:textSize="20dip"/>
<EditText android:layout_width="150dip"
android:layout_height="wrap_content"
android:id="#+id/messageEdit"
android:text="HAI HOW R U"
android:clickable="false"
android:cursorVisible="false"
android:focusable="false"
android:focusableInTouchMode="false"
/>
</LinearLayout>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/subBtn"
android:text="SUBMIT"/>
</LinearLayout>
Activty
public class MainActivity extends Activity {
private EditText contactEdit;
private EditText messageEdit;
private Button submitBtn;
private Button editBtn;
String contact;
String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactEdit = (EditText)findViewById(R.id.numberEdit);
messageEdit = (EditText)findViewById(R.id.messageEdit);
submitBtn = (Button)findViewById(R.id.subBtn);
editBtn = (Button)findViewById(R.id.editBtn);
if(editBtn.isSelected()){
submitBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
contact = contactEdit.getText().toString();
message = messageEdit.getText().toString();
try{
SmsManager manger = SmsManager.getDefault();
manger.sendTextMessage(contact, null, message, null,
null);
Toast.makeText(getApplicationContext(), "SMS SENT",
100).show();
}
catch(Exception e){
Toast.makeText(getApplicationContext(), "SMS NOT
SEND", 100).show();
e.printStackTrace();
}
}
});
}
else {
Toast.makeText(getApplicationContext(), "NOT EDITED", 100).show();
}
editBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
changeEdit();
}
});
}
private void changeEdit(){
contactEdit.setClickable(true);
contactEdit.setCursorVisible(true);
contactEdit.setFocusable(true);
contactEdit.setFocusableInTouchMode(true);
messageEdit.setClickable(true);
messageEdit.setCursorVisible(true);
messageEdit.setFocusable(true);
messageEdit.setFocusableInTouchMode(true);
}
}
Try to use OnTouchListener for the edittext
sample,
editBtn.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
changeEdit();
return true;
}
});
if its not working
Create a boolean variable Globally and make it true if u touched onto the edittext,
//In grobal
boolean e_clicked = false;
//Inside the Edittext onTouchListener
e_clicked=true;
and check
if(e_clicked)
{
// your sms send action
}
try this
public class AlarmReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
#Override
public void onReceive(Context context, Intent intent) {
Intent intent=new Intent(context,Service.class);
//get lat/lng and pass it or get from service if u want
intent.putExtra("lat","lat");
intent.putExtra("lon","lng");
context.startService(intent);
}
}
public void SetAlarm(Context context) {
AlarmManager am = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, AlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.MINUTE, 10);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
calendar.getTimeInMillis(), pi);
}

Categories