0% found this document useful (0 votes)
83 views15 pages

Android Code

This document contains code for an Android application that provides safety features. It includes: - The AndroidManifest.xml file which declares permissions, activities, and a foreground service. - XML layout files for the main activity, registration activity, and splash screen that set up the user interfaces. - The MainActivity Java code which handles permissions, shared preferences, and starting/stopping the foreground service. The app allows a user to register an emergency contact number, and has buttons to start and stop a foreground service that will send SMS alerts to that number if needed. It uses permissions for location, SMS, and running a foreground service.

Uploaded by

Aditya Borle
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
83 views15 pages

Android Code

This document contains code for an Android application that provides safety features. It includes: - The AndroidManifest.xml file which declares permissions, activities, and a foreground service. - XML layout files for the main activity, registration activity, and splash screen that set up the user interfaces. - The MainActivity Java code which handles permissions, shared preferences, and starting/stopping the foreground service. The app allows a user to register an emergency contact number, and has buttons to start and stop a foreground service that will send SMS alerts to that number if needed. It uses permissions for location, SMS, and running a foreground service.

Uploaded by

Aditya Borle
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Program code

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.bhushan.wsafety">

<uses-feature
android:name="android.hardware.sensor.accelerometer"
android:required="true" />

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.SEND_SMS"/>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Wsafety">
<activity android:name=".RegisterNumberActivity"></activity>
<activity android:name=".SplashScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
<activity android:name=".MainActivity"/>

<service
android:name=".ServiceMine"
android:enabled="true"
android:foregroundServiceType="location" />
</application>

</manifest>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayoutxmlns: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="@drawable/background"
tools:context=".MainActivity">

<View
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentEnd="true"
android:onClick="PopupMenu"
android:clickable="true"
android:focusable="true"
android:layout_margin="20dp"
android:background="@drawable/ic_baseline_more_vert_24"/>

<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center">

<TextView
android:id="@+id/textNum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:fontFamily="@font/varela_round"
android:text="SOS Will Be Sent To\n"

android:textAlignment="center"
android:textSize="23sp"
android:textStyle="bold|italic" />

<com.google.android.material.button.MaterialButton
android:id="@+id/start"
android:layout_width="200dp"
android:layout_height="60dp"
android:layout_below="@+id/textNum"
android:layout_marginTop="13dp"
android:layout_marginBottom="10dp"
android:backgroundTint="#ffffff"
android:gravity="center"

android:onClick="startServiceV"
android:text="Start"
android:textColor="@color/black"
app:cornerRadius="10dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<com.google.android.material.button.MaterialButton
android:id="@+id/stop"
android:layout_width="200dp"
android:layout_height="60dp"
android:layout_below="@+id/start"
android:layout_marginTop="26dp"
android:backgroundTint="#ffffff"
android:gravity="center"
android:onClick="stopService"
android:text="stop"
android:textColor="@color/black"
app:cornerRadius="10dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/start" />

</RelativeLayout>

</RelativeLayout>
activity_register_number.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayoutxmlns: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:background="@drawable/background"
android:layout_height="match_parent"
tools:context=".RegisterNumberActivity">

<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Enter Number To\nSend SMS\nin\nEMERGENCY!"
android:textSize="28sp"
android:textStyle="italic|bold"
android:fontFamily="@font/varela_round"
android:textColor="@color/black"
android:id="@+id/text1"
android:textAlignment="center"/>

<com.google.android.material.textfield.TextInputLayout
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_margin="10dp"
android:id="@+id/number"
android:layout_below="@id/text1"
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:hint="Number"
android:inputType="numberDecimal"
android:id="@+id/numberEdit"
android:maxLength="10"
android:fontFamily="@font/varela_round"
android:textAlignment="center"
android:layout_height="match_parent"/>
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.button.MaterialButton
android:layout_width="200dp"
android:layout_height="60dp"
android:layout_margin="10dp"
android:onClick="saveNumber"
android:textColor="@color/black"
app:cornerRadius="10dp"
android:layout_below="@id/number"
android:layout_centerHorizontal="true"
android:fontFamily="@font/varela_round"
android:backgroundTint="#ffffff"
android:text="Finish"/>

</RelativeLayout>

</RelativeLayout>
activity_splash_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayoutxmlns: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=".SplashScreen">

<ImageView
android:id="@+id/girlVector"
android:layout_width="130dp"
android:layout_height="200dp"
android:layout_centerInParent="true"
android:src="@drawable/girl_vector"
android:layout_marginBottom="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Feel Safe Everywhere"
android:fontFamily="@font/varela_round"
android:textSize="28sp"
android:layout_below="@id/girlVector"
app:layout_constraintTop_toBottomOf="@id/girlVector"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_centerHorizontal="true"/>

</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package com.bhushan.wsafety;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.PopupMenu;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.google.android.material.snackbar.Snackbar;
import java.util.Map;
import java.util.function.BiConsumer;

public class MainActivityextends AppCompatActivity {

@Override
protected void onResume() {
super.onResume();
SharedPreferencessharedPreferences =
getSharedPreferences("MySharedPref",MODE_PRIVATE);
String ENUM = sharedPreferences.getString("ENUM","NONE");
if(ENUM.equalsIgnoreCase("NONE")){
startActivity(new Intent(this,RegisterNumberActivity.class));
}else {
TextViewtextView = findViewById(R.id.textNum);
textView.setText("SOS Will Be Sent To\n"+ENUM);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.O) {
if (android.os.Build.VERSION.SDK_INT>= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("MYID",
"CHANNELFOREGROUND", NotificationManager.IMPORTANCE_DEFAULT);

NotificationManager m = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
m.createNotificationChannel(channel);
}
}

private ActivityResultLauncher<String[]>multiplePermissions=
registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), new
ActivityResultCallback<Map<String, Boolean>>() {
@Override
public void onActivityResult(Map<String, Boolean> result) {

for (Map.Entry<String,Boolean> entry : result.entrySet())


if(!entry.getValue()){
Snackbarsnackbar = Snackbar.make(findViewById(android.R.id.content),"Permission Must
Be Granted!", Snackbar.LENGTH_INDEFINITE);
snackbar.setAction("Grant Permission", new View.OnClickListener() {
@Override
public void onClick(View v) {
multiplePermissions.launch(new String[]{entry.getKey()});
snackbar.dismiss();
}
});
snackbar.show();
}

});
public void stopService(View view) {

Intent notificationIntent = new Intent(this,ServiceMine.class);


notificationIntent.setAction("stop");
if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.O) {
getApplicationContext().startForegroundService(notificationIntent);
Snackbar.make(findViewById(android.R.id.content),"Service Stopped!",
Snackbar.LENGTH_LONG).show();
}
}

public void startServiceV(View view) {

if (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) ==
PackageManager.PERMISSION_GRANTED&&ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED&&ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
Intent notificationIntent = new Intent(this,ServiceMine.class);
notificationIntent.setAction("Start");
if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.O) {
getApplicationContext().startForegroundService(notificationIntent);
Snackbar.make(findViewById(android.R.id.content),"Service Started!",
Snackbar.LENGTH_LONG).show();
}
}else{
multiplePermissions.launch(new String[]
{Manifest.permission.SEND_SMS,Manifest.permission.ACCESS_COARSE_LOCATION,Ma
nifest.permission.ACCESS_FINE_LOCATION});
}

public void PopupMenu(View view) {


PopupMenupopupMenu = new PopupMenu(MainActivity.this,view);
popupMenu.getMenuInflater().inflate(R.menu.popup,popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public booleanonMenuItemClick(MenuItem item) {
if(item.getItemId() == R.id.changeNum){
startActivity(new Intent(MainActivity.this,RegisterNumberActivity.class));
}
return true;
}
});
popupMenu.show();
}
}
RegisterNumberActivity

package com.bhushan.wsafety;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.google.android.material.textfield.TextInputEditText;

public class RegisterNumberActivityextends AppCompatActivity {

TextInputEditTextnumber;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_number);

number = findViewById(R.id.numberEdit);
}

public void saveNumber(View view) {


String numberString = number.getText().toString();
if(numberString.length()==10){
SharedPreferencessharedPreferences =
getSharedPreferences("MySharedPref",MODE_PRIVATE);
SharedPreferences.EditormyEdit = sharedPreferences.edit();
myEdit.putString("ENUM", numberString);
myEdit.apply();
RegisterNumberActivity.this.finish();
}else {
Toast.makeText(this, "Enter Valid Number!", Toast.LENGTH_SHORT).show();
}
}
ServiceMine.java
package com.bhushan.wsafety;

import android.Manifest;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.IBinder;
import android.telephony.SmsManager;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import com.github.tbouron.shakedetector.library.ShakeDetector;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
public class ServiceMine extends Service {

booleanisRunning= false;

FusedLocationProviderClientfusedLocationClient;

@Nullable
@Override
public IBinderonBind(Intent intent) {
return null;
}

SmsManagermanager = SmsManager.getDefault();
String myLocation;
@Override
public void onCreate() {
super.onCreate();

fusedLocationClient= LocationServices.getFusedLocationProviderClient(this);
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED&&ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
fusedLocationClient.getLastLocation()
.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
// Logic to handle location object
location.getAltitude();
location.getLongitude();
myLocation= "http://maps.google.com/maps?q=loc:"+location.getLatitude()
+","+location.getLongitude();
}else {
myLocation= "Unable to Find Location :(";
}
}
});

ShakeDetector.create(this, () -> {

//if you want to play siren sound you can do it here


//just create music player and play here
//before playing sound please set volume to max

SharedPreferencessharedPreferences =
getSharedPreferences("MySharedPref",MODE_PRIVATE);
String ENUM = sharedPreferences.getString("ENUM","NONE");
if(!ENUM.equalsIgnoreCase("NONE")){
manager.sendTextMessage(ENUM,null,"Im in Trouble!\nSending My Location :\
n"+myLocation,null,null);
}

});

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

if (intent.getAction().equalsIgnoreCase("STOP")) {
if(isRunning) {
this.stopForeground(true);
this.stopSelf();
}
} else {

Intent notificationIntent = new Intent(this, MainActivity.class);


PendingIntentpendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

if (android.os.Build.VERSION.SDK_INT>=
android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("MYID",
"CHANNELFOREGROUND", NotificationManager.IMPORTANCE_DEFAULT);

NotificationManager m = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
m.createNotificationChannel(channel);

Notification notification = new Notification.Builder(this, "MYID")


.setContentTitle("Women Safety")
.setContentText("Shake Device to Send SOS")
.setSmallIcon(R.drawable.girl_vector)
.setContentIntent(pendingIntent)
.build();
this.startForeground(115, notification);
isRunning= true;
return START_NOT_STICKY;
}
}

return super.onStartCommand(intent,flags,startId);

@Override
public void onDestroy() {
super.onDestroy();
}
}
SplashScreen.java
package com.bhushan.wsafety;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;

public class SplashScreenextends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);

new CountDownTimer(1000,500){
@Override
public void onTick(long millisUntilFinished) {

@Override
public void onFinish() {
startActivity(new Intent(SplashScreen.this,MainActivity.class));
SplashScreen.this.finish();
}
}.start();

}
}
background.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

<gradient android:type="linear" android:startColor="#E205524F"


android:endColor="#EB3249C5" android:angle="90"/>

</shape>
Colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<colorname="purple_200">#FFBB86FC</color>
<colorname="purple_500">#FF6200EE</color>
<colorname="purple_700">#FF3700B3</color>
<colorname="teal_200">#FF03DAC5</color>
<colorname="teal_700">#FF018786</color>
<colorname="black">#FF000000</color>
<colorname="white">#FFFFFFFF</color>
</resources>

You might also like