How do I make my application run on background? - android

My application is all about an EMERGENCY SMS where I just click my volume button and a simulated Message is sent to a certain Phone Number.
I wanted to know how I can make my application run on background when I want and close it whenever I want?
Hoping for your kind help, my Code is this:
public class MainActivity extends Activity {
private final static int SEND_SMS_PERMISSION_REQUEST_CODE = 111;
private Button sendMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendMessage = findViewById(R.id.send_message);
final EditText phone = findViewById(R.id.phone_no);
final EditText message = findViewById(R.id.message);
sendMessage.setEnabled(false);
if (checkPermission(Manifest.permission.SEND_SMS)) {
sendMessage.setEnabled(true);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, SEND_SMS_PERMISSION_REQUEST_CODE);
}
sendMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg = message.getText().toString();
String phonenumber = phone.getText().toString();
if (!TextUtils.isEmpty(msg) && !TextUtils.isEmpty(phonenumber)) {
if (checkPermission(Manifest.permission.SEND_SMS)) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(String.valueOf(phone), null, msg, null, null);
} else {
Toast.makeText(MainActivity.this, "Permission denied", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, "Enter a message and a phone number", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) {
final EditText phone = findViewById(R.id.phone_no);
final EditText message = findViewById(R.id.message);
String msg = message.getText().toString();
String phonenumber = phone.getText().toString();
if (!TextUtils.isEmpty(msg) && !TextUtils.isEmpty(phonenumber)) {
if (checkPermission(Manifest.permission.SEND_SMS)) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(String.valueOf(phone), null, msg, null, null);
} else {
Toast.makeText(MainActivity.this, "Permission denied", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, "Enter a message and a phone number", Toast.LENGTH_SHORT).show();
}
return true;
} else
return super.onKeyDown(keyCode, event);
}
private boolean checkPermission(String permission) {
int checkPermission = ContextCompat.checkSelfPermission(this, permission);
return checkPermission == PackageManager.PERMISSION_GRANTED;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case SEND_SMS_PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
sendMessage.setEnabled(true);
}
break;
}
}
}

You have to start a service in your Application class to run it always. If you do that, your service will be always running.Even though user terminates your app from task manager or force stop your app, it will start running again in Background.
You can get more info about service from this link:
https://developer.android.com/training/run-background-service/create-service

Related

My text to speech do not work, when i give speech to text as input in android chatbot

I made a chatbot using online tutorial, Now apart from writing in edit text as input I am using voice recognition also. but the problem is the tts do not work when I am pressing the voice recognition button. I dont know what is the problem I used various methods. tts works fine while sending text from edit text field. here is the sample for two codes in main activity. First code is for sending text via send button and works fine. Second code is the wone I use stt to chat and tts do not work. Need help to fix the problem. Thanks in advance.
public class MainActivity extends AppCompatActivity {
private ListView mListView;
private FloatingActionButton mButtonSend;
private EditText mEditTextMessage;
private ImageView mImageView;
public Bot bot;
public static Chat chat;
private ChatMessage.ChatMessageAdapter mAdapter;
public Button buSpeak;
public TextToSpeech tts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR){
tts.setLanguage(Locale.US);
}
}
});
mListView = (ListView) findViewById(R.id.listView);
mButtonSend = (FloatingActionButton) findViewById(R.id.btn_send);
mEditTextMessage = (EditText) findViewById(R.id.et_message);
mImageView = (ImageView) findViewById(R.id.iv_image);
mAdapter = new ChatMessage.ChatMessageAdapter(this, new ArrayList<ChatMessage>());
mListView.setAdapter(mAdapter);
buSpeak = (Button)findViewById(R.id.buSpeak);
CheckUserPermsions();
//chat button
mButtonSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String message = mEditTextMessage.getText().toString();
//bot
String response = chat.multisentenceRespond(mEditTextMessage.getText().toString());
if (TextUtils.isEmpty(message)) {
return;
}
sendMessage(message);
mimicOtherMessage(response);
mEditTextMessage.setText("");
mListView.setSelection(mAdapter.getCount() - 1);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
tts.speak(response, TextToSpeech.QUEUE_FLUSH,null,null);
}else{
tts.speak(response, TextToSpeech.QUEUE_FLUSH,null);
}
}
});
and the code for Using voice recognition, here the tts do not work
public void buSpeak(View view) {
startVoiceRecognitionActivity();
}
private void startVoiceRecognitionActivity() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass().getPackage().getName());
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
//since you only want one, only request 1
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-US");
startActivityForResult(intent, 1234);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK){
tts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR){
tts.setLanguage(Locale.US);
}
}
});
//pull all of the matches
ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String topResult = matches.get(0);
EditText AutoText = (EditText) findViewById(R.id.et_message);
AutoText.setText(topResult);
String message = AutoText.getText().toString();
//bot
String response = chat.multisentenceRespond(AutoText.getText().toString());
if (TextUtils.isEmpty(response)) {
return;
}
sendMessage(message);
mimicOtherMessage(response);
AutoText.setText("");
mListView.setSelection(mAdapter.getCount() - 1);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
tts.speak(response, TextToSpeech.QUEUE_FLUSH,null,null);
}else{
tts.speak(response, TextToSpeech.QUEUE_FLUSH,null);
}
}
}
public void CheckUserPermsions(){
if ( Build.VERSION.SDK_INT >= 23){
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED ){
requestPermissions(new String[]{
android.Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE_ASK_PERMISSIONS);
return ;
}
}
}
//get acces to location permsion
final private int REQUEST_CODE_ASK_PERMISSIONS = 123;
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
} else {
// Permission Denied
Toast.makeText( this,"denail" , Toast.LENGTH_SHORT)
.show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
public void onPause(){
if(tts !=null){
tts.stop();
tts.shutdown();
}
super.onPause();
}
}
just call this method and pass your text in this method
public void textToSpeech(String message){
if (result==TextToSpeech.LANG_NOT_SUPPORTED ||result==TextToSpeech.LANG_MISSING_DATA){
Toast.makeText(Activity.this, "Language is Not Supported", Toast.LENGTH_SHORT).show();
}else {
String text=message;
if (text==null||text.equals("")){
text="Text is Empty";
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
textToSpeech.speak(text,TextToSpeech.QUEUE_FLUSH,null,null);
} else {
textToSpeech.speak(text,TextToSpeech.QUEUE_FLUSH,null);
}
}
}
Okay I have solved the problem, Instead of onPause just used onDestry after tts.
and added tts.stop(); in buSpeak button method to stop tts when that button is pressed.
`Code below
public void buSpeak(View view) {
tts.stop();
startVoiceRecognitionActivity();
}
//after all other steps
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}

Measure mobile data usage from a particular point of time

I want to use a service to measure the mobile data used since that service is started but I'm only able to measure the mobile data since device boot using the methods getTotalRxBytes() and getTotalTxBytes() of the TrafficStats class. Can someone help me in measuring the data used when the button is clicked and the service is started?
MainActivity.java
public class MainActivity extends AppCompatActivity {
private long data_limit;
EditText et_data_limit;
Button btn_start_track;
private int STORAGE_PERMISSION_CODE = 23;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
int PRIVATE_MODE = 0;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = MainActivity.this.getSharedPreferences("Data measured", PRIVATE_MODE);
editor = sharedPreferences.edit();
editor.putLong("data", 0);
if(isPermissionAllowed()){
}
else{
requestPermission();
}
et_data_limit = (EditText)findViewById(R.id.et_data_limit);
btn_start_track = (Button)findViewById(R.id.btn_start_track);
btn_start_track.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
data_limit = Long.parseLong(et_data_limit.getText().toString());
data_limit = data_limit * 1024;
Log.i("enter", String.valueOf(data_limit));
//data_limit = data_limit + sharedPreferences.getLong("data", 0);
editor.putLong("data", data_limit);
editor.commit();
Intent intent = new Intent(MainActivity.this, DataTracking.class);
intent.putExtra("data limit", data_limit);
MainActivity.this.startService(intent);
}
});
}
private boolean isPermissionAllowed() {
//Getting the permission status
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_WIFI_STATE);
int result1 = ContextCompat.checkSelfPermission(this, Manifest.permission.CHANGE_WIFI_STATE);
int result2 = ContextCompat.checkSelfPermission(this, Manifest.permission.MODIFY_PHONE_STATE);
//If permission is granted returning true
if (result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED &&
result2 == PackageManager.PERMISSION_GRANTED)
return true;
//If permission is not granted returning false
return false;
}
private void requestPermission(){
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_WIFI_STATE) &&
ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CHANGE_WIFI_STATE) &&
ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.MODIFY_PHONE_STATE)){
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
}
//And finally ask for the permission
ActivityCompat.requestPermissions(this,new String[]{
Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.CHANGE_WIFI_STATE,
Manifest.permission.MODIFY_PHONE_STATE},STORAGE_PERMISSION_CODE);
}
//This method will be called when the user will tap on allow or deny
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if(requestCode == STORAGE_PERMISSION_CODE){
//If permission is granted
if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
//Displaying a toast
Toast.makeText(this,"Permission granted!",Toast.LENGTH_LONG).show();
}else{
//Displaying another toast if permission is not granted
Toast.makeText(this,"Permission denied! App may not work properly",Toast.LENGTH_LONG).show();
}
}
}
}
DataTracking.java
public class DataTracking extends Service {
private long data_limit;
private long data_used;
public DataTracking(){
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
data_limit = intent.getExtras().getLong("data limit");
Log.i("data", String.valueOf(data_limit));
Toast.makeText(getApplicationContext(), "Service started", Toast.LENGTH_SHORT).show();
onHandleIntent(intent);
return Service.START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
protected void onHandleIntent(#Nullable Intent intent) {
TrafficStats trafficStats = new TrafficStats();
long mtx = TrafficStats.getMobileTxBytes();
long mrx = TrafficStats.getMobileRxBytes();
data_used = mtx + mrx;
Toast.makeText(getApplicationContext(), data_used + "-" + data_limit, Toast.LENGTH_SHORT).show();
if(data_used >= data_limit){
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
try{
TelephonyManager telephonyManager = (TelephonyManager) getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
Method setMobileDataStatus = telephonyManager.getClass().getDeclaredMethod("setDataEnabled", boolean.class);
if (null != setMobileDataStatus){
setMobileDataStatus.invoke(telephonyManager, false);
stopSelf();
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
}

Android Smsmanager not sending message more than once

I want to send message everytime I click button but with this code I am able to send message only first time.I can only send message again when I clear App data and cache.
public class MainActivity extends AppCompatActivity {
TextView tapme;
private static final int MY_PERMISSIONS_REQUEST_SEND_SMS = 0;
String phoneNo;
String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tapme = (TextView) findViewById(R.id.tapme);
tapme.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendSMS();
}
});
}
protected void sendSMS() {
phoneNo = "+911333444400";
message = "hi";
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.SEND_SMS)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.", Toast.LENGTH_LONG).show();
return;
}
}
}
}
Where i do wrong? Any help is greatly appreciated.
protected void sendSMS() {
phoneNo = "1";
message = "hi";
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
} else {
SendTextMsg();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
SendTextMsg();
} else {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.", Toast.LENGTH_LONG).show();
}
}
}
}
private void SendTextMsg() {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
}

Recognizer and Text to speech

I want to make an application in the way that when I speak, can answer me without the necessity of press any button. I want that my recordings guard on a string, and then depending of the record, the TTS can answer diferent things. This is my source code.
protected static final int RESULT_SPEACH =1;
private Button record, speak;
TextToSpeech t1;
String SpokedText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mai);
record = (Button) findViewById(R.id.record);
speak = (Button) findViewById(R.id.speak);
speak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reconize = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
try {
startActivityForResult(reconize, RESULT_SPEACH);
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(), "Your divece cannot execute this kind of operation", Toast.LENGTH_LONG);
t.show();
}
}
});
}
public void onActivityResult (int requestCode, int resultCode, Intent Data) {
super.onActivityResult(requestCode,resultCode,Data);
switch (requestCode) {
case RESULT_SPEACH: {
if (resultCode == RESULT_OK && null != Data) {
final String spoked = (RecognizerIntent.EXTRA_RESULTS);
if (spoked == "Good Morning") {
String SpokedText= "Good Morning";
t1.speak(SpokedText, TextToSpeech.QUEUE_FLUSH, null);
} else {
if (spoked== "I need your help") {
String SpokedText= "Alright sir";
t1.speak(SpokedText, TextToSpeech.QUEUE_FLUSH, null);
}
}
}
}
t1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
t1.setLanguage(Locale.getDefault());
}
}
});
}}

android permission READ_SMS granted but not working (even using REQUEST_CODE_ASK_PERMISSIONS)

I want to create an app that reads all inbox sms and when i tap on a message from the list it sends the data to another activity which contains another list to forward the message to.
the reading SMS worked perfectly before i started working on the other activity.
once i finished the whole app , i ran the application on phone but when there are messages it gives me that android app unfortunately stopped but when i delete all threads it start the app normally with no messages in it. what might be the error ??
here is my main activity and i added the read sms permission in Manifest
public class main extends ListActivity {
final private int REQUEST_CODE_ASK_PERMISSIONS = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(getBaseContext(), "android.permission.READ_SMS") == PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(main.this, new String[]{"android.permission.READ_SMS"}, REQUEST_CODE_ASK_PERMISSIONS);
return;
}
readAllSMS();
} else {
readAllSMS();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
readAllSMS();
} else {
Toast.makeText(main.this, "READING SMS Denied", Toast.LENGTH_SHORT)
.show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
protected void readAllSMS() {
Toast.makeText(main.this, "READING SMS Granted", Toast.LENGTH_SHORT)
.show();
List<SMSData> smsList = new ArrayList<>();
Uri uri = Uri.parse("content://sms/inbox");
Cursor c = getContentResolver().query(uri, null, null, null, null);
startManagingCursor(c);
if (c.moveToFirst()) {
for (int i = 0; i < c.getCount(); i++) {
SMSData sms = new SMSData();
sms.setBody(c.getString(c.getColumnIndexOrThrow("body")).toString());
sms.setNumber(c.getString(c.getColumnIndexOrThrow("address")).toString());
smsList.add(sms);
c.moveToNext();
}
}
c.close();
setListAdapter(new ListAdapter(this, smsList));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
SMSData sms = (SMSData) getListAdapter().getItem(position);
String msg = "number : " + sms.getNumber() + "\nsent : " + sms.getBody();
sendSMS(msg);
Toast.makeText(getApplicationContext(), sms.getBody(), Toast.LENGTH_LONG).show();
}
private void sendSMS(String message) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("SMS_Message",message);
startActivity(i);
}
}

Categories

Resources