package com.example.trynot;
import java.io.IOException;
import java.util.Calendar;
import java.util.Locale;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Flags.Flag;
import javax.mail.search.FlagTerm;
import com.example.trynot.MainActivity;
import com.example.trynot.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.sax.StartElementListener;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import android.speech.tts.TextToSpeech;
public class MainActivity extends Activity {
private static final int MY_DATA_CHECK_CODE = 1234;
public static Context c,b;
public TextToSpeech tts;
public static Intent serviceIntent;
private static int myNotificationId;
public static class ReadMailSample extends AsyncTask<String,String,Void> implements TextToSpeech.OnInitListener{
Message message;
private TextToSpeech tts;
static String command, phoneNumber, type, priority, name, time_stamp, imei, opt1, opt2, opt3, fromSubString;
Properties properties = null;
private Session session = null;
private Store store = null;
private Folder inbox = null;
String userName="avarote1994#gmail.com" ; // PROVIDE RECEPIENT EMAIL ID
String password="amul11111994" ; // PROVIDE RECEPIENT PASSWORD
static SQLiteDatabase db;
boolean flag=false;
Context acn;
//private Bundle savedInstanceState;
protected Void doInBackground(String...params){ // SEPARATE THREAD TO RUN IN THE BACKGROUND
try{
readMails();
}
catch(Exception e){
Logger logger = Logger.getAnonymousLogger();
logger.log(Level.INFO, "an exception was thrown", e);
}
return null;
}
ReadMailSample(SQLiteDatabase db){
this.db = db;
}
ReadMailSample(){
}
ReadMailSample(Context cn){
acn=cn;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
tts = new TextToSpeech(c,ReadMailSample.this);
}
#Override
protected void onProgressUpdate(String... values) {
try {
System.out.println("---------------------adasd-----------" + time_stamp);
showNotification();
speakOut();
}
catch(Exception e){
e.printStackTrace();
}
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
tts.speak(command, TextToSpeech.QUEUE_FLUSH, null);
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
public void speakOut() {
tts.speak("hello hi", TextToSpeech.QUEUE_FLUSH, null);
}
public void showNotification() {
PendingIntent notificationIntent = preparePendingIntent();
Notification notification = createBasicNotification(notificationIntent);
displayNotification(notification);
}
#SuppressLint("InlinedApi")
private PendingIntent preparePendingIntent() {
Intent intent=new Intent(c,MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(
c,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT);
return pendingIntent;
}
private Notification createBasicNotification(PendingIntent notificationIntent) {
NotificationCompat.Builder builder = new Builder(c);
long[] vibrationPattern = {0, 200, 800, 200, 600, 200, 400, 200, 200, 200, 100, 200, 50, 200, 50, 200, 50, 200, 50, 200};
Notification notification = builder
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Medication Reminder")
.setContentText(command)
.setAutoCancel(true)
.setContentIntent(notificationIntent)
.setWhen(Calendar.getInstance().getTimeInMillis() + 1000*60+60)
.setVibrate(vibrationPattern)
.build();
return notification;
}
private void displayNotification(Notification notification) {
NotificationManager notificationManager = (NotificationManager)c.getSystemService(Context.NOTIFICATION_SERVICE);
myNotificationId=(int) System.currentTimeMillis();
notificationManager.notify(myNotificationId , notification);
}
public void readMails() throws IOException{
System.out.println("READMAIL hi");
properties = new Properties();
// SETTING UP AN IMAP SERVER TO ACCESS THE RECEPIENT'S EMAIL
properties.setProperty("mail.host", "imap.gmail.com");
properties.setProperty("mail.port", "995");
properties.setProperty("mail.transport.protocol", "imaps");
while(true){// CONTINUOUSLY MONITOR INCOMING MAIL'S
//String cq = "select * from Login4";
//Cursor c = db.rawQuery(cq, null);
// c.moveToFirst();
//final String userName = c.getString(0);
//final String password = c.getString(1);
//String cloud = "avarote1994#gmail.com";
// AUTHENTICATE AND GET AN INSTANCE OF THE SESSION FROM THE SERVER
session = Session.getInstance(properties,new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
try {
store = session.getStore("imaps");
store.connect();
inbox = store.getFolder("INBOX"); // ACCESS THE INBOX OF THE RECEPIENT'S EMAIL ID
inbox.open(Folder.READ_WRITE); // OPEN THE INBOX IN READ-WRITE MODE
Message messages[] = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false)); //SEARCH INBOX FOR ANY UNREAD MAILS
System.out.println("Number of mails = " + messages.length);
for (int i = 0; i < messages.length; i++) { // PROCESS ALL THE UNREAD MAILS
message = messages[i];
Address[] from = message.getFrom();
String from1 = from[0].toString();
System.out.println(from1);
if(from1.contains("<")){
int start = from1.indexOf("<");
int end = from1.indexOf(">");
fromSubString = from1.substring(start+1,end); // RETRIEVE THE SENDER'S EMAIL ID
} else{
fromSubString = from1;
}
System.out.println(fromSubString);
//if(fromSubString.equals(cloud)){ // CHECK WHETHER THE MAIL IS FROM THE CLOUD
String[] subject = message.getSubject().split(","); // SPLIT THE SUBJECT
System.out.println("hi");
type = subject[0]; // STORE THE DETAILS IN RESPECTIVE VARIABLES
phoneNumber =subject[1];
name = subject[2];
System.out.println(type);
System.out.println(phoneNumber);
System.out.println(name);
//String body=message.getContentType().toString();
// System.out.print(body);
processMessageBody(message);
//System.out.println("--------------------------------");
// }
}
inbox.close(true);
store.close();
}
catch (NoSuchProviderException e) {
e.printStackTrace();
}
catch (MessagingException e) {
e.printStackTrace();
}
}
}
public void processMessageBody(Message message) {
try {
Object content = message.getContent();
String msg=content.toString();
System.out.println(msg);
if (content instanceof Multipart) { // IF MAIL HAS MULTIPART MESSAGE
Multipart multiPart = (Multipart) content;
procesMultiPart(multiPart);
}
else{
System.out.println("Content = "+content);
processSinglepart(content.toString());
}
}
catch (IOException e) {
e.printStackTrace();
}
catch (MessagingException e) {
e.printStackTrace();
}
}
public void processSinglepart(String content){
String[] body = content.split(","); // SPLIT THE CONTENTS OF THE BODY
System.out.println('1');
time_stamp = body[0]; // STORE THE DETAILS IN RESPECTIVE VARIABLES
command = body[3];
System.out.println(time_stamp);
//tts.speak(time_stamp, TextToSpeech.QUEUE_FLUSH, null);
publishProgress(command);
}
public void procesMultiPart(Multipart content) {
System.out.println("amulya");
try {
BodyPart bodyPart = content.getBodyPart(0); // RETRIEVE THE CONTENTS FROM THE BODY
Object o;
o = bodyPart.getContent();
if (o instanceof String) {
System.out.println("Content Multipart= "+o.toString());
processSinglepart(o.toString());
}
}
catch (IOException e) {
e.printStackTrace();
}
catch (MessagingException e) {
e.printStackTrace();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
c = this.getApplicationContext();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ReadMailSample rd=new ReadMailSample(getApplicationContext());
System.out.println("hello");
rd.execute();
System.out.println("------xvsdfsdfsd---------aefaefa-----------------");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I am trying to implement texttospeech functionality. I am getting the above error. The functionality runs in async thread. The async thread reads mail. I want to convert the read mail to speech.
Logcat:
02-08 21:45:26.009: I/System.out(12947): TESTING
02-08 21:45:26.709: I/System.out(12947): javax.mail.internet.MimeMultipart#21cdab10
02-08 21:45:26.709: I/System.out(12947): amulya
02-08 21:45:27.279: I/System.out(12947): Content Multipart= 1221235487821,ad:af:12:2a:d5:c8,High,IT IS THURSDAY TAKE TABLETS,future
02-08 21:45:27.279: I/System.out(12947): use,future use,future use
02-08 21:45:27.279: I/System.out(12947): 1
02-08 21:45:27.279: I/System.out(12947): 1221235487821
02-08 21:45:27.279: I/System.out(12947): ---------------------adasd-----------1221235487821
02-08 21:45:27.299: W/TextToSpeech(12947): speak failed: TTS engine connection not fully set up
02-08 21:45:29.689: D/dalvikvm(12947): GC_FOR_ALLOC freed 455K, 19% free 5727K/7068K, paused 7ms, total 7ms
02-08 21:45:30.499: I/System.out(12947): Number of mails = 0
02-08 21:45:36.029: I/System.out(12947): Number of mails = 0
I have solved this issue with audible speech
import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import java.util.HashMap;
import java.util.Locale;
public class Speecher implements TextToSpeech.OnInitListener {
private static final String TAG = "TextToSpeechController";
private TextToSpeech myTTS;
private String textToSpeak;
private Context context;
private static Speecher singleton;
public static Speecher getInstance(Context ctx) {
if (singleton == null)
singleton = new Speecher(ctx);
return singleton;
}
private Speecher(Context ctx) {
context = ctx;
}
public void speak(String text) {
textToSpeak = text;
if (myTTS == null) {
// currently can\'t change Locale until speech ends
try {
// Initialize text-to-speech. This is an asynchronous operation.
// The OnInitListener (second argument) is called after
// initialization completes.
myTTS = new TextToSpeech(context, this);
} catch (Exception e) {
e.printStackTrace();
}
}
sayText();
}
public void onInit(int initStatus) {
if (initStatus == TextToSpeech.SUCCESS) {
if (myTTS.isLanguageAvailable(Locale.UK) == TextToSpeech.LANG_AVAILABLE)
myTTS.setLanguage(Locale.UK);
myTTS.setPitch((float) 0.9);
}
// status can be either TextToSpeech.SUCCESS or TextToSpeech.ERROR.
if (initStatus == TextToSpeech.SUCCESS) {
int result = myTTS.setLanguage(Locale.UK);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e(TAG, "TTS missing or not supported (" + result + ")");
// Language data is missing or the language is not supported.
// showError(R.string.tts_lang_not_available);
} else {
// Initialization failed.
Log.e(TAG, "Error occured");
}
}
}
private void sayText() {
HashMap<String, String> myHash = new HashMap<String, String>();
myHash.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "done");
String[] splitspeech = this.textToSpeak.split("\\\\");
for (int i = 0; i < splitspeech.length; i++) {
if (i == 0) { // Use for the first splited text to flush on audio stream
myTTS.speak(splitspeech[i].toString().trim(), TextToSpeech.QUEUE_FLUSH, myHash);
} else { // add the new test on previous then play the TTS
myTTS.speak(splitspeech[i].toString().trim(), TextToSpeech.QUEUE_ADD, myHash);
}
myTTS.playSilence(100, TextToSpeech.QUEUE_FLUSH, null);
}
}
public void stopTTS() {
if (myTTS != null) {
myTTS.shutdown();
myTTS.stop();
myTTS = null;
}
}
}
Calling method from any where...
Speecher.getInstance(getApplicationContext()).speak(YOUR_TTS_MESSAGE_HERE);
From the Api Docs we see that your implementation of OnInitListener is necessesary to receive a notification that the TTS initialization is complete. This is described in the TextToSpeech docs as well where it is stated that the speech will fail until initialized. In the following, I will not attempt to fix all of your code so that it works, but I will point out how you're mis-using the TTS framework currently and nudge you in the right direction.
Though you have implemented onInitListener, you aren't doing anything useful with that implementation. Below, I show something more useful in which one captures the result of onInitListener's onInit callback, in order to remain aware of the initialization state of TTS.
...
private boolean mIsTTSInited = false; // member indicating TTS initialization state
...
// Receives notification of initialization
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
Log.i("TTS", "Initilization Succeeded!");
// save the state indicating success of TTS initialization
mIsTTSInited = true;
...
} else {
Log.e("TTS", "Initilization Failed!");
mIsTTSInited = false;
}
}
...
...
#Override
protected void onProgressUpdate(String... values) {
// A trivial example to show how you can check the state of initialization for TTS
if (mIsTTSInited) {
showNotification();
speakOut();
} else {
// code to deal with TTS not init'ed case
}
}
Additionally, I wouldn't run the TextToSpeech initialization as part of the AsyncTask. If I were you, I'd move
tts = new TextToSpeech(c,ReadMailSample.this);
into onCreate rather than onPreExecute. I see this used in the tutorials seen here, and here
Related
I am making a attendance application that uses NFC technology. An NFC tag act as the student ID.
however I need to input atleast two (2) data from student to the tag. I came across on a video on yt and copy the whole code and add two lines because I need two data but it seems it doesnt work lol! i hope you help me with this one
this is my code
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
//import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
public class writeHome extends AppCompatActivity {
public static final String Error_Detected = "No NFC Tag Detected!";
public static final String Write_Success = "Text Written Successfully!";
public static final String Write_Error = "Error during Writing, Try again!";
NfcAdapter nfcAdapter;
PendingIntent pendingIntent;
IntentFilter[] writingTagFilters;
boolean writeMode;
Tag myTag;
Context context;
TextView editTextTextPersonName7;
TextView editTextTextPersonName3;
// read
Button button2;
#RequiresApi(api = Build.VERSION_CODES.S)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_write_home);
editTextTextPersonName7 = findViewById(R.id.editTextTextPersonName7);
editTextTextPersonName3 = findViewById(R.id.editTextTextPersonName3);
button2 = findViewById(R.id.button2);
context = this;
button2.setOnClickListener(view -> {
try {
if(myTag == null) {
Toast.makeText(context, Error_Detected, Toast.LENGTH_LONG).show();
} else {
write(editTextTextPersonName7.getText().toString(), myTag);
write(editTextTextPersonName3.getText().toString(), myTag);
Toast.makeText(context, Write_Success, Toast.LENGTH_SHORT).show();
}
} catch (IOException | FormatException e) {
Toast.makeText(context, Write_Error, Toast.LENGTH_LONG).show();
e.printStackTrace();
}
});
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if(nfcAdapter == null) {
Toast.makeText(this, "This device does not support NFC!", Toast.LENGTH_SHORT).show();
}
readFromIntent(getIntent());
pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE);
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
writingTagFilters = new IntentFilter[] { tagDetected };
}
private void readFromIntent(Intent intent) {
String action = intent.getAction();
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage[] msgs = null;
if (rawMsgs != null) {
msgs = new NdefMessage[rawMsgs.length];
for (int i = 0; i< rawMsgs.length; i++) {
msgs[i] = (NdefMessage) rawMsgs[i];
}
}
buildTagViews(msgs);
}
}
private void buildTagViews(NdefMessage[] msgs) {
if (msgs == null || msgs.length == 0) return;
String text = "";
String text2 = "";
byte [] payload = msgs [0].getRecords()[0].getPayload();
String textEncoding = ((payload [0]&128) == 0) ? "UTF-8" : "UTF-16";
int languageCodeLength = payload[0] & 51;
try {
text= new String(payload, languageCodeLength +1, payload.length - languageCodeLength - 1, textEncoding);
} catch (UnsupportedEncodingException e) {
Log.e("UnsupportedEncoding", e.toString());
}
//output
editTextTextPersonName7.setText(text);
editTextTextPersonName3.setText(text2);
}
private void write(String text, Tag tag) throws IOException, FormatException {
NdefRecord[] records = { createRecord(text) };
NdefMessage message = new NdefMessage(records);
Ndef ndef = Ndef.get(tag);
ndef.connect();
ndef.writeNdefMessage(message);
ndef.close();
}
private NdefRecord createRecord(String text) {
String lang = "en";
byte[] textBytes = text.getBytes();
byte[] langBytes = lang.getBytes(StandardCharsets.US_ASCII);
int langLength = langBytes.length;
int textLength = textBytes.length;
byte[] payload = new byte[1 + langLength + textLength];
payload[0] = (byte) langLength;
System.arraycopy(langBytes, 0, payload, 1, langLength);
System.arraycopy(langBytes, 0, payload, 1+langLength, textLength);
return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload);
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
readFromIntent(intent);
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
myTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
}
}
#Override
public void onPause() {
super.onPause();
WriteModeOff();
}
#Override
public void onResume() {
super.onResume();
WriteModeOn();
}
//write & read switches
private void WriteModeOn() {
writeMode = true;
String[][] techList = new String[][] { { android.nfc.tech.Ndef.class.getName() }, { android.nfc.tech.NdefFormatable.class.getName() } };
nfcAdapter.enableForegroundDispatch(this, pendingIntent, writingTagFilters,techList);
}
private void WriteModeOff() {
writeMode = false;
nfcAdapter.disableForegroundDispatch(this);
}
}````
I don't know much of these as I am new to programming. Can someone teach me how to make this work? Also I put this in a way that the output can be viewed on the input section if that make sense. I just copy this code from youtube so I didnt expect this to work at all. thanks!
I tried to read as much I can understand but I really don't know what to do so I wrote another question even though this was already ask before.
I just want to record two string data into NFC tag
also if you want to rewrite the code with the same id that would be great! thanks!
Hi I am currently facing issues with connection and reading of BLE devices. I think I have connected as the code below prints a message for connection, however the reading of values from the BLE device does not seem to work. The service uuid returns a null value.
package com.example.asp_sqllite;
import android.Manifest;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.ParcelUuid;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.UUID;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
public class PlayActivity extends AppCompatActivity {
private static final int REQUEST_ENABLE_BT =1 ;
private Button btnPlay;
private Button btnConnect;
private ListView btList;
SQLiteDatabase db;
private Handler handler;
private ArrayList<String> deviceList = new ArrayList<>();
private ArrayAdapter<String> testAdapter;
private ArrayAdapter<String> deviceAdapter;
private BluetoothAdapter bluetoothAdapter;
private BluetoothLeScanner bleScanner;
private BluetoothGatt bleGatt;
private ArrayList<ScanResult> results = new ArrayList<>();
private ScanSettings settings;
private Intent intent;
private ListView bluetoothList;
private boolean completed = false;
static final UUID HR_SERVICE_UUID = UUID.fromString("0000110a-0000-1000-8000-00805f9b34fb");
private static final UUID HEART_RATE_MEASUREMENT_CHARACTERISTIC_UUID = UUID.fromString("00002A37-0000-1000-8000-00805f9b34fb");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
this.handler= new Handler();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ) {
checkPermission();
}
BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
bluetoothAdapter = bluetoothManager.getAdapter();
this.btList = (ListView) findViewById(R.id.btlist);
deviceAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1);
testAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, android.R.id.text1);
intent = getIntent();
db = openOrCreateDatabase("myDB.db", MODE_PRIVATE, null);
checkBluetooth();
this.btnPlay = (Button) findViewById(R.id.btnPlay);
this.btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(bleGatt!=null) {
final String username = intent.getStringExtra("username");
System.out.println(username+"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
String sqlStatement = "insert into records (Name) values( '" + username + "')";
String result = updateTable(sqlStatement);
/*
* Run query to get recid to be passed over to the next activity
*
* */
final Cursor cursor = db.rawQuery("SELECT recID From records", null);
int num = 0;
if (cursor != null) {
cursor.moveToLast();
num = cursor.getInt(0);
cursor.close();
db.close();
}
Intent intent = new Intent(PlayActivity.this, testPlayActivity.class);
intent.putExtra("ID", Integer.toString(num));
startActivity(intent);
}
else
Toast.makeText(getApplicationContext(),"Connect to BLE device", Toast.LENGTH_LONG).show();
//finish();
}
});
this.btnConnect = (Button) findViewById(R.id.connect);
this.btnConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startScan();
Dialog d = new Dialog(PlayActivity.this); //open up dialog box with listview
d.setContentView(R.layout.bluetooth_device);
d.setTitle("Devices");
d.show();
//stopScan();
Button scanBtn = d.findViewById(R.id.scanBluetooth);
bluetoothList = d.findViewById(R.id.bluetoothDeviceList);
bluetoothList.setAdapter(deviceAdapter);
bluetoothList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
ScanResult device = results.get(i);
Toast.makeText(getApplicationContext(), device.getDevice().getName(), Toast.LENGTH_LONG).show();
bleGatt = device.getDevice().connectGatt(getApplicationContext(), false, bleGattCallback);
System.out.println("##############################################testing 123");
//finish();
try {
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
Method getUuidsMethod = BluetoothAdapter.class.getDeclaredMethod("getUuids", null);
ParcelUuid[] uuids = (ParcelUuid[]) getUuidsMethod.invoke(adapter, null);
if(uuids != null) {
for (ParcelUuid uuid : uuids) {
System.out.println(uuid.getUuid().toString()+"#############################");
}
}else{
System.out.println("fail");
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
});
scanBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) { //clear all list and adapters before scanning again
deviceList.clear();
deviceAdapter.clear();
results.clear();
startScan();
//stopScan();
handler.postDelayed(new Runnable() {
#Override
public void run() {
stopScan();
}
},5000);
}
});
handler.postDelayed(new Runnable() {
#Override
public void run() {
stopScan();
}
},5000);
}
});
}
public void checkPermission(){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
){//Can add more as per requirement
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},
123);
}
}
private void checkBluetooth()
{
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
private String updateTable(String sql) {
try {
db.beginTransaction();
db.execSQL(sql);
db.setTransactionSuccessful();
db.endTransaction();
} catch (Exception e) {
System.out.println(e.toString());
return ("Error");
}
Toast.makeText(this, "DB updated", Toast.LENGTH_LONG).show();
return ("Welcome");
}
private void stopScan(){
bleScanner = bluetoothAdapter.getBluetoothLeScanner();
bleScanner.stopScan(scanCallback);
}
private void startScan() {
bleScanner = bluetoothAdapter.getBluetoothLeScanner();
if (bleScanner != null) { //setting up of scanner
final ScanFilter scanFilter =new ScanFilter.Builder().build();
settings =new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
bleScanner.startScan(Arrays.asList(scanFilter), settings, scanCallback);
//stopScan();
}
else
checkBluetooth();
}
private ScanCallback scanCallback = new ScanCallback() { //scan and return device results
#Override
public void onScanResult(int callbackType, ScanResult result) {
System.out.println("######### "+callbackType + result);
if (bleScanner != null && !deviceList.contains(result.getDevice().getName())) {
deviceList.add(result.getDevice().getName());
String device = result.getDevice().getName() + "\n" + result.getDevice().getAddress();
deviceAdapter.add(device); //Store device name and address
results.add(result); //records found devices as ScanResult
}
}
public void onScanFailed(int errorCode) {
super.onScanFailed(errorCode);
Log.e("TAG","onScanFailed");
}
};
private BluetoothGattCallback bleGattCallback = new BluetoothGattCallback()
{
#Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (newState== BluetoothProfile.STATE_CONNECTED){
System.out.println("#################################################################Connected");
}
else if (newState == BluetoothProfile.STATE_DISCONNECTED)
{
System.out.println("################################################################Not Connected");
}
gatt.discoverServices();
super.onConnectionStateChange(gatt, status, newState);
}
#Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
BluetoothGattService service = gatt.getService(HR_SERVICE_UUID);
System.out.println(service+"!!!!!!!!!!!!!!!!!!!!!!");
BluetoothGattCharacteristic temperatureCharacteristic = service.getCharacteristic(HEART_RATE_MEASUREMENT_CHARACTERISTIC_UUID);
gatt.readCharacteristic(temperatureCharacteristic);
super.onServicesDiscovered(gatt, status);
}
#Override
public void onCharacteristicRead(BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, int status) {
final String value = characteristic.getStringValue(0);
runOnUiThread(new Runnable() {
#Override
public void run() {
if(HEART_RATE_MEASUREMENT_CHARACTERISTIC_UUID.equals(characteristic.getUuid())) {
//Toast.makeText(getApplicationContext(), "Correct Bluetooth: " + value, Toast.LENGTH_LONG).show();
System.out.println("###########################################################correct");
} else {
//Toast.makeText(getApplicationContext(), "Wrong Bluetooth", Toast.LENGTH_LONG).show();
System.out.println("##############################################################wrong");
}
}
});
BluetoothGattService service = gatt.getService(HR_SERVICE_UUID);
//readNextCharacteristic(gatt, characteristic);
super.onCharacteristicRead(gatt, characteristic, status);
}
};
}
The code is an example in arduino library(BLE_Example/BLE_HRM)
/*
* Copyright (c) 2016 RedBear
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
/**
* #note This demo is Nordic HRM example.
* You could use nRF toolbox tool to test it.
*/
#include <nRF5x_BLE_API.h>
#define DEVICE_NAME "Nordic_HRM"
BLE ble;
Ticker ticker_task1;
static uint8_t hrmCounter = 100;
static uint8_t bpm[2] = {0x00, hrmCounter};
static const uint8_t location = 0x03;
static const uint16_t uuid16_list[] = {GattService::UUID_HEART_RATE_SERVICE};
// Create characteristic and service
GattCharacteristic hrmRate(GattCharacteristic::UUID_HEART_RATE_MEASUREMENT_CHAR, bpm, sizeof(bpm), sizeof(bpm), GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY);
GattCharacteristic hrmLocation(GattCharacteristic::UUID_BODY_SENSOR_LOCATION_CHAR,(uint8_t *)&location, sizeof(location), sizeof(location),GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ);
GattCharacteristic *hrmChars[] = {&hrmRate, &hrmLocation, };
GattService hrmService(GattService::UUID_HEART_RATE_SERVICE, hrmChars, sizeof(hrmChars) / sizeof(GattCharacteristic *));
void disconnectionCallBack(const Gap::DisconnectionCallbackParams_t *params) {
Serial.println("Disconnected!");
Serial.println("Restarting the advertising process");
ble.startAdvertising();
}
void periodicCallback() {
if (ble.getGapState().connected) {
// Update the HRM measurement
// First byte = 8-bit values, no extra info, Second byte = uint8_t HRM value
// See --> https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml
hrmCounter++;
if (hrmCounter == 175)
hrmCounter = 100;
bpm[1] = hrmCounter;
ble.updateCharacteristicValue(hrmRate.getValueAttribute().getHandle(), bpm, sizeof(bpm));
}
}
void setup() {
// put your setup code here, to run once
Serial.begin(9600);
Serial.println("Nordic_HRM Demo ");
// Init timer task
ticker_task1.attach(periodicCallback, 1);
// Init ble
ble.init();
ble.onDisconnection(disconnectionCallBack);
// setup adv_data and srp_data
ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
ble.accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, (uint8_t*)uuid16_list, sizeof(uuid16_list));
ble.accumulateAdvertisingPayload(GapAdvertisingData::HEART_RATE_SENSOR_HEART_RATE_BELT);
ble.accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME));
// set adv_type
ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
// add service
ble.addService(hrmService);
// set device name
ble.setDeviceName((const uint8_t *)DEVICE_NAME);
// set tx power,valid values are -40, -20, -16, -12, -8, -4, 0, 4
ble.setTxPower(4);
// set adv_interval, 100ms in multiples of 0.625ms.
ble.setAdvertisingInterval(160);
// set adv_timeout, in seconds
ble.setAdvertisingTimeout(0);
// start advertising
ble.startAdvertising();
}
void loop() {
// put your main code here, to run repeatedly:
ble.waitForEvent();
}
I got this code from the Internet and I modified it to upload a specific file automatically to Google Drive when starting the activity.
It is always ask me to select my Google account when I start this activity!
I want it ask about Google account once only when started for the first time after install it, How to do that?
package com.example.googledrive;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.util.Arrays;
import java.io.IOException;
import android.accounts.AccountManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.widget.Toast;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.http.FileContent;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
public class MainActivity extends Activity {
static final int REQUEST_ACCOUNT_PICKER = 1;
static final int REQUEST_AUTHORIZATION = 2;
static final int REQUEST_DOWNLOAD_FILE = 3;
static final int RESULT_STORE_FILE = 4;
private static Uri mFileUri;
private static Drive mService;
private GoogleAccountCredential mCredential;
private Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// setup for credentials for connecting to the Google Drive account
mCredential = GoogleAccountCredential.usingOAuth2(this, Arrays.asList(DriveScopes.DRIVE));
// start activity that prompts the user for their google drive account
startActivityForResult(mCredential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
// mContext = getApplicationContext();
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data)
{
switch (requestCode) {
case REQUEST_ACCOUNT_PICKER:
if (resultCode == RESULT_OK && data != null && data.getExtras() != null) {
String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
mCredential.setSelectedAccountName(accountName);
mService = getDriveService(mCredential);
}
saveFileToDrive();
}
break;
case REQUEST_AUTHORIZATION:
if (resultCode == Activity.RESULT_OK) {
//account already picked
} else {
startActivityForResult(mCredential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
}
break;
}
}
private Drive getDriveService(GoogleAccountCredential credential)
{
return new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential)
.build();
}
private void saveFileToDrive()
{
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
// Create URI from real path
String path;
path = "/sdcard/DCIM/Camera/a.png";
mFileUri = Uri.fromFile(new java.io.File(path));
ContentResolver cR = MainActivity.this.getContentResolver();
// File's binary content
java.io.File fileContent = new java.io.File(mFileUri.getPath());
FileContent mediaContent = new FileContent(cR.getType(mFileUri), fileContent);
showToast("Selected " + mFileUri.getPath() + "to upload");
// File's meta data.
File body = new File();
body.setTitle(fileContent.getName());
body.setMimeType(cR.getType(mFileUri));
com.google.api.services.drive.Drive.Files f1 = mService.files();
com.google.api.services.drive.Drive.Files.Insert i1 = f1.insert(body, mediaContent);
File file = i1.execute();
if (file != null)
{
showToast("Uploaded: " + file.getTitle());
}
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
showToast("Transfer ERROR: " + e.toString());
}
}
});
t.start();
}
public void showToast(final String toast)
{
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), toast, Toast.LENGTH_SHORT).show();
}
});
}
}
It's been a while, so you probably managed to do this by now, but I was just looking for the same thing and it's fairly easy. In the code you use and how it's used on several sites you get an Intent after calling a static method on GoogleAccountCredential.
You can also create your own, by calling a static method on AccountPicker and define a params that it's only required to pick once.
Intent accountPicker = AccountPicker.newChooseAccountIntent(null, null, new String[]{"com.google"}, false, null, null, null, null);
startActivityForResult(accountPicker, GOOGLE_ACCOUNT_PICKED);
The fourth param is what you want and you can read more about it here:
https://developers.google.com/android/reference/com/google/android/gms/common/AccountPicker?hl=en
Since I finally figured out that the registerReceiver() method is usually running on the UI-Thread, I now want to change that. I just need some advice of how I could do that.
How would I be able to change registerReceiver() to stop freezing my app?
My doInBackground() method from the AsyncTask, runs another method that is using the registerReceiver(mReceiver, filter) method (both variables are already defined). But I want to keep seeing my ProgressDialog instead of making the app freezing.
I read about using a Handler and a new Thread, but I need some help there.
Thanks in advance.
Code:
package ch.scs.mod.tools.messagegenerator.business;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.telephony.SmsManager;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import ch.scs.mod.tools.messagegenerator.R;
import ch.scs.mod.tools.messagegenerator.model.Testcase;
import ch.scs.mod.tools.messagegenerator.model.Testset;
public class ReportActivity extends Activity implements OnClickListener {
private static final String TAG = "ReportActivity";
private TextView title;
private TextView lblReport;
private TextView lblEmail;
private TableLayout tblReport;
private Button btnBack;
private Testset testset;
private Testcase testcase;
private List<Testcase> testcases = new ArrayList<Testcase>();
private String number;
private String apn = "not used";
private String error;
private ArrayList<String> resultarray = new ArrayList<String>();
private ProgressDialog progressdialog;
private boolean running = false;
public enum State {
UNKNOWN, CONNECTED, NOT_CONNECTED
}
private ConnectivityManager mConnMgr;
private PowerManager.WakeLock mWakeLock;
private ConnectivityBroadcastReceiver mReceiver;
private NetworkInfo mNetworkInfo;
private State mState;
private boolean mListening;
private boolean mSending;
private SendMms sendMms = SendMms.getInstance();
private MMSTest myTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.report);
title = (TextView) findViewById(R.id.lblTitle);
lblReport = (TextView) findViewById(R.id.lblReport);
lblEmail = (TextView) findViewById(R.id.lblMmsEmail);
tblReport = (TableLayout) findViewById(R.id.tblReport);
btnBack = (Button) findViewById(R.id.btnBack);
progressdialog = new ProgressDialog(this);
progressdialog.setTitle("Please wait...");
progressdialog.setMessage("Sending...");
progressdialog.setCancelable(false);
Typeface tf = Typeface.createFromAsset(getAssets(),
"fonts/TheSansB_TT4_App.ttf");
title.setTypeface(tf);
lblEmail.setTypeface(tf);
lblReport.setTypeface(tf);
btnBack.setTypeface(tf);
lblEmail.setText(Html
.fromHtml("<a href=\'mailto:mathias.hubacher#swisscom.com\'>mathias.hubacher#swisscom.com</a>"));
lblEmail.setMovementMethod(LinkMovementMethod.getInstance());
btnBack.setOnClickListener(this);
testset = (Testset) this.getIntent().getSerializableExtra("testset");
number = (String) this.getIntent().getStringExtra("number");
lblReport.setText(getResources().getString(R.string.reportText1) + " "
+ number + " " + getResources().getString(R.string.reportText2));
testcases = testset.getTestcases();
resultarray.clear();
// Creating Views for Asynctask
ScrollView sv = new ScrollView(this);
LinearLayout ll = new LinearLayout(this);
HorizontalScrollView hsv = new HorizontalScrollView(this);
sv.setLayoutParams(new ScrollView.LayoutParams(ScrollView.LayoutParams.MATCH_PARENT, getWindowManager().getDefaultDisplay().getHeight()/2));
sv.setVerticalScrollBarEnabled(true);
sv.setHorizontalScrollBarEnabled(true);
sv.setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);
hsv.setLayoutParams(new HorizontalScrollView.LayoutParams(HorizontalScrollView.LayoutParams.MATCH_PARENT, HorizontalScrollView.LayoutParams.MATCH_PARENT));
hsv.setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);
ll.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
ll.setOrientation(LinearLayout.VERTICAL);
for (Testcase testc : testcases) {
TableRow tr = new TableRow(this);
TextView tv = new TextView(this);
TextView tvok = new TextView(this);
TextView tverror = new TextView(this);
tr.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
tv.setText(testc.getName() + " ");
tv.setTextColor(getResources().getColor(R.color.white));
tr.addView(tv);
tvok.setText("Sending...");
tvok.setTextColor(getResources().getColor(R.color.white));
tverror.setText("");
tverror.setTextColor(getResources().getColor(R.color.orange));
tr.addView(tvok);
tr.addView(tverror);
ll.addView(tr);
testc.setTextView(tv);
testc.setTextViewOk(tvok);
testc.setTextViewError(tverror);
}
hsv.addView(ll);
sv.addView(hsv);
tblReport.addView(sv);
myTask = new MMSTest();
myTask.execute();
}
private void createSms(List<Testcase> tcs) {
for (Testcase testc : tcs) {
error = "";
if (!testc.isExecute()) {
resultarray.add(getResources().getString(R.string.notExe));
resultarray.add(error);
} else {
sendSms(number, testc);
if (testc.isSuccsess()) {
resultarray.add(getResources().getString(R.string.ok));
resultarray.add(error);
} else {
resultarray.add(getResources().getString(R.string.failed));
resultarray.add(error);
}
}
testc.setRunning(true);
myTask.onProgressUpdate(resultarray.get(resultarray.size()-2), resultarray.get(resultarray.size()-1));
}
}
private class MMSTest extends AsyncTask<String, String, ArrayList<String>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mReceiver = new ConnectivityBroadcastReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mReceiver, filter);
// progressdialog.show();
}
#Override
protected ArrayList<String> doInBackground(String... params) {
if (testset.getType().equals("sms")) {
Log.v(TAG, "Testtype SMS");
createSms(testcases);
} else if (testset.getType().equals("mms")) {
Log.v(TAG, "Testtype MMS");
mListening = true;
mSending = false;
mConnMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// mReceiver = new ConnectivityBroadcastReceiver();
apn = (String) ReportActivity.this.getIntent().getStringExtra("apn");
startMms();
} else {
lblReport.setText("Error Testset Type not valid");
}
return resultarray;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
for (Testcase testc : testcases) {
if (testc.getRunning()) {
TextView tvok = testc.getTextViewOk();
TextView tverror = testc.getTextViewError();
if (testc.isExecute()) {
if (testc.isSuccsess()) {
tvok.setText(values[0]);
tvok.setTextColor(getResources().getColor(R.color.green));
tverror.setText(values[1]);
tverror.setTextColor(getResources().getColor(R.color.orange));
}
else {
tvok.setText(values[0]);
tvok.setTextColor(getResources().getColor(R.color.red));
tverror.setText(values[1]);
tverror.setTextColor(getResources().getColor(R.color.white));
}
}
else {
tvok.setText(values[0]);
tvok.setTextColor(getResources().getColor(R.color.red));
tverror.setText(values[1]);
tverror.setTextColor(getResources().getColor(R.color.white));
}
testc.setRunning(false);
break;
}
}
}
#Override
protected void onPostExecute(ArrayList<String> result) {
super.onPostExecute(result);
// int r = 0;
// for (Testcase testc : testcases) {
// TextView tvok = testc.getTextViewOk();
// TextView tverror = testc.getTextViewError();
// if (testc.isExecute()) {
// if (testc.isSuccsess()) {
// tvok.setText(result.get(r));
// tvok.setTextColor(getResources().getColor(R.color.green));
// tverror.setText(result.get(r+1));
// tverror.setTextColor(getResources().getColor(R.color.orange));
// }
// else {
// tvok.setText(result.get(r));
// tvok.setTextColor(getResources().getColor(R.color.red));
// tverror.setText(result.get(r+1));
// tverror.setTextColor(getResources().getColor(R.color.white));
// }
// }
// else {
// tvok.setText(result.get(r));
// tvok.setTextColor(getResources().getColor(R.color.red));
// tverror.setText(result.get(r+1));
// tverror.setTextColor(getResources().getColor(R.color.white));
// }
// r = r + 2;
// }
// progressdialog.dismiss();
}
}
private void sendMms() {
int responseCode=0;
for (Testcase testc : testcases) {
error = "";
if (testc.isExecute()) {
File file = new File(Environment.getExternalStorageDirectory(), ".MODTest/" + testc.getContentFile());
if (file.exists()) {
if (file.length() > 300000) {
Log.v(TAG, "File Length="+ Long.toString(file.length()));
error=getResources().getString(R.string.warningFileSize);
}
responseCode = sendMms.startMms(testc.getSubject(), number, apn, testc.getContentFile(), testc.getContentType(), getApplicationContext());
Log.v(TAG,"Test: "+ testc.getName() + " / Response code: " + Integer.toString(responseCode));
if (responseCode == 200) {
testc.setSuccsess(true);
responseCode = 0;
} else {
testc.setSuccsess(false);
error =Integer.toString(responseCode);
}
} else {
testc.setSuccsess(false);
error =getResources().getString(R.string.errorNoFile);
}
if (testc.isSuccsess()) {
resultarray.add(getResources().getString(R.string.ok) + " ");
resultarray.add(error);
} else {
resultarray.add(getResources().getString(R.string.failed) + " ");
resultarray.add(error);
}
} else {
resultarray.add(getResources().getString(R.string.notExe));
resultarray.add(error);
}
testc.setRunning(true);
myTask.onProgressUpdate(resultarray.get(resultarray.size()-2), resultarray.get(resultarray.size()-1));
}
endMmsConnectivity();
mSending = false;
mListening = false;
}
public void startMms() {
for (Testcase tcs : testcases) {
testcase = tcs;
number = number + "/TYPE=PLMN";
// IntentFilter filter = new IntentFilter();
// filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
// registerReceiver(mReceiver, filter);
try {
// Ask to start the connection to the APN. Pulled from Android
// source code.
int result = beginMmsConnectivity();
Log.v(TAG, "Result= " + Integer.toString(result));
if (result != PhoneEx.APN_ALREADY_ACTIVE) {
Log.v(TAG, "Extending MMS connectivity returned " + result
+ " instead of APN_ALREADY_ACTIVE");
// Just wait for connectivity startup without
// any new request of APN switch.
return;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void sendSms(String nr, Testcase tc) {
if (!tc.getBody().equals("")) {
SmsManager sm = SmsManager.getDefault();
sm.getDefault().sendTextMessage(nr, null, tc.getBody(), null, null);
tc.setSuccsess(true);
} else {
tc.setSuccsess(false);
error = getResources().getString(R.string.errorEmptySms);
}
}
#Override
public void onClick(View v) {
if (v.equals(findViewById(R.id.btnBack))) { // Wenn Button zurück
// geklickt wird
Intent startMmsTest = new Intent(ReportActivity.this,
StartActivity.class);
startActivity(startMmsTest);
}
}
protected void endMmsConnectivity() {
// End the connectivity
try {
Log.v(TAG, "endMmsConnectivity");
if (mConnMgr != null) {
mConnMgr.stopUsingNetworkFeature(
ConnectivityManager.TYPE_MOBILE,
PhoneEx.FEATURE_ENABLE_MMS);
}
} finally {
releaseWakeLock();
}
}
protected int beginMmsConnectivity() throws IOException {
// Take a wake lock so we don't fall asleep before the message is
// downloaded.
createWakeLock();
int result = mConnMgr.startUsingNetworkFeature(
ConnectivityManager.TYPE_MOBILE, PhoneEx.FEATURE_ENABLE_MMS);
Log.v(TAG, "beginMmsConnectivity: result=" + result);
switch (result) {
case PhoneEx.APN_ALREADY_ACTIVE:
case PhoneEx.APN_REQUEST_STARTED:
acquireWakeLock();
return result;
}
throw new IOException("Cannot establish MMS connectivity");
}
private synchronized void createWakeLock() {
// Create a new wake lock if we haven't made one yet.
if (mWakeLock == null) {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"MMS Connectivity");
mWakeLock.setReferenceCounted(false);
}
}
private void acquireWakeLock() {
// It's okay to double-acquire this because we are not using it
// in reference-counted mode.
mWakeLock.acquire();
}
private void releaseWakeLock() {
// Don't release the wake lock if it hasn't been created and acquired.
if (mWakeLock != null && mWakeLock.isHeld()) {
mWakeLock.release();
}
}
private class ConnectivityBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
int responseCode;
String action = intent.getAction();
if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)
|| mListening == false) {
Log.w(TAG, "onReceived() called with " + mState.toString()
+ " and " + intent);
return;
}
boolean noConnectivity = intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if (noConnectivity) {
mState = State.NOT_CONNECTED;
} else {
mState = State.CONNECTED;
}
mNetworkInfo = (NetworkInfo) intent
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
// mOtherNetworkInfo = (NetworkInfo) intent
// .getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
// mReason =
// intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
// mIsFailover =
// intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER,
// false);
// Check availability of the mobile network.
if (mNetworkInfo == null) {
/**
* || (mNetworkInfo.getType() !=
* ConnectivityManager.TYPE_MOBILE)) {
*/
Log.v(TAG, " type is not TYPE_MOBILE_MMS, bail");
return;
}
if (!mNetworkInfo.isConnected()) {
Log.v(TAG, " TYPE_MOBILE_MMS not connected, bail");
return;
} else {
Log.v(TAG, "connected..");
if (mSending == false) {
mSending = true;
sendMms();
}
}
}
}
}
Move it to onProgressUpdate() method, or better , onPostExecute()/onPreExecuteMethod() depending on your need.
These methods run on UI thread and not on the new thread creetaed by the Asynctask
I'm trying to get user location in the background.
Everything works great on my phone (htc one m7), but from some reason it's not working on two devices I tested:
Samsung galaxy s3
Sony Xperia Z1
btw: I added everything to the manifest as it should be.
this is my code:
**BackgroundLocationService **
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationRequest;
public class BackgroundLocationService extends Service implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
IBinder mBinder = new LocalBinder();
private LocationClient mLocationClient;
private LocationRequest mLocationRequest;
// Flag that indicates if a request is underway.
private boolean mInProgress;
private Boolean servicesAvailable = false;
public class LocalBinder extends Binder {
public BackgroundLocationService getServerInstance() {
return BackgroundLocationService.this;
}
}
#Override
public void onCreate() {
super.onCreate();
mInProgress = false;
// Create the LocationRequest object
mLocationRequest = LocationRequest.create();
// Use high accuracy
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
// Set the update interval to 5 seconds
mLocationRequest.setInterval(0);
// Set the fastest update interval to 1 second
mLocationRequest.setFastestInterval(1);
servicesAvailable = servicesConnected();
/*
* Create a new location client, using the enclosing class to
* handle callbacks.
*/
mLocationClient = new LocationClient(this, this, this);
}
private boolean servicesConnected() {
// Check that Google Play services is available
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode) {
return true;
} else {
return false;
}
}
public int onStartCommand (Intent intent, int flags, int startId)
{
super.onStartCommand(intent, flags, startId);
if(!servicesAvailable || mLocationClient.isConnected() || mInProgress)
return START_STICKY;
setUpLocationClientIfNeeded();
if(!mLocationClient.isConnected() || !mLocationClient.isConnecting() && !mInProgress)
{
mInProgress = true;
mLocationClient.connect();
}
return START_STICKY;
}
/*
* Create a new location client, using the enclosing class to
* handle callbacks.
*/
private void setUpLocationClientIfNeeded()
{
if(mLocationClient == null)
mLocationClient = new LocationClient(this, this, this);
}
// Define the callback method that receives location updates
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public void appendLog(String text, String filename)
{
File logFile = new File(filename);
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onDestroy(){
// Turn off the request flag
mInProgress = false;
if(servicesAvailable && mLocationClient != null) {
//mLocationClient.removeLocationUpdates(callbackIntent);
// Destroy the current location client
mLocationClient = null;
}
// Display the connection status
// Toast.makeText(this, DateFormat.getDateTimeInstance().format(new Date()) + ": Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
super.onDestroy();
}
/*
* Called by Location Services when the request to connect the
* client finishes successfully. At this point, you can
* request the current location or start periodic updates
*/
#Override
public void onConnected(Bundle bundle) {
// Request location updates using static settings
Intent intent = new Intent(this, LocationReceiver.class);
PendingIntent locationIntent = PendingIntent.getBroadcast(getApplicationContext(), 14872, intent, PendingIntent.FLAG_CANCEL_CURRENT);
mLocationClient.requestLocationUpdates(mLocationRequest, locationIntent);
}
/*
* Called by Location Services if the connection to the
* location client drops because of an error.
*/
#Override
public void onDisconnected() {
// Turn off the request flag
mInProgress = false;
// Destroy the current location client
mLocationClient = null;
// Display the connection status
// Toast.makeText(this, DateFormat.getDateTimeInstance().format(new Date()) + ": Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
}
/*
* Called by Location Services if the attempt to
* Location Services fails.
*/
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
mInProgress = false;
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
// If no resolution is available, display an error dialog
} else {
}
}
}
**LocationReceiver **
import java.util.List;
import java.util.Locale;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.util.Log;
import com.google.android.gms.location.LocationClient;
public class LocationReceiver extends BroadcastReceiver {
public static double lat;
public static double alt;
public static String address;
#Override
public void onReceive(Context context, Intent intent) {
Location location = (Location) intent.getExtras().get(LocationClient.KEY_LOCATION_CHANGED);
Log.d("New Location Reciver", "location "+location.toString());
lat = location.getLatitude();
alt = location.getAltitude();
address = getAddressByCord(lat, alt, context);
}
public static String getAddressByCord(double lat, double longi, Context context) {
try {
Geocoder geo = new Geocoder(context, Locale.getDefault());
List<Address> addresses = geo.getFromLocation(lat, longi, 1);
if (addresses.isEmpty()) {
return "Waiting for Location";
} else {
if (addresses.size() > 0) {
String s = "";
if (addresses.get(0).getFeatureName() != null)
s += addresses.get(0).getFeatureName();
if (addresses.get(0).getThoroughfare() != null)
s += "," + addresses.get(0).getThoroughfare();
if (addresses.get(0).getLocality() != null)
s += "," + addresses.get(0).getLocality();
if (addresses.get(0).getAdminArea() != null)
s += "," + addresses.get(0).getAdminArea();
if (addresses.get(0).getCountryName() != null)
s += "," + addresses.get(0).getCountryName();
return s;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}
if someone has any idea, Thank you!
code to check for google play services.
private static final int CONNECTION_FAILURE_RESOLUTION_REQUEST = 94378;
private boolean isGooglePlay() {
int mIsGooglePlayServicesAvailable = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(context);
switch (mIsGooglePlayServicesAvailable) {
case ConnectionResult.SUCCESS:
return true;
default:
Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(
mIsGooglePlayServicesAvailable, this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
// If Google Play services can provide an error dialog
if (errorDialog != null) {
// Create a new DialogFragment for the error dialog
ErrorDialogFragment errorFragment = new ErrorDialogFragment();
// Set the dialog in the DialogFragment
errorFragment.setDialog(errorDialog);
// Show the error dialog in the DialogFragment
errorFragment.show(getSupportFragmentManager(),
"Location Updates");
}
// case ConnectionResult.SERVICE_MISSING:
// case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
// case ConnectionResult.SERVICE_DISABLED:
// case ConnectionResult.SERVICE_INVALID:
// case ConnectionResult.DATE_INVALID:
}
return false;
}
/*
* This is a class used to resolve errors with google play services It is
* copied code that doesn't run durring normal operation.
*/
public static class ErrorDialogFragment extends DialogFragment {
// Global field to contain the error dialog
private Dialog mDialog;
// Default constructor. Sets the dialog field to null
public ErrorDialogFragment() {
super();
mDialog = null;
}
// Set the dialog to display
public void setDialog(Dialog dialog) {
mDialog = dialog;
}
// Return a Dialog to the DialogFragment.
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return mDialog;
}
}
I found the answer.
It was the devices own definitions.
The device was not enabling apps to use location .
thank you anyway!