Android TTS how to display speaking word in textview - java

How can i display tts output as text view when word speaking.
Actually i want to display tts output words in textview. I have 1 edittext in which i enter some data and then when click on play button it performs speech but i also want to display speaking words in text view how can i do this any one can help me. i also think about convert text into array form and then pass but, i don't think it useful any other solution ?
Code which i do currently.
For Example: If TTS is speaking this string: How are you! and when it reaches 'how', how can I display 'how' in text view only single word.
Initializations();
textToSpeech = new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.ENGLISH);
if (result == TextToSpeech.LANG_MISSING_DATA) {
Toast.makeText(MainActivity.this, "Sorry ! Language data missing", Toast.LENGTH_SHORT).show();
} else if (result == TextToSpeech.LANG_NOT_SUPPORTED) {
Toast.makeText(MainActivity.this, "Sorry ! Language not supported", Toast.LENGTH_SHORT).show();
} else {
speek.setEnabled(true);
}
} else if (status == TextToSpeech.ERROR) {
Toast.makeText(MainActivity.this, "Sorry ! Text to speech can't be initialized", Toast.LENGTH_SHORT).show();
speek.setEnabled(false);
}
}
});
speek.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SpeekOut();
}
});
private void SpeekOut() {
String text = etTextToSpeech.getText().toString();
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);
}
}

Try this to read
add this in any button click.
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
Intent i = new Intent(MainService.ACTION);
if (isServiceRunning()) {
stopService(i);
((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
.cancelAll();
} else {
startService(i);
runAsForeground();
}
try { startActivityForResult(intent, RESULT_SPEECH);
txtText.setText("");
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(), "Opps! Your device doesn't support Speech to Text", Toast.LENGTH_SHORT); t.show();
}
//runAsForeground function here
private void runAsForeground(){
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(this, 0,
notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
Notification notification=new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getString(R.string.app_name))
.setContentText("Night Mode")
.setContentIntent(pendingIntent).build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notification.flags = notification.flags
| Notification.FLAG_ONGOING_EVENT;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
}
To display in the textview
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SPEECH: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtText.setText(text.get(0));
}
break;
}
}
}
//MainService
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.os.PowerManager;
import android.provider.ContactsContract.PhoneLookup;
import android.util.Log;
public class MainService extends Service {
public static final String ACTION = "com.thul.CallRecorder.CALL_RECORD";
public static final String STATE = "STATE";
public static final String START = "START";
public static final String STORAGE = "STORAGE";
public static final String INCOMING = "INCOMING";
public static final String OUTGOING = "OUTGOING";
public static final String BEGIN = "BEGIN";
public static final String END = "END";
protected static final String TAG = MainService.class.getName();
protected static final boolean DEBUG = false;
private static final String AMR_DIR = "/callrec/";
private static final String IDLE = "";
private static final String INCOMING_CALL_SUFFIX = "_i";
private static final String OUTGOING_CALL_SUFFIX = "_o";
private Context cntx;
private volatile String fileNamePrefix = IDLE;
private volatile MediaRecorder recorder;
private volatile PowerManager.WakeLock wakeLock;
private volatile boolean isMounted = false;
private volatile boolean isInRecording = false;
#Override
public IBinder onBind(Intent i) {
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
this.cntx = getApplicationContext();
this.prepareAmrDir();
log("service create");
}
#Override
public void onDestroy() {
log("service destory");
this.stopRecording();
this.cntx = null;
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (null == intent || !ACTION.equals(intent.getAction())) {
return super.onStartCommand(intent, flags, startId);
}
String state = intent.getStringExtra(STATE);
String phoneNo = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
log("state: " + state + " phoneNo: " + phoneNo);
if (OUTGOING.equals(state)) {
fileNamePrefix = getContactName(this.getContext(), phoneNo)
+ OUTGOING_CALL_SUFFIX;
} else if (INCOMING.equals(state)) {
fileNamePrefix = getContactName(this.getContext(), phoneNo)
+ INCOMING_CALL_SUFFIX;
} else if (BEGIN.equals(state)) {
startRecording();
} else if (END.equals(state)) {
stopRecording();
} else if (STORAGE.equals(state)) {
String mountState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(mountState)) {
prepareAmrDir();
} else {
isMounted = false;
}
if (!isInRecording) {
stopSelf();
}
}
return START_STICKY;
}
public Context getContext() {
return cntx;
}
private void stopRecording() {
if (isInRecording) {
isInRecording = false;
recorder.stop();
recorder.release();
recorder = null;
releaseWakeLock();
stopSelf();
log("call recording stopped");
}
}
private String getDateTimeString() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'_'HHmmss");
Date now = new Date();
return sdf.format(now);
}
private String getMonthString() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
Date now = new Date();
return sdf.format(now);
}
private String getDateString() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date now = new Date();
return sdf.format(now);
}
private String getTimeString() {
SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");
Date now = new Date();
return sdf.format(now);
}
private void startRecording() {
if (!isMounted)
return;
stopRecording();
try {
File amr = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath()
+ AMR_DIR
+ getDateTimeString()
+ "_"
+ fileNamePrefix + ".amr");
log("Prepare recording in " + amr.getAbsolutePath());
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(amr.getAbsolutePath());
recorder.prepare();
recorder.start();
isInRecording = true;
acquireWakeLock();
log("Recording in " + amr.getAbsolutePath());
} catch (Exception e) {
Log.w(TAG, e);
}
}
private void prepareAmrDir() {
isMounted = Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
if (!isMounted)
return;
File amrRoot = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + AMR_DIR);
if (!amrRoot.isDirectory())
amrRoot.mkdir();
}
private String getContactName(Context cntx, String phoneNo) {
if (null == phoneNo)
return "";
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phoneNo));
ContentResolver cr = cntx.getContentResolver();
Cursor c = cr.query(uri, new String[] { PhoneLookup.DISPLAY_NAME },
null, null, null);
if (null == c) {
log("getContactName: The cursor was null when query phoneNo = "
+ phoneNo);
return phoneNo;
}
try {
if (c.moveToFirst()) {
String name = c.getString(0);
name = name.replaceAll("(\\||\\\\|\\?|\\*|<|:|\"|>)", "");
log("getContactName: phoneNo: " + phoneNo + " name: " + name);
return name;
} else {
log("getContactName: Contact name of phoneNo = " + phoneNo
+ " was not found.");
return phoneNo;
}
} finally {
c.close();
}
}
private void log(String info) {
if (DEBUG && isMounted) {
File log = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath()
+ AMR_DIR
+ "log_"
+ getMonthString()
+ ".txt");
try {
BufferedWriter out = new BufferedWriter(new FileWriter(log,
true));
try {
synchronized (out) {
out.write(getDateString()+getTimeString());
out.write(" ");
out.write(info);
out.newLine();
}
} finally {
out.close();
}
} catch (IOException e) {
Log.w(TAG, e);
}
}
}
private void acquireWakeLock() {
if (wakeLock == null) {
log("Acquiring wake lock");
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this
.getClass().getCanonicalName());
wakeLock.acquire();
}
}
private void releaseWakeLock() {
if (wakeLock != null && wakeLock.isHeld()) {
wakeLock.release();
wakeLock = null;
log("Wake lock released");
}
}
}
//isServiceRunning
private boolean isServiceRunning() {
ActivityManager myManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
ArrayList<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) myManager
.getRunningServices(30);
for (int i = 0; i < runningService.size(); i++) {
if (runningService.get(i).service.getClassName().equals(
MainService.class.getName())) {
return true;
}
}
return false;
}

Related

Application has Stoppped (Android Studio Bluetooth)

I try to make communication between two devices by using Bluteooth but always the application stopped when i try to test it.
I just try to send simple string (for exemple 'A') but also I have errors.
Also i can't turn on/off bluetooth manually.
the error is : Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothAdapter.isEnabled()' on a null object reference
at com.example.pfe.reglages.onCreate(reglages.java:53).
I need help because it's my project to get graduated
Thank you.
entrainement.java
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Handler;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
import android.os.Message;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import static android.bluetooth.BluetoothAdapter.getDefaultAdapter;
import static android.content.ContentValues.TAG;
public class entrainement extends AppCompatActivity {
private boolean CONTINUE_READ_WRITE = true;
private boolean CONNECTION_ENSTABLISHED = false;
private boolean DEVICES_IN_LIST = true;
private static String NAME = "pfe.fawez";
private static UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
Button btn6, btn7, btn8, btn16, btn9, btn5;
EditText txt;
TextView logview;
ListView lv;
ArrayList<String> listItems;
ArrayAdapter<String> listAdapter;
private BluetoothAdapter adapter;
private BluetoothSocket socket;
private InputStream is;
private OutputStream os;
private BluetoothDevice remoteDevice;
private Set<BluetoothDevice> pairedDevices;
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.entrainement);
btn6 = findViewById(R.id.button6);
btn7 = findViewById(R.id.button7);
btn8 = findViewById(R.id.button8);
btn16 = findViewById(R.id.button16);
btn9 = findViewById(R.id.button9);
btn5 = findViewById(R.id.button5);
txt = findViewById(R.id.editText2);
logview = findViewById(R.id.textView14);
lv = (ListView)findViewById(R.id.listView);
listItems = new ArrayList<String>(); //shows messages in list view
listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems);
lv.setAdapter(listAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() //list onclick selection process
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
if(DEVICES_IN_LIST)
{
String name = (String) parent.getItemAtPosition(position);
selectBTdevice(name); //selected device will be set globally
//Toast.makeText(getApplicationContext(), "Selected " + name, Toast.LENGTH_SHORT).show();
//do not automatically call OpenBT(null) because makes troubles with server/client selection
}
else //message is selected
{
String message = (String) parent.getItemAtPosition(position);
txt.setText(message);
}
}
/*adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter == null) //If the adapter is null, then Bluetooth is not supported
{
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_SHORT).show();
finish();
return;
}
list(null);*/
});
btn9.setOnClickListener(new View.OnClickListener() //sends text from text button
{
#Override
public void onClick(View v) {
String textToSend = txt.getText().toString();
byte[] b = textToSend.getBytes();
try {
os.write(b);
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Not sent", Toast.LENGTH_SHORT).show(); //usually problem server-client decision
}
logview.append("\nConnection !\n");
}
});
btn6.setOnClickListener(new View.OnClickListener() //sends text from text button
{
#Override
public void onClick(View v) {
String textToSend = "R";
byte[] b = textToSend.getBytes();
try {
os.write(b);
Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Not sent", Toast.LENGTH_SHORT).show(); //usually problem server-client decision
}
}
});
btn16.setOnClickListener(new View.OnClickListener() //sends text from text button
{
#Override
public void onClick(View v) {
String textToSend = "L";
byte[] b = textToSend.getBytes();
try {
os.write(b);
Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Not sent", Toast.LENGTH_SHORT).show(); //usually problem server-client decision
}
}
});
btn7.setOnClickListener(new View.OnClickListener() //sends text from text button
{
#Override
public void onClick(View v) {
String textToSend = "X";
byte[] b = textToSend.getBytes();
try {
os.write(b);
Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Not sent", Toast.LENGTH_SHORT).show(); //usually problem server-client decision
}
}
});
btn8.setOnClickListener(new View.OnClickListener() //sends text from text button
{
#Override
public void onClick(View v) {
String textToSend = "Y";
byte[] b = textToSend.getBytes();
try {
os.write(b);
Toast.makeText(getApplicationContext(), "OK", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Not sent", Toast.LENGTH_SHORT).show(); //usually problem server-client decision
}
}
});
}
private Runnable writter = new Runnable() {
#Override
public void run() {
while (CONTINUE_READ_WRITE) //reads from open stream
{
try
{
os.flush();
Thread.sleep(2000);
} catch (Exception e)
{
Log.e(TAG, "Writer failed in flushing output stream...");
CONTINUE_READ_WRITE = false;
}
}
}
};
public void list(View v) //shows paired devices to UI
{
CONNECTION_ENSTABLISHED = false; //protect from failing
listItems.clear(); //remove chat history
listAdapter.notifyDataSetChanged();
pairedDevices = adapter.getBondedDevices(); //list of devices
for(BluetoothDevice bt : pairedDevices) //foreach
{
listItems.add(0, bt.getName());
}
listAdapter.notifyDataSetChanged(); //reload UI
}
public void selectBTdevice(String name) //for selecting device from list which is used in procedures
{
if(pairedDevices.isEmpty()) {
list(null);
Toast.makeText(getApplicationContext(), "Selecting was unsucessful, no devices in list." ,Toast.LENGTH_SHORT ).show();
}
for(BluetoothDevice bt : pairedDevices) //foreach
{
if(name.equals(bt.getName()))
{
remoteDevice = bt;
Toast.makeText(getApplicationContext(), "Selected " + remoteDevice.getName(), Toast.LENGTH_SHORT ).show();
}
}
}
public void openBT(View v) //opens right thread for server or client
{
if(adapter == null)
{
adapter = getDefaultAdapter();
Log.i(TAG, "Backup way of getting adapter was used!");
}
CONTINUE_READ_WRITE = true; //writer tiebreaker
socket = null; //resetting if was used previously
is = null; //resetting if was used previously
os = null; //resetting if was used previously
if(pairedDevices.isEmpty() || remoteDevice == null)
{
Toast.makeText(this, "Paired device is not selected, choose one", Toast.LENGTH_SHORT).show();
return;
}
}
public void closeBT(View v) //for closing opened communications, cleaning used resources
{
/*if(adapter == null)
return;*/
CONTINUE_READ_WRITE = false;
CONNECTION_ENSTABLISHED = false;
if (is != null) {
try {is.close();} catch (Exception e) {}
is = null;
}
if (os != null) {
try {os.close();} catch (Exception e) {}
os = null;
}
if (socket != null) {
try {socket.close();} catch (Exception e) {}
socket = null;
}
try {
Handler mHandler = new Handler();
mHandler.removeCallbacksAndMessages(writter);
mHandler.removeCallbacksAndMessages(serverListener);
mHandler.removeCallbacksAndMessages(clientConnecter);
Log.i(TAG, "Threads ended...");
}catch (Exception e)
{
Log.e(TAG, "Attemp for closing threads was unsucessfull.");
}
Toast.makeText(getApplicationContext(), "Communication closed" ,Toast.LENGTH_SHORT).show();
list(null); //shows list for reselection
txt.setText(getResources().getString(R.string.demo));
}
private Runnable serverListener = new Runnable()
{
public void run()
{
try //opening of BT connection
{
android.util.Log.i("TrackingFlow", "Server socket: new way used...");
socket =(BluetoothSocket) remoteDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class}).invoke(remoteDevice,1);
socket.connect();
CONNECTION_ENSTABLISHED = true; //protect from failing
} catch(Exception e) //obsolete way how to open BT
{
try
{
android.util.Log.e("TrackingFlow", "Server socket: old way used...");
BluetoothServerSocket tmpsocket = adapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
socket = tmpsocket.accept();
CONNECTION_ENSTABLISHED = true; //protect from failing
android.util.Log.i("TrackingFlow", "Listening...");
}
catch (Exception ie)
{
Log.e(TAG, "Socket's accept method failed", ie);
ie.printStackTrace();
}
}
Log.i(TAG, "Server is ready for listening...");
runOnUiThread(new Runnable() {
#Override
public void run() { //Show message on UIThread
listItems.clear(); //remove chat history
listItems.add(0, String.format(" Server opened! Waiting for clients..."));
listAdapter.notifyDataSetChanged();
}});
try //reading part
{
is = socket.getInputStream();
os = socket.getOutputStream();
new Thread(writter).start();
int bufferSize = 1024;
int bytesRead = -1;
byte[] buffer = new byte[bufferSize];
while(CONTINUE_READ_WRITE) //Keep reading the messages while connection is open...
{
final StringBuilder sb = new StringBuilder();
bytesRead = is.read(buffer);
if (bytesRead != -1) {
String result = "";
while ((bytesRead == bufferSize) && (buffer[bufferSize-1] != 0))
{
result = result + new String(buffer, 0, bytesRead - 1);
bytesRead = is.read(buffer);
}
result = result + new String(buffer, 0, bytesRead - 1);
sb.append(result);
}
android.util.Log.e("TrackingFlow", "Read: " + sb.toString());
runOnUiThread(new Runnable() {
#Override
public void run() { //Show message on UIThread
Toast.makeText(entrainement.this, sb.toString(), Toast.LENGTH_SHORT).show();
listItems.add(0, String.format("< %s", sb.toString())); //showing in history
listAdapter.notifyDataSetChanged();
}
});
}
}
catch(IOException e){
Log.e(TAG, "Server not connected...");
e.printStackTrace();
}
}
};
private Runnable clientConnecter = new Runnable()
{
#Override
public void run()
{
try
{
socket = remoteDevice.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
CONNECTION_ENSTABLISHED = true; //protect from failing
Log.i(TAG, "Client is connected...");
runOnUiThread(new Runnable() {
#Override
public void run() { //Show message on UIThread
listItems.clear(); //remove chat history
listItems.add(0, String.format(" ready to communicate! Write something..."));
listAdapter.notifyDataSetChanged();
}});
os = socket.getOutputStream();
is = socket.getInputStream();
new Thread(writter).start();
Log.i(TAG, "Preparation for reading was done");
int bufferSize = 1024;
int bytesRead = -1;
byte[] buffer = new byte[bufferSize];
while(CONTINUE_READ_WRITE) //Keep reading the messages while connection is open...
{
final StringBuilder sb = new StringBuilder();
bytesRead = is.read(buffer);
if (bytesRead != -1)
{
String result = "";
while ((bytesRead == bufferSize) && (buffer[bufferSize-1] != 0))
{
result = result + new String(buffer, 0, bytesRead - 1);
bytesRead = is.read(buffer);
}
result = result + new String(buffer, 0, bytesRead - 1);
sb.append(result);
}
android.util.Log.e("TrackingFlow", "Read: " + sb.toString());
runOnUiThread(new Runnable() {
#Override
public void run() { //Show message on UIThread
Toast.makeText(entrainement.this, sb.toString(), Toast.LENGTH_SHORT).show();
listItems.add(0, String.format("< %s", sb.toString()));
listAdapter.notifyDataSetChanged();
}
});
}
}
catch (IOException e)
{
Log.e(TAG, "Client not connected...");
e.printStackTrace();
}
}
};
}
reglages.java
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Set;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class reglages extends AppCompatActivity {
private static final int REQUEST_ENABLE_BT = 0;
private static final int REQUEST_DISCOVER_BT = 1;
TextView mStatusBlueTv, mPairedTv;
ImageView mBlueIv;
Button mOnBtn, mOffBtn, mDiscoverBtn, mPairedBtn;
BluetoothAdapter mBlueAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reglages);
mStatusBlueTv = findViewById(R.id.statusBluetoothTv);
mPairedTv = findViewById(R.id.pairedTv);
mBlueIv = findViewById(R.id.bluetoothIv);
mOnBtn = findViewById(R.id.onBtn);
mOffBtn = findViewById(R.id.offBtn);
mDiscoverBtn = findViewById(R.id.discoverableBtn);
mPairedBtn = findViewById(R.id.pairedBtn);
//adapter
mBlueAdapter = BluetoothAdapter.getDefaultAdapter();
//check if bluetooth is available or not
if (mBlueAdapter == null){
mStatusBlueTv.setText("Bluetooth is not available");
}
else {
mStatusBlueTv.setText("Bluetooth is available");
}
//set image according to bluetooth status(on/off)
if (mBlueAdapter.isEnabled()){
mBlueIv.setImageResource(R.drawable.ic_action_on);
}
else {
mBlueIv.setImageResource(R.drawable.ic_action_off);
}
//on btn click
mOnBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mBlueAdapter.isEnabled()){
showToast("Turning On Bluetooth...");
//intent to on bluetooth
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, REQUEST_ENABLE_BT);
}
else {
showToast("Bluetooth is already on");
}
}
});
//discover bluetooth btn click
mDiscoverBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mBlueAdapter.isDiscovering()){
showToast("Making Your Device Discoverable");
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(intent, REQUEST_DISCOVER_BT);
}
}
});
//off btn click
mOffBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mBlueAdapter.isEnabled()){
mBlueAdapter.disable();
showToast("Turning Bluetooth Off");
mBlueIv.setImageResource(R.drawable.ic_action_off);
}
else {
showToast("Bluetooth is already off");
}
}
});
//get paired devices btn click
mPairedBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mBlueAdapter.isEnabled()){
mPairedTv.setText("Paired Devices");
Set<BluetoothDevice> devices = mBlueAdapter.getBondedDevices();
for (BluetoothDevice device: devices){
mPairedTv.append("\nDevice: " + device.getName()+ ", " + device);
}
}
else {
//bluetooth is off so can't get paired devices
showToast("Turn on bluetooth to get paired devices");
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case REQUEST_ENABLE_BT:
if (resultCode == RESULT_OK){
//bluetooth is on
mBlueIv.setImageResource(R.drawable.ic_action_on);
showToast("Bluetooth is on");
}
else {
//user denied to turn bluetooth on
showToast("could't on bluetooth");
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
//toast message function
private void showToast(String msg){
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
}
Then change this lines:
//check if bluetooth is available or not
if (mBlueAdapter == null){
mStatusBlueTv.setText("Bluetooth is not available");
}
else {
mStatusBlueTv.setText("Bluetooth is available");
}
//set image according to bluetooth status(on/off)
if (mBlueAdapter.isEnabled()){
mBlueIv.setImageResource(R.drawable.ic_action_on);
}
else {
mBlueIv.setImageResource(R.drawable.ic_action_off);
}
To this:
//check if bluetooth is available or not
if (mBlueAdapter == null) {
mStatusBlueTv.setText("Bluetooth is not available");
mBlueIv.setImageResource(R.drawable.ic_action_off);
} else {
mStatusBlueTv.setText("Bluetooth is available");
//set image according to bluetooth status(on/off)
if (mBlueAdapter.isEnabled()) {
mBlueIv.setImageResource(R.drawable.ic_action_on);
} else {
mBlueIv.setImageResource(R.drawable.ic_action_off);
}
}
And each time you check isEnabled check for null first, changing:
if (mBlueAdapter.isEnabled()){
to:
if (mBlueAdapter != null && mBlueAdapter.isEnabled()) {
This way you'll prevent having NullPointers when the Bluetooth is not available (mBlueAdapter == null) as you can not check isEnabled() in this cases.

Java android java.util.ConcurrentModificationException

I have a service in which I have a AsyncTask
if (s != null) {
if (!MainActivity.photoListSend.isEmpty()) {
if (MainActivity.photoListSend.size() > 0) {
File file = MainActivity.photoListSend.get(0);
if (file.exists())
file.delete();
MainActivity.photoListSend.remove(0);
Gson gson = new Gson();
String jsonCurProduct = gson.toJson(MainActivity.photoListSend);
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("TAG", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("TAG", jsonCurProduct);
editor.apply();
File imagesFolder = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
assert imagesFolder != null;
}
}
}
On this line :
String jsonCurProduct = gson.toJson(MainActivity.photoListSend);
I have java.util.ConcurrentModificationException
And this is my all class :
ublic class Sendrer extends Service {
public static boolean running = false;
private Timer timer = new Timer();
private SendPhotoTask asyncSender;
private Context context;
private SharedPreferences sp;
private SharedPreferences.Editor editor;
public static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
sp = getSharedPreferences("pfref", Activity.MODE_PRIVATE);
editor = sp.edit();
Gson gson = new Gson();
List<File> productFromShared = new ArrayList<>();
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("TAG", Context.MODE_PRIVATE);
String jsonPreferences = sharedPref.getString("TAG", "");
Type type = new TypeToken<List<File>>() {
}.getType();
productFromShared = gson.fromJson(jsonPreferences, type);
MainActivity.photoListSend = null;
MainActivity.photoListSend = new ArrayList<>();
if (productFromShared != null)
MainActivity.photoListSend.addAll(productFromShared);
Log.e("tworzenie serwisu ", "tworzenie");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("Dziełanie serwisu ", "Dziełanie");
if (!running) {
running = true;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
asyncSender = new SendPhotoTask();
asyncSender.execute();
}
}, 1000 * 60 * 2);
}
return START_STICKY;
}
#Override
public void onDestroy() {
if (running) {
timer.cancel();
asyncSender = new SendPhotoTask();
asyncSender.cancel(true);
running = false;
}
Log.e("service ", "nie działa");
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
public boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
class SendPhotoTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... strings) {
running = true;
if (MainActivity.photoListSend != null) {
if (!MainActivity.photoListSend.isEmpty())
if (NetworkUtil.isNetworkAvailable(context)) {
if (MainActivity.photoListSend.size() > 0) {
MainActivity.isSend = true;
running = true;
InputStream responseInputStream = null;
Log.e("start wysłania ", "start");
try {
if (MainActivity.photoListSend.get(0).isFile()) {
responseInputStream = HttpConnectionsUtil.sendPhotoRequest(getApplicationContext(), true, MainActivity.photoListSend.get(0).getName());
if (responseInputStream != null) {
String input = convertStreamToString(responseInputStream);
if (input.equals("empty"))
return "BAD";
else {
try {
int tt = ResponseParser.getType(input);
Log.e("TaG", tt + " ");
if (tt == 0) {
return null;
} else if (tt == -1) {
return null;
}
} catch (UnknownAnswerName e) {
e.printStackTrace();
return null;
}
}
}
} else {
return "BAD";
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
// Log.e("Wysyłanie zdjęcia ", convertStreamToString(responseInputStream));
if (responseInputStream != null)
return convertStreamToString(responseInputStream);
}
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (NetworkUtil.isNetworkAvailable(context)) {
if (sp.getBoolean("workOffLine", false)) {
editor.putBoolean("workOffLine", false);
editor.commit();
isConnect.setVisibility(View.VISIBLE);
imgIsSend.setVisibility(View.VISIBLE);
imgIsNet.setVisibility(View.GONE);
}
}
if (s != null) {
if (!MainActivity.photoListSend.isEmpty()) {
if (MainActivity.photoListSend.size() > 0) {
File file = MainActivity.photoListSend.get(0);
if (file.exists())
file.delete();
MainActivity.photoListSend.remove(0);
Gson gson = new Gson();
String jsonCurProduct = gson.toJson(MainActivity.photoListSend);
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("TAG", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("TAG", jsonCurProduct);
editor.apply();
File imagesFolder = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
assert imagesFolder != null;
}
}
}
if (s == null) {
MainActivity.isSend = false;
}
if (!MainActivity.photoListSend.isEmpty()) {
if (NetworkUtil.isNetworkAvailable(context)) {
if (MainActivity.photoListSend.size() > 0) {
asyncSender = new SendPhotoTask();
asyncSender.execute();
Log.e("Wysyłanie kolejnego ", "zdjecia");
} else {
context.stopService(new Intent(context, Sendrer.class));
asyncSender.cancel(true);
context.startService(new Intent(context, Sendrer.class));
}
} else {
context.stopService(new Intent(context, Sendrer.class));
asyncSender.cancel(true);
context.startService(new Intent(context, Sendrer.class));
}
} else {
MainActivity.isSend = false;
context.stopService(new Intent(context, Sendrer.class));
asyncSender.cancel(true);
context.startService(new Intent(context, Sendrer.class));
}
running = false;
}
}
}
That's because another thread is modifying MainActivity meanwhile. You can branch the line with
synchronized(MainActivity.this) {
String jsonCurProduct = gson.toJson(MainActivity.photoListSend);
}
however you should be aware of possible performance issues because now all threads will be waiting till toJson method ends
Read more about the exception and how to avoid this

Blocking any other application via Service

I'm creating a business application and must block any other application that the user tries to open. I am creating a service to it, but it's not working.
When run, it does not see the other applications when opened by the user.
I read some other posts here, but I could not solve.
Below is my service.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
startService(new Intent(this, clsServico.class));
}
my class:
import android.app.ActivityManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class clsServico extends Service {
private static final long INTERVAL = TimeUnit.SECONDS.toMillis(2); // em segundos
private static final String TAG = clsServico.class.getSimpleName();
private static final String APS_BG = "APS_BG";
private Thread t = null;
private Context ctx = null;
private boolean running = false;
#Override
public void onDestroy() {
running =false;
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
running = true;
ctx = this;
// checa periodicamente se tem algum outro app na tela
t = new Thread(new Runnable() {
#Override
public void run() {
do {
//checkAPS();
try {
if(Build.VERSION.SDK_INT >= 21)
listTasks();
else
listTasks_SDK21();
} catch (PackageManager.NameNotFoundException e) {
}
try {
Thread.sleep(INTERVAL);
} catch (InterruptedException e) {
}
}while(running);
stopSelf();
}
});
t.start();
return Service.START_NOT_STICKY;
}
public void listTasks() throws PackageManager.NameNotFoundException {
if(Build.VERSION.SDK_INT >= 21) {
ActivityManager mgr = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.AppTask> tasks = mgr.getAppTasks();
String packagename;
String label;
for (ActivityManager.AppTask task : tasks) {
packagename = task.getTaskInfo().baseIntent.getComponent().getPackageName();
label = getPackageManager().getApplicationLabel(getPackageManager().getApplicationInfo(packagename, PackageManager.GET_META_DATA)).toString();
//Log.i(TAG, packagename + ":" + label);
}
}
}
public void listTasks_SDK21() throws PackageManager.NameNotFoundException {
ActivityManager mgr = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RecentTaskInfo> tasks = mgr.getRecentTasks(20, 0);
String packagename;
String label;
for(ActivityManager.RecentTaskInfo task: tasks){
packagename = task.baseIntent.getComponent().getPackageName();
label = getPackageManager().getApplicationLabel(getPackageManager().getApplicationInfo(packagename, PackageManager.GET_META_DATA)).toString();
Log.i(TAG,packagename + ":" + label);
}
}
private void checkAPS() {
/*
if(apenasAPSAtivado(ctx)) {
if(isInBackground()) {
restoreApp(); // tras p frente
}
}
*/
PackageManager packageManager = getPackageManager();
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ResolveInfo> appList = packageManager.queryIntentActivities(mainIntent, 0);
Collections.sort(appList, new ResolveInfo.DisplayNameComparator(packageManager));
List<PackageInfo> packs = packageManager.getInstalledPackages(0);
for(int i=0; i < packs.size(); i++) {
PackageInfo p = packs.get(i);
ApplicationInfo a = p.applicationInfo;
// skip system apps if they shall not be included
if((a.flags & ApplicationInfo.FLAG_SYSTEM) == 1) {
continue;
}
//Log.i("packageName","" + p.packageName);
}
List<ActivityManager.RunningTaskInfo> RunningTask = mActivityManager.getRunningTasks(1);
ActivityManager.RunningTaskInfo run = RunningTask.get(0);
Log.i("topActivity", run.topActivity.getClassName());
Intent ints = new Intent(Intent.ACTION_MAIN, null);
ints.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> intentlist = packageManager.queryIntentActivities(ints, PackageManager.PERMISSION_GRANTED);
List<ActivityManager.RunningTaskInfo> processes = mActivityManager.getRunningTasks(Integer.MAX_VALUE);
String pName = "";
if (processes != null)
{
for (int i = 0; i < processes.size(); i++) {
String packageName = processes.get(i).topActivity.getPackageName();
ActivityManager.RunningTaskInfo temp = processes.get(i);
try
{
pName = (String) packageManager.getApplicationLabel(packageManager.getApplicationInfo(packageName, PackageManager.GET_META_DATA));
}
catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
//Log.i("RunningTaskInfo",pName + " : " + temp.id);
/*
if (savedapp.equals(pName)) {
// finish(pm.);
int code = intentlist.get(i).activityInfo.hashCode();
finishActivity(code);
mActivityManager.killBackgroundProcesses(packageName);
mActivityManager.restartPackage(packageName);
android.os.Process.killProcess(temp.id);
finishActivity(temp.id);
}
*/
}
}
List<ActivityManager.RunningTaskInfo> rt = mActivityManager.getRunningTasks(1000);
for(int i = 0; i < rt.size(); i++){
ActivityManager.RunningTaskInfo ar = rt.get(i);
String activityOnTop=ar.topActivity.getClassName();
//Log.i("rt", activityOnTop);
}
//ActivityManager.RunningTaskInfo ar = rt.get(0);
//String activityOnTop=ar.topActivity.getClassName();
//Log.i("activityOnTop", activityOnTop);
//ActivityManager am = (ActivityManager)ctx.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> pids = mActivityManager.getRunningAppProcesses();
for(int i = 0; i < pids.size(); i++)
{
ActivityManager.RunningAppProcessInfo p = pids.get(i);
if(!p.processName.equalsIgnoreCase("nog.aps3")){
android.os.Process.killProcess(p.pid);
try {
android.os.Process.killProcess(p.pid);
android.os.Process.sendSignal(p.pid, android.os.Process.SIGNAL_KILL);
mActivityManager.killBackgroundProcesses(p.processName);
} catch (Exception e) {
e.printStackTrace();
//Log.i("try", e.toString());
}
}
//Log.i("info.processName", p.processName);
//isInBackground();
}
}
private boolean isInBackground() {
ActivityManager am = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
//Log.i("getPackageName", ctx.getApplicationContext().getPackageName() +" =? "+ componentInfo.getPackageName());
return (!ctx.getApplicationContext().getPackageName().equals(componentInfo.getPackageName()));
}
private void restoreApp() {
//restore other class
}
public boolean apenasAPSAtivado(final Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getBoolean(APS_BG, false);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Can anyone help me with this, pls?

Updating the UI upon receiving an android push notification

I have a query regarding android push notification and i had asked it in another stackoverflow post and i did not get much help out of it [Query regarding Android push notifications. So i am posting it again, and it is as follows:
I have an android app that receives push notifications from Google push notification service. When i tap on the received notification, it opens an UI which displays this message, it is a list view. Now, when the user receives the push notification, and assuming that this screen is open, the UI should be refreshed automatically, such that it displays the latest notification. Could anybody let me know how i can solve this?
Below is my code that i have implemented:
Java code to receive the notification:
import java.util.Timer;
import java.util.TimerTask;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.util.Log;
import com.example.foodu.R;
import com.google.android.gcm.GCMBaseIntentService;
public class GCMIntentService extends GCMBaseIntentService {
private static final String TAG = "GCM ::Service";
// Use your PROJECT ID from Google API into SENDER_ID
public static final String SENDER_ID = "53340195486";
public GCMIntentService() {
super(SENDER_ID);
}
#Override
protected void onError(Context arg0, String errorId) {
Log.e(TAG, "onError: errorId=" + errorId);
}
#Override
protected void onMessage(Context context, Intent data) {
String message;
// Message from PHP server
message = data.getStringExtra("message");
// Open a new activity called GCMMessageView
Intent intent = new Intent(this, com.example.foodu.Notification.class);
// Pass data to the new activity
intent.putExtra("message", message);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Starts the activity on notification click
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
// Create the notification with a notification builder
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_logo)
.setWhen(System.currentTimeMillis())
.setContentTitle("Deals")
.setContentText(message).setContentIntent(pIntent)
.getNotification();
// Remove the notification on click
notification.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(R.string.app_name, notification);
{
// Wake Android Device when notification received
PowerManager pm = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
final PowerManager.WakeLock mWakelock = pm.newWakeLock(
PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP, "GCM_PUSH");
mWakelock.acquire();
// Timer before putting Android Device to sleep mode.
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
mWakelock.release();
}
};
timer.schedule(task, 5000);
}
}
#Override
protected void onRegistered(Context arg0, String registrationId) {
Log.i(TAG, "onRegistered: registrationId=" + registrationId);
}
#Override
protected void onUnregistered(Context arg0, String registrationId) {
Log.i(TAG, "onUnregistered: registrationId=" + registrationId);
}
}
The code for the corresponding activity that would be launched when the user taps on the notification:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.Locale;
import java.util.StringTokenizer;
import java.util.TimeZone;
import com.example.foodu.R;
import com.example.foodu.R.drawable;
import com.example.foodu.R.id;
import com.example.foodu.R.layout;
import com.example.foodu.R.menu;
import com.google.android.gcm.GCMRegistrar;
import android.support.v7.app.ActionBarActivity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.util.Log;
import android.view.ActionMode;
import android.view.ActionMode.Callback;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Notification extends ActionBarActivity {
LinkedList<NotificationData> notificationList = new LinkedList<NotificationData>();
ListView listView = null;
NotificationListAdapter adaptor;
ActionMode mActionMode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
overridePendingTransition(R.anim.trans_left_in, R.anim.trans_left_out);
listView = (ListView) findViewById(R.id.listView1);
// Retrive the data from GCMIntentService.java
Intent i = getIntent();
String message = i.getStringExtra("message");
//getDataForDisplay();
if(message!=null)
{
parseData(message);
}else{
getDataToDisplay();
}
adaptor = new NotificationListAdapter(getApplicationContext(), notificationList);
listView.setAdapter(adaptor);
TextView emptyText = (TextView) findViewById(R.id.empty);
emptyText.setText("No Events Yet!");
listView.setEmptyView(emptyText);
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
onListitemSelect(position);
view.setSelected(true);
return true;
}
});
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
adaptor.notifyDataSetChanged();
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
}
void writeToFile(){
FileOutputStream fos;
try {
fos = openFileOutput("varun", Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(notificationList);
oos.close();
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void readFromFile(){
try{
FileInputStream fis = openFileInput("varun");
ObjectInputStream ois = new ObjectInputStream(fis);
LinkedList<NotificationData> local = (LinkedList<NotificationData>) ois.readObject();
ois.close();
for (int i = 0; i < local.size(); i++) {
notificationList.add(local.get(i));
}
}catch(Exception e){
e.printStackTrace();
}
}
private void getDataToDisplay() {
// TODO Auto-generated method stub
readFromFile();
}
private void parseData(String message) {
try {
int len = 0;
String[] stringArr = new String[100];
StringTokenizer st = new StringTokenizer(message, ".");
len = st.countTokens();
for (int i = 0; i < len; i++) {
if (st.hasMoreTokens()) {
stringArr[i] = st.nextToken();
}
}
NotificationData data = new NotificationData();
data.title = stringArr[0];
data.venue = stringArr[1];
data.date = stringArr[2];
data.time = stringArr[3];
notificationList.add(data);
readFromFile();
} catch (Exception e) {
e.printStackTrace();
}
}
private void getDateToDisplay() {
// TODO Auto-generated method stub
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
writeToFile();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.notificationmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
if(id == R.id.action_register){
registerDevice();
return true;
}
return super.onOptionsItemSelected(item);
}
private void registerDevice() {
try {
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
GCMRegistrar
.register(Notification.this, GCMIntentService.SENDER_ID);
} catch (Exception e) {
e.printStackTrace();
}
}
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.notificationcontext, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_calender:
addToCalender();
mode.finish();
return true;
case R.id.menu_delete:
//deleteData();
showAlertBox();
return false;
case R.id.menu_share:
shareDate();
mode.finish();
return true;
case R.id.menu_copy:
copyToClip();
mode.finish();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
adaptor.removeSelection();
}
};
void onListitemSelect(int position) {
adaptor.toggleSelection(position);
boolean hasCheckedItems = adaptor.getSelectedCount() > 0;
if (hasCheckedItems && mActionMode == null) {
mActionMode = startActionMode((Callback) mActionModeCallback);
} else if (!hasCheckedItems && mActionMode != null) {
mActionMode.finish();
}
if (mActionMode != null)
mActionMode.setTitle(String.valueOf(adaptor.getSelectedCount()));
}
protected void showAlertBox() {
// TODO Auto-generated method stub
AlertDialog.Builder builder1 = new AlertDialog.Builder(Notification.this);
builder1.setMessage("Delete " + adaptor.getSelectedIds().size()+ " events?");
builder1.setCancelable(true);
builder1.setIcon(R.drawable.alert);
builder1.setTitle("Caution");
builder1.setIcon(android.R.drawable.ic_dialog_alert);
builder1.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
deleteData();
mActionMode.finish();
}
});
builder1.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
protected void copyToClip() {
StringBuilder shareText = new StringBuilder();
for (int i = 0; i < adaptor.getSelectedIds().size(); i++) {
NotificationData data = notificationList
.get(adaptor.getSelectedIds().keyAt(i));
shareText.append(data.title + " " + data.venue + " " + data.date
+ " " + data.time);
shareText.append("\n");
}
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Notification App", shareText);
clipboard.setPrimaryClip(clip);
Toast.makeText(getApplicationContext(), "Data copied to ClipBoard",
Toast.LENGTH_LONG).show();
}
protected void shareDate() {
StringBuilder shareText = new StringBuilder();
for (int i = 0; i < adaptor.getSelectedIds().size(); i++) {
NotificationData data = notificationList
.get(adaptor.getSelectedIds().keyAt(i));
shareText.append(data.title + " " + data.venue + " " + data.date
+ " " + data.time);
shareText.append("\n");
}
String share = shareText.toString();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, share);
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
protected void deleteData() {
int count = 0;
int startPoint = adaptor.getSelectedIds().keyAt(0);
for (int i = 0; i < adaptor.getSelectedIds().size(); i++) {
adaptor.remove(notificationList.get(startPoint));
count++;
}
String message = " Event";
if(count>1)
{
message = " Events";
}
Toast.makeText(getApplicationContext(),
count + message+" deleted", Toast.LENGTH_LONG)
.show();
}
private void addToCalender() {
try {
int count = 0;
for (int i = 0; i < adaptor.getSelectedIds().size(); i++) {
NotificationData data = notificationList
.get(adaptor.getSelectedIds().keyAt(i));
ContentResolver cr = getApplicationContext()
.getContentResolver();
ContentValues values = new ContentValues();
String myDate = data.date + " " + data.time;
String timeArr[] = data.time.split("to");
SimpleDateFormat sfd = new SimpleDateFormat(
"' Date: 'MM/dd/yyyy 'Time: 'hh a", Locale.getDefault());
long time = sfd.parse(myDate).getTime();
values.put(CalendarContract.Events.DTSTART, time);
if (timeArr.length > 0) {
String endTime = timeArr[1];
SimpleDateFormat timeFormat = new SimpleDateFormat(
"' Date: 'MM/dd/yyyy hh a", Locale.getDefault());
long endtime = timeFormat.parse(data.date + " " + endTime)
.getTime();
values.put(CalendarContract.Events.DTEND, endtime);
}
values.put(CalendarContract.Events.TITLE, data.title);
values.put(CalendarContract.Events.DESCRIPTION, data.venue);
TimeZone timeZone = TimeZone.getDefault();
values.put(CalendarContract.Events.EVENT_TIMEZONE,
timeZone.getID());
values.put(CalendarContract.Events.CALENDAR_ID, 1);
Uri uri = cr
.insert(CalendarContract.Events.CONTENT_URI, values);
count++;
}
String message = " Event";
if(count>1)
{
message = " Events";
}
Toast.makeText(getApplicationContext(),
count + message + " added to Calender", Toast.LENGTH_LONG)
.show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Use LocalBroadcastManager
Check following code / steps
1) Add in your activity (UI refresh Activity)
private BroadcastReceiver mMyBroadcastReceiver;
Then ,
2) In onResume
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mMyBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent)
{
// Here you can refresh your listview or other UI
Toast.makeText(getApplicationContext(), "Receiver", 2000).show();
}
};
try {
LocalBroadcastManager.getInstance(this).registerReceiver(mMyBroadcastReceiver,new IntentFilter("your_action"));
} catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
}}
// and your other code
3) Then unregister in onPause
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMyBroadcastReceiver);
}
4) Finally add in your GCM reciver class.
first check your activity is Visible or not using static variable
if visible add
Intent gcm_rec = new Intent("your_action"); LocalBroadcastManager.getInstance(arg0).sendBroadcast(gcm_rec);
else
use Notification Manager for notification.
I think this is easy and best way to refresh your listview UI / call Fetching method.

Inverting audio in Java

I am new to Java and I want to know how to invert audio (fixed voice inversion) coming from the input through a loopback to the output after a delay. How and where would I do this, and would I be able to set a frequency of the inversion somehow. Thanks.
package net.bitplane.android.microphone;
import java.nio.ByteBuffer;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;
public class MicrophoneService extends Service implements OnSharedPreferenceChangeListener {
private static final String APP_TAG = "Microphone";
private static final int mSampleRate = 44100;
private static final int mFormat = AudioFormat.ENCODING_PCM_16BIT;
private AudioTrack mAudioOutput;
private AudioRecord mAudioInput;
private int mInBufferSize;
private int mOutBufferSize;
SharedPreferences mSharedPreferences;
private static boolean mActive = false;
private NotificationManager mNotificationManager;
private MicrophoneReceiver mBroadcastReceiver;
private class MicrophoneReceiver extends BroadcastReceiver {
// Turn the mic off when things get loud
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action != null && action.equals(android.media.AudioManager.ACTION_AUDIO_BECOMING_NOISY)) {
SharedPreferences prefs = context.getSharedPreferences(APP_TAG, Context.MODE_PRIVATE);
SharedPreferences.Editor e = prefs.edit();
e.putBoolean("active", false);
e.commit();
}
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
Log.d(APP_TAG, "Creating mic service");
// notification service
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mBroadcastReceiver = new MicrophoneReceiver();
// create input and output streams
mInBufferSize = AudioRecord.getMinBufferSize(mSampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, mFormat);
mOutBufferSize = AudioTrack.getMinBufferSize(mSampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, mFormat);
mAudioInput = new AudioRecord(MediaRecorder.AudioSource.MIC, mSampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, mFormat, mInBufferSize);
mAudioOutput = new AudioTrack(AudioManager.STREAM_MUSIC, mSampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, mFormat, mOutBufferSize, AudioTrack.MODE_STREAM);
// listen for preference changes
mSharedPreferences = getSharedPreferences(APP_TAG, MODE_PRIVATE);
mSharedPreferences.registerOnSharedPreferenceChangeListener(this);
mActive = mSharedPreferences.getBoolean("active", false);
if (mActive)
record();
}
#Override
public void onDestroy() {
Log.d(APP_TAG, "Stopping mic service");
// close the service
SharedPreferences.Editor e = mSharedPreferences.edit();
e.putBoolean("active", false);
e.commit();
// disable the listener
mSharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
mAudioInput.release();
mAudioOutput.release();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.d(APP_TAG, "Service sent intent");
// if this is a stop request, cancel the recording
if (intent != null && intent.getAction() != null) {
if (intent.getAction().equals("net.bitplane.android.microphone.STOP")) {
Log.d(APP_TAG, "Cancelling recording via notification click");
SharedPreferences.Editor e = mSharedPreferences.edit();
e.putBoolean("active", false);
e.commit();
}
}
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// intercept the preference change.
if (!key.equals("active"))
return;
boolean bActive = sharedPreferences.getBoolean("active", false);
Log.d(APP_TAG, "Mic state changing (from " + mActive + " to " + bActive + ")");
if (bActive != mActive) {
mActive = bActive;
if (mActive)
record();
if (!mActive)
mNotificationManager.cancel(0);
}
}
public void record() {
Thread t = new Thread() {
public void run() {
Context context = getApplicationContext();
CharSequence titleText = getString(R.string.mic_active);
CharSequence statusText = getString(R.string.cancel_mic);
long when = System.currentTimeMillis();
Intent cancelIntent = new Intent();
cancelIntent.setAction("net.bitplane.android.microphone.STOP");
cancelIntent.setData(Uri.parse("null://null"));
cancelIntent.setFlags(cancelIntent.getFlags() | Notification.FLAG_AUTO_CANCEL);
PendingIntent pendingCancelIntent = PendingIntent.getService(context, 0, cancelIntent, 0);
Notification notification = new Notification(R.drawable.status, titleText, when);
notification.setLatestEventInfo(context, titleText, statusText, pendingCancelIntent);
mNotificationManager.notify(0, notification);
// allow the
registerReceiver(mBroadcastReceiver, new IntentFilter(android.media.AudioManager.ACTION_AUDIO_BECOMING_NOISY));
Log.d(APP_TAG, "Entered record loop");
recordLoop();
Log.d(APP_TAG, "Record loop finished");
}
private void recordLoop() {
if ( mAudioOutput.getState() != AudioTrack.STATE_INITIALIZED || mAudioInput.getState() != AudioTrack.STATE_INITIALIZED) {
Log.d(APP_TAG, "Can't start. Race condition?");
}
else {
try {
try { mAudioOutput.play(); } catch (Exception e) { Log.e(APP_TAG, "Failed to start playback"); return; }
try { mAudioInput.startRecording(); } catch (Exception e) { Log.e(APP_TAG, "Failed to start recording"); mAudioOutput.stop(); return; }
try {
ByteBuffer bytes = ByteBuffer.allocateDirect(mInBufferSize);
int o = 0;
byte b[] = new byte[mInBufferSize];
while(mActive) {
o = mAudioInput.read(bytes, mInBufferSize);
bytes.get(b);
bytes.rewind();
mAudioOutput.write(b, 0, o);
}
Log.d(APP_TAG, "Finished recording");
}
catch (Exception e) {
Log.d(APP_TAG, "Error while recording, aborting.");
}
try { mAudioOutput.stop(); } catch (Exception e) { Log.e(APP_TAG, "Can't stop playback"); mAudioInput.stop(); return; }
try { mAudioInput.stop(); } catch (Exception e) { Log.e(APP_TAG, "Can't stop recording"); return; }
}
catch (Exception e) {
Log.d(APP_TAG, "Error somewhere in record loop.");
}
}
// cancel notification and receiver
mNotificationManager.cancel(0);
try {
unregisterReceiver(mBroadcastReceiver);
} catch (IllegalArgumentException e) { Log.e(APP_TAG, "Receiver wasn't registered: " + e.toString()); }
}
};
t.start();
}
}

Categories