I have it set up so that when the user hits "clock in" it starts the intentservice, the intent service then updates the ui, the only problem is its not working.... here is my code for the main activity page :
package com.famousmods.payme;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
import android.graphics.PorterDuff;
public class PayTracker extends Activity {
private ResponseReceiver receiver;
private static double Reserve;
private static int Reserve1;
public static double money;
public static double counter;
private static int go;
private static int countdown;
public static int convert;
public static double HW;
public static double OTW;
public static double HPD;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pay_tracker);
getActionBar().setDisplayHomeAsUpEnabled(true);
// register reciver
IntentFilter filter = new IntentFilter(ResponseReceiver.ACTION_RESP);
filter.addCategory(Intent.CATEGORY_DEFAULT);
receiver = new ResponseReceiver();
registerReceiver(receiver, filter);
// Receive messages from options page
double pHW, pOTW, pHPD;
Intent intent = getIntent();
pHW = intent.getDoubleExtra(Options.MESSAGE_HW, 0);
pOTW = intent.getDoubleExtra(Options.MESSAGE_OTW, 0);
pHPD = intent.getDoubleExtra(Options.MESSAGE_HPD, 0);
if(pHW != 0){
HW = pHW;
OTW = pOTW;
HPD = pHPD;
}
// Color buttons
Button buttonc = (Button) findViewById(R.id.clockin);
buttonc.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);
Button buttond = (Button) findViewById(R.id.clockout);
buttond.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);
final Button b = (Button) findViewById(R.id.clockout);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_pay_tracker, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
};
return super.onOptionsItemSelected(item);
}
public void sendMessage(View view) {
//Start IntentService
Intent msgIntent = new Intent(this, SimpleIntentService.class);
msgIntent.putExtra(SimpleIntentService.PARAM_IN_HW, HW);
msgIntent.putExtra(SimpleIntentService.PARAM_IN_OTW, OTW);
msgIntent.putExtra(SimpleIntentService.PARAM_IN_HPD, HPD);
startService(msgIntent);//}
}
public class ResponseReceiver extends BroadcastReceiver {
public static final String ACTION_RESP = "com.famousmods.payme.action.MESSAGE_PROCESSED";
#Override
public void onReceive(Context context, Intent intent) {
// Update UI, new "message" processed by SimpleIntentService
final TextView t1 = (TextView) findViewById(R.id.yourpay);
t1.setTextColor(Color.parseColor("#008000"));
final TextView t2 = (TextView) findViewById(R.id.payper);
String end = intent.getStringExtra(SimpleIntentService.PARAM_OUT_END);
String result = intent.getStringExtra(SimpleIntentService.PARAM_OUT_RESULT);
t2.setText(result);
t1.setText(end);
}
}
#Override
public void onDestroy() {
this.unregisterReceiver(receiver);
super.onDestroy();
}
}
And Here is my intent service page, its set up so that swhen the intent starts it starts a timer that every 20ms should send the new intent back to the activity page, here is the code:
package com.famousmods.payme;
import java.util.Timer;
import java.util.TimerTask;
import com.famousmods.payme.PayTracker.ResponseReceiver;
import android.app.IntentService;
import android.content.Intent;
public class SimpleIntentService extends IntentService {
public static final String PARAM_OUT_END = "end";
public static final String PARAM_OUT_RESULT = "result";
public static final String PARAM_IN_HW = "hourly wage";
public static final String PARAM_IN_OTW = "overtime";
public static final String PARAM_IN_HPD = "hours per day";
public static String end;
public static String result;
private static double Reserve;
private static int Reserve1;
public static double money;
public static double counter;
private static int go;
private static int countdown;
public static int convert;
public SimpleIntentService() {
super("SimpleIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
// recieve from paytracker
double HW = intent.getDoubleExtra(PARAM_IN_HW, 1);
double OTW = intent.getDoubleExtra(PARAM_IN_OTW, 1);
double HPD = intent.getDoubleExtra(PARAM_IN_HPD, 1);
// Calculate pay per second
final double PPS = (HW/3600);
final double DPPS = (PPS/50);
final double OTPPS = (OTW/3600);
final double DOTPPS = (OTPPS/50);
final double HPDPS = (HPD*3600);
final double DHPDPS = (HPDPS*50);
Timer t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
new Runnable() {
public void run() {
if(DHPDPS==0){
money = (DPPS+Reserve);
Reserve = (money);
end = String.format("%1f", money);
//t1.setText("$" + end);
}else if(counter > DHPDPS && DOTPPS != 0 && DHPDPS != 0){
money = (DOTPPS+Reserve);
Reserve = (money);
end = String.format("%1f", money);
//t1.setText("$" + end);
} else{
money = (DPPS+Reserve);
Reserve = (money);
end = String.format("%1f", money);
//t1.setText("$" + end);
}
counter++;
//if(counter == 3000)
// t.cancel();
// Display pay per second
if(counter <= DHPDPS || DHPDPS == 0){
result = String.format("%.8f", PPS);
}else{
// t2.setText("Your pay per second is: $"+result2);
result = String.format("%.8f", OTPPS);
}
// Broadcast intent
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(ResponseReceiver.ACTION_RESP);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
broadcastIntent.putExtra(PARAM_OUT_END, end);
broadcastIntent.putExtra(PARAM_OUT_RESULT, result);
sendBroadcast(broadcastIntent);
}
};
}
}, 20, 20);
}
}
Thanks everybody!
Related
I have a medicine_activity class
package com.example.shubhmgajra.medikit;
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
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.Toast;
public class Medicine_Activity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "Medicine_Activity";
private Button btnAdd;
private ListView listMeds;
private AppDatabase db;
private ArrayAdapter<MedicineRecord> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medicine);
btnAdd = findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(this);
listMeds = findViewById(R.id.listMeds);
listMeds.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MedicineRecord medicineRecord = db.medicineRecordDao().findMedicineById(id + 1);
Intent intent = new Intent(getApplicationContext(), MedicineInputActivity.class);
startActivity(intent);
MedicineInputActivity.getInstance().update(medicineRecord, true);
}
});
db = AppDatabase.getInstance(getApplicationContext());
FeedAdapter feedAdapter = new FeedAdapter(Medicine_Activity.this, R.layout.list_record, db.medicineRecordDao().loadAllRecords());
listMeds.setAdapter(feedAdapter);
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onClick(View v) {
Intent intent = new Intent(this, MedicineInputActivity.class);
startActivity(intent);
}
}
In this i am trying to call update() method of another activity namely MedicineInputActivity
package com.example.shubhmgajra.medikit;
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
public class MedicineInputActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "MedicineInputActivity";
static EditText dosage;
static EditText medName;
static TimePicker timePicker;
static Button btnSave;
Button btnInc;
Button btnDec;
private AppDatabase db;
private static MedicineInputActivity instance;
boolean isEdit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medicine_input);
isEdit = false;
instance = this;
dosage = findViewById(R.id.dosage);
dosage.setShowSoftInputOnFocus(false);
dosage.setCursorVisible(false);
medName = findViewById(R.id.medName);
timePicker = findViewById(R.id.simpleTimePicker);
btnInc = findViewById(R.id.btnInc);
btnDec = findViewById(R.id.btnDec);
btnInc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = dosage.getText().toString();
int tempVal = Integer.parseInt(val);
tempVal++;
dosage.setText("" + tempVal);
}
});
btnDec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = dosage.getText().toString();
int tempVal = Integer.parseInt(val);
if (tempVal > 0) {
tempVal--;
}
dosage.setText("" + tempVal);
}
});
btnSave = findViewById(R.id.btnSave);
btnSave.setOnClickListener(this);
db = AppDatabase.getInstance(getApplicationContext());
}
#Override
public void onClick(View v) {
String name = medName.getText().toString();
int min = timePicker.getMinute();
int hour = timePicker.getHour();
String val = dosage.getText().toString();
int dose = Integer.parseInt(val);
MedicineRecord medicineRecord = new MedicineRecord(name, dose, min, hour);
if (validate(name)) {
if (isEdit) {
db.medicineRecordDao().updateRecord(medicineRecord);
} else {
db.medicineRecordDao().insertRecord(medicineRecord);
}
Intent intent = new Intent(this, Medicine_Activity.class);
startActivity(intent);
} else {
Toast toast = Toast.makeText(getApplicationContext(), "Medicine name cannot be empty", Toast.LENGTH_SHORT);
toast.show();
}
}
private boolean validate(String name) {
if (name.length() == 0) {
return false;
} else {
return true;
}
}
public static MedicineInputActivity getInstance() {
return instance;
}
public void update(MedicineRecord medicineRecord, boolean isEdit) {
this.isEdit = isEdit;
dosage.setText(medicineRecord.getDosage());
medName.setText(medicineRecord.getMedName());
timePicker.setHour(medicineRecord.getHour());
timePicker.setMinute(medicineRecord.getMinute());
}
}
What i am trying to achieve is when the user taps the list item, the input activity is loaded and the user can update the record. I wasnt able to find an elegant solution other than making an update method in MedicineInputActivity and then getting an instance of MedicineInputActivity in Medicine_Activity and calling update.
I am getting errors like "Attempt to invoke virtual method 'void com.example.shubhmgajra.medikit.MedicineInputActivity.update() on a null object reference".
You can return data from second activity to the first activity when user is done updating the record. You should start second activity by calling startActivityForResult() instead of startActivity() in the first activity. You should also override onActivityResult() in the first activity. You can read more here.
UPDATE:
I think you want to send selected medicine details from Medicine_Activity to MedicineInputActivity. In that case, you can send selected medicine object by binding it to the intent as follows:
public class Medicine_Activity ... {
#Override
protected void onCreate(Bundle savedInstanceState) {
...
listMeds.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MedicineRecord medicineRecord = db.medicineRecordDao().findMedicineById(id + 1);
Intent intent = new Intent(getApplicationContext(), MedicineInputActivity.class);
intent.putExtra("selectedMedicine", medicineRecord);
startActivity(intent);
MedicineInputActivity.getInstance().update(medicineRecord, true);
}
});
...
}
}
Then on MedicineInputActivity, you should be doing this:
public class MedicineInputActivity ... {
MedicineRecord selectedMedicineRecord;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
selectedMedicineRecord = (MedicineRecord) getIntent().getParcelableExtra("selectedMedicine");
...
}
}
To be able to do this, your MedicineRecord class should implement Parcelable interface.
I have a problem with an activity after minimalising. Everything is going ok when i start an activity and press start button. But when i minimalise activity and again maximalize it, it doesnt respond to my buttons and commands. Anybody know what to do? This is my first android app so i dont know what is going on..
here are my classes :
TrackerService
package sk.tuke.smart.makac.services;
import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
public class TrackerService extends Service implements LocationListener {
private Intent commandIntent;
private long duration;
private boolean paused,checkedAfterPause;
private int sportActivity;
private double distance,pace,calories;
private ArrayList<Location> finalPositionList = new ArrayList<Location>();
private LocationManager locationManager;
private static final String TAG = "TrackerService";
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.i(TAG,"onStart intent " +intent.getAction());
commandIntent=intent;
checkedAfterPause=true;
if(intent.getAction() == "sk.tuke.smart.makac.COMMAND_START"){
if(intent.getAction() == "sk.tuke.smart.makac.COMMAND_START") {
duration = 0;
}
new Timer().scheduleAtFixedRate(new TimerTask()
{
#Override
public void run() {
if(!paused){
duration++;
Intent intent1 = new Intent();
intent1.setAction("sk.tuke.smart.makac.TICK");
intent1.putExtra("duration", duration);
intent1.putExtra("distance",distance);
sendBroadcast(intent1);
Log.i(TAG,"" + duration);
}
}
}, 1000, 1000);
}else if (intent.getAction() == "sk.tuke.smart.makac.COMMAND_PAUSE"){
paused=true;
locationManager.removeUpdates(this);
}
if(intent.getAction() == "sk.tuke.smart.makac.COMMAND_CONTINUE"){
paused=false;
checkedAfterPause=false;
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,10,this);
}
}
#Override
public void onCreate() {
super.onCreate();
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,10,this);
}
#Override
public void onDestroy() {
locationManager.removeUpdates(this);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onLocationChanged(Location location) {
finalPositionList.add(location);
Location lastLocation;
double minDistance;
if (finalPositionList.size() != 1 && checkedAfterPause) {
lastLocation = finalPositionList.get(finalPositionList.size() - 2);
minDistance=location.distanceTo(lastLocation);
if(minDistance>=2){
distance += location.distanceTo(lastLocation);
}else{
finalPositionList.remove(finalPositionList.size()-1);
}
}
if(commandIntent.getAction() == "sk.tuke.smart.makac.COMMAND_CONTINUE" && !checkedAfterPause){
Log.i(TAG,"checking distance after pause");
lastLocation = finalPositionList.get(finalPositionList.size() - 2);
minDistance=location.distanceTo(lastLocation);
if(minDistance<=100){
distance += location.distanceTo(lastLocation);
}
checkedAfterPause=true;
}
Log.i(TAG,"locations " + finalPositionList);
Log.i(TAG,"distance = " + distance);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
public long getDuration(){
return duration;
}
public double getPace(){
return pace;
}
}
SportsActivity
package sk.tuke.smart.makac;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import sk.tuke.smart.makac.helpers.MainHelper;
import sk.tuke.smart.makac.services.TrackerService;
public class StopwatchActivity extends AppCompatActivity {
private static final int MY_PERMISSIONS_REQUEST_FINE_LOCATION = 111;
private static final String TAG = "StopwatchActivity";
private boolean started;
private boolean running;
private boolean paused=false;
private long duration;
private double distance;
private MainHelper helper;
private TextView durationView,distanceView;
private Button startButton,endButton;
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction()=="sk.tuke.smart.makac.TICK"){
duration = intent.getLongExtra("duration",duration);
distance = intent.getDoubleExtra("distance",distance);
durationView.setText(helper.formatDuration(duration));
distanceView.setText(helper.formatDistance(distance));
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stopwatch);
IntentFilter intentFilter = new IntentFilter("sk.tuke.smart.makac.TICK");
registerReceiver(receiver,intentFilter);
started=false;
running=false;
helper = new MainHelper();
durationView = findViewById(R.id.textview_stopwatch_duration);
distanceView = findViewById(R.id.textview_stopwatch_distance);
startButton = findViewById(R.id.button_stopwatch_start);
endButton = findViewById(R.id.button_stopwatch_endworkout);
if(!canAccessLocation()){
ActivityCompat.requestPermissions(this,
new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_FINE_LOCATION);
}
}
public void toggle(View view){
Intent intent = new Intent(this,TrackerService.class);
started=true;
this.running = !this.running;
if(running && started){
startButton.setText("Stop");
endButton.setVisibility(view.GONE);
if(paused){
intent.setAction("sk.tuke.smart.makac.COMMAND_CONTINUE");
paused=false;
}else
intent.setAction("sk.tuke.smart.makac.COMMAND_START");
}
if(!running && started){
startButton.setText("Continue");
endButton.setVisibility(view.VISIBLE);
intent.setAction("sk.tuke.smart.makac.COMMAND_PAUSE");
paused=true;
}
startService(intent);
}
public void endWorkout(View view){
Intent intent = new Intent(this,TrackerService.class);
intent.setAction("sk.tuke.smart.makac.COMMAND_STOP");
startService(intent);
setContentView(R.layout.activity_workout_detail);
onStop();
}
public void openMaps(View view){
Intent intent = new Intent(StopwatchActivity.this, MapsActivity.class);
startActivity(intent);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
Intent intent= new Intent(this,TrackerService.class);
stopService(intent);
}
private boolean hasPermission(String perm) {
return(PackageManager.PERMISSION_GRANTED==checkSelfPermission(perm));
}
private boolean canAccessLocation() {
return(hasPermission(Manifest.permission.ACCESS_FINE_LOCATION));
}
}
You aren't creating a connection to the service. You're only starting it, not binding it. So there's no connection to maintain.
It looks like you're trying to do quasi-binding via actions. Don't do that, properly bind the service and avoid a whole raft of problems like this.
**MainActivity.java**
package com.cetpainfotech.newandroid;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SmsMessage;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity {
private final int CHECK_CODE = 0x1;
private final int LONG_DURATION = 5000;
private final int SHORT_DURATION = 1200;
private Speaker speaker;
private ToggleButton toggle;
private OnCheckedChangeListener toggleListener;
private TextView smsText;
private TextView smsSender;
private BroadcastReceiver smsReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toggle = (ToggleButton)findViewById(R.id.speechToggle);
smsText = (TextView)findViewById(R.id.sms_text);
smsSender = (TextView)findViewById(R.id.sms_sender);
toggleListener = new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton view, boolean isChecked) {
if(isChecked){
speaker.allow(true);
speaker.speak(getString(R.string.start_speaking));
}else{
speaker.speak(getString(R.string.stop_speaking));
speaker.allow(false);
}
}
};
toggle.setOnCheckedChangeListener(toggleListener);
checkTTS();
initializeSMSReceiver();
registerSMSReceiver();
}
private void checkTTS(){
Intent check = new Intent();
check.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(check, CHECK_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == CHECK_CODE){
if(resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS){
speaker = new Speaker(this);
}else {
Intent install = new Intent();
install.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(install);
}
}
}
private void initializeSMSReceiver(){
smsReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if(bundle!=null){
Object[] pdus = (Object[])bundle.get("pdus");
for(int i=0;i<pdus.length;i++){
byte[] pdu = (byte[])pdus[i];
SmsMessage message = SmsMessage.createFromPdu(pdu);
String text = message.getDisplayMessageBody();
String sender = getContactName(message.getOriginatingAddress());
speaker.pause(LONG_DURATION);
speaker.speak("You have a new message from" + sender + "!");
speaker.pause(SHORT_DURATION);
speaker.speak(text);
smsSender.setText("Message from " + sender);
smsText.setText(text);
}
}
}
};
}
private void registerSMSReceiver() {
IntentFilter intentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(smsReceiver, intentFilter);
}
private String getContactName(String phone){
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
String projection[] = new String[]{ContactsContract.Data.DISPLAY_NAME};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if(cursor.moveToFirst()){
return cursor.getString(0);
}else {
return "unknown number";
}
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(smsReceiver);
speaker.destroy();
}
}
**Speaker.java** //Helper class
This class is used to avoid calling the TTS API directly from the Activity.
This class implements the OnInitListener interface so that it knows when the TTS engine is ready.
package com.cetpainfotech.newandroid;
import android.content.Context;
import android.media.AudioManager;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import java.util.HashMap;
import java.util.Locale;
public class Speaker implements OnInitListener {
private TextToSpeech tts;
private boolean ready = false;
private boolean allowed = false;
public Speaker(Context context){
tts = new TextToSpeech(context, this);
}
public boolean isAllowed(){
return allowed;
}
public void allow(boolean allowed){
this.allowed = allowed;
}
#Override
public void onInit(int status) {
if(status == TextToSpeech.SUCCESS){
// Change this to match your
// locale
tts.setLanguage(Locale.US);
ready = true;
}else{
ready = false;
}
}
public void speak(String text){
// Speak only if the TTS is ready
// and the user has allowed speech
if(ready && allowed) {
HashMap<String, String> hash = new HashMap<>();
hash.put(TextToSpeech.Engine.KEY_PARAM_STREAM,
String.valueOf(AudioManager.STREAM_NOTIFICATION));
tts.speak(text, TextToSpeech.QUEUE_ADD, hash);
}
}
public void pause(int duration){
tts.playSilence(duration, TextToSpeech.QUEUE_ADD, null);
}
// Free up resources
public void destroy(){
tts.shutdown();
}
}
i download this example from the net and i want modify to sent a Obj student from a service to activity already run.
This is the code, the communication from service to activity it's work fine, but the object arrived empty.
Main Activity:
package com.websmithing.broadcasttest;
import com.websmithing.broadcasttest.Student;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class BroadcastTest extends Activity {
private static final String TAG = "BroadcastTest";
private Intent intent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
intent = new Intent(this, BroadcastService.class);
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateUI(intent);
}
};
#Override
public void onResume() {
super.onResume();
startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter(
BroadcastService.BROADCAST_ACTION));
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
stopService(intent);
}
private void updateUI(Intent intent) {
// String counter = intent.getStringExtra("studente");
Student student = (Student) getIntent().getParcelableExtra("student");
Log.d(TAG, "Ricevuto");
if (student != null) {
TextView txtCounter = (TextView) findViewById(R.id.txtCounter);
txtCounter.setText(student.mSAge);
} else {
Log.d(TAG, "Sudente Vuoto");
}
}
}
The Service:
package com.websmithing.broadcasttest;
import com.websmithing.broadcasttest.Student;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
public class BroadcastService extends Service {
private static final String TAG = "BroadcastService";
public static final String BROADCAST_ACTION = "com.websmithing.broadcasttest.displayevent";
private final Handler handler = new Handler();
Intent intent;
int counter = 0;
public Student student = new Student("Mario", 20, "Calatafimi", "Informatica");
#Override
public void onCreate() {
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
}
#Override
public void onStart(Intent intent, int startId) {
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 1000); // 1 second
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
DisplayLoggingInfo();
handler.postDelayed(this, 5000); // 10 seconds
}
};
private void DisplayLoggingInfo() {
Log.d(TAG, "entered DisplayLoggingInfo");
intent.putExtra("studente", student);
sendBroadcast(intent);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
handler.removeCallbacks(sendUpdatesToUI);
super.onDestroy();
}
}
The class Student:
package com.websmithing.broadcasttest;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
public class Student implements Parcelable{
String mSName;
int mSAge;
String mSAddress;
String mSCourse;
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
/*
* Storing the Student data to Parcel object
*/
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mSName);
dest.writeInt(mSAge);
dest.writeString(mSAddress);
dest.writeString(mSCourse);
}
/*
* A constructor that initializes the Student object
*/
public Student(String sName, int sAge, String sAddress, String sCourse){
this.mSName = sName;
this.mSAge = sAge;
this.mSAddress = sAddress;
this.mSCourse = sCourse;
}
/*
* Retrieving Student data from Parcel object
* This constructor is invoked by the method createFromParcel(Parcel source) of
* the object CREATOR
*/
private Student(Parcel in){
this.mSName = in.readString();
this.mSAge = in.readInt();
this.mSAddress = in.readString();
this.mSCourse = in.readString();
}
public static final Parcelable.Creator<Student> CREATOR = new Parcelable.Creator<Student>() {
#Override
public Student createFromParcel(Parcel source) {
return new Student(source);
}
#Override
public Student[] newArray(int size) {
return new Student[size];
}
};
}
Many thanks!!!
May be the problem is you send from Service:
intent.putExtra("studente", student);
and want to receive in Activity:
Student student = (Student) getIntent().getParcelableExtra("student");
student - studentE
Make keys the same and try again, please
Hope it helps
UPD: The problem is in your Activity updateUI method:
private void updateUI(Intent intent) {
// String counter = intent.getStringExtra("studente");
Student student = (Student) getIntent().getParcelableExtra("student");
Log.d(TAG, "Ricevuto");
if (student != null) {
TextView txtCounter = (TextView) findViewById(R.id.txtCounter);
txtCounter.setText(student.mSAge);
} else {
Log.d(TAG, "Sudente Vuoto");
}
}
You use getIntent() but you should use intent provided in method params updateUI(Intent intent).
So, please, change this line:
Student student = getIntent().getParcelableExtra("student");
to
Student student = intent.getParcelableExtra("student");
and try again
I am trying to update my existing Android Application to work on both mobile phone and Tablet. So I want to change the Activity class to fragment. The below is my activity class.
Individual Activity class
package FXPAL.Unity.Android;
import FXPAL.Unity.Android.Person.CalendarEntry;
import FXPAL.Unity.Android.Person.IM;
import FXPAL.Unity.Android.Person.Person;
import FXPAL.Unity.Android.Person.Status;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
public class IndividualViewActivity extends Activity {
private static final String DB_TAG = "IndividualView";
//private static final String DB_TAG_PING = "ShowPingView";
private TextView displayName, presence, phoneNum, cellNum, emailAddr, btLocation, calInfo, status;
private ImageView userImage;
private Person personToDisplay;
private String phoneNumber, cellNumber, username, emailAddress;
private TableRow fxpalIMrow, skypeIMrow, msLiveIMrow, gtalkIMrow;
private TableLayout imTable;
private TextView fxpalIMstatus, skypeIMstatus, msLiveIMstatus, gtalkIMstatus, pingText;
private Button nudgeButton, pingButton, clearPingButton, calendarButton;
private LinearLayout pingLayout, pingNudgeButtonLayout;
protected String numToCall, numtype;
private DatabaseHelper db;
//private int pingID = -1;
private UnityMobileApp appCtx;
private static final int DIALOG_CALL_OFFICE_ID = 0;
private static final int DIALOG_CALL_CELL_ID = 1;
protected static final int DIALOG_VIEW_CALENDAR = 2;
private static final int REFRESH_MENU_ID = 0;
protected static final String OFFICE = "office";
private static final String CELL = "cell";
protected static final int MESSAGE_CONNECTION_ERROR_TOAST = 0;
//private static final String DEBUG_TAG = "unity.IndividualViewActivity";
private final Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_CONNECTION_ERROR_TOAST:
Toast.makeText(IndividualViewActivity.this, Consts.CONNECTION_ERROR_MESSAGE, Toast.LENGTH_SHORT).show();
break;
}
}
};
private SharedPreferences prefs;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//doBindService();
setContentView(R.layout.individual_view);
db = new DatabaseHelper(this);
appCtx = (UnityMobileApp) getApplication();
prefs = PreferenceManager.getDefaultSharedPreferences(this);
//Setup View
displayName = (TextView)findViewById(R.id.individualName);
presence = (TextView)findViewById(R.id.individualPresence);
userImage = (ImageView)findViewById(R.id.individualUserImage);
phoneNum = (TextView)findViewById(R.id.individualPhone);
cellNum = (TextView)findViewById(R.id.individualCellPhone);
emailAddr = (TextView)findViewById(R.id.individualEmail);
btLocation = (TextView)findViewById(R.id.individualLocation);
calInfo = (TextView)findViewById(R.id.individualCalendarInfo);
status = (TextView)findViewById(R.id.individualStatus);
fxpalIMrow = (TableRow)findViewById(R.id.im_fxpal);
skypeIMrow = (TableRow)findViewById(R.id.im_skype);
msLiveIMrow = (TableRow)findViewById(R.id.im_ms_live);
gtalkIMrow = (TableRow)findViewById(R.id.im_gtalk);
fxpalIMstatus = (TextView)findViewById(R.id.im_status_fxpal);
skypeIMstatus = (TextView)findViewById(R.id.im_status_skype);
msLiveIMstatus = (TextView)findViewById(R.id.im_status_ms_live);
gtalkIMstatus = (TextView)findViewById(R.id.im_status_gtalk);
imTable = (TableLayout)findViewById(R.id.individualIMStatus);
nudgeButton = (Button)findViewById(R.id.individual_nudge_button);
pingButton = (Button) findViewById(R.id.individual_ping_button);
calendarButton = (Button)findViewById(R.id.individualViewCalendarButton);
pingText = (TextView)findViewById(R.id.individualPingText);;
clearPingButton = (Button) findViewById(R.id.individualClearPingButton);
pingLayout = (LinearLayout)findViewById(R.id.individualPingInfo);
pingNudgeButtonLayout = (LinearLayout)findViewById(R.id.individual_nudge_ping_layout);
calendarButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(DIALOG_VIEW_CALENDAR);
db.viewEvent(DB_TAG + ":CalendarDialog", username);
}
});
nudgeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(IndividualViewActivity.this, SendNudgeActivity.class)
.putExtra(Consts.EXTRA_USERNAME, personToDisplay.getUsername())
.putExtra(Consts.EXTRA_DISPLAY_NAME, personToDisplay.getDisplayName()));
}
});
pingButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(IndividualViewActivity.this, SendPingActivity.class)
.putExtra(Consts.EXTRA_USERNAME, personToDisplay.getUsername())
.putExtra(Consts.EXTRA_DISPLAY_NAME, personToDisplay.getDisplayName()));
}
});
}
public void onPause(){
super.onPause();
}
public void onDestroy(){
super.onDestroy();
//doUnbindService();
db.close();
}
public void onResume(){
super.onResume();
Intent mIntent = getIntent();
username = mIntent.getStringExtra(Consts.EXTRA_USERNAME);
if(username.equalsIgnoreCase(prefs.getString(Consts.PREF_USERNAME, "")))
pingNudgeButtonLayout.setVisibility(View.GONE);
else
pingNudgeButtonLayout.setVisibility(View.VISIBLE);
personToDisplay = appCtx.getEveryone().get(username);
updateView();
updateInfo();
if (personToDisplay == null || personToDisplay.getCalendar() == null ||
personToDisplay.getCalendar().getCalendar().size() == 0)
calendarButton.setEnabled(false);
else
calendarButton.setEnabled(true);
db.viewEvent(DB_TAG, username);
pingLayout.setVisibility(View.GONE);
//}
}
private void updateInfo(){
ServerHelper.RequestListener listener = new ServerHelper.RequestListener() {
public void onCompleted(ServerHelper.Request request) {
if (request.isUnauthorized())
startActivity(new Intent(IndividualViewActivity.this, LoginActivity.class));
else if (request.isSuccess()) {
Person.PersonHelper.getEveryoneAsync(IndividualViewActivity.this, appCtx.everyone, null, request.getResponseString(),
new Runnable() {
public void run () {
personToDisplay = appCtx.everyone.get(username);
updateView();
}
});
}
}
};
ServerHelper.appCtx = appCtx;
ServerHelper.getStatus (prefs, listener);
}
private void updateView(){
if (personToDisplay == null)
return;
displayName.setText(personToDisplay.getDisplayName());
presence.setText(personToDisplay.getPresenceState());
Status mStatus = personToDisplay.getStatus();
if( mStatus!= null && mStatus.toString().length()>0){
status.setVisibility(View.VISIBLE);
status.setText(mStatus.toString());
}
userImage.setImageBitmap(personToDisplay.getRoundedImage(Consts.LARGE_USER_IMAGE_SIZE, Consts.LARGE_USER_IMAGE_BORDER));
phoneNumber = personToDisplay.getPhoneNum();
if(phoneNumber.length()>0){
phoneNum.setText(OFFICE + ": " + phoneNumber);
phoneNum.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
numToCall = phoneNumber;
numtype = OFFICE;
showDialog(DIALOG_CALL_OFFICE_ID);
}
});}
else
phoneNum.setVisibility(View.GONE);
cellNumber = personToDisplay.getCellPhoneNum();
if(cellNumber.length()>0){
cellNum.setText(CELL + ": " + cellNumber);
cellNum.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
numToCall = cellNumber;
numtype = CELL;
showDialog(DIALOG_CALL_CELL_ID);
}
});}
else
cellNum.setVisibility(View.GONE);
emailAddress = personToDisplay.getEmailAddress();
emailAddr.setText(emailAddress);
emailAddr.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
db.communicate(DB_TAG, "email", username);
Intent emailIntent = new Intent();
emailIntent.setAction(android.content.Intent.ACTION_SENDTO);
emailIntent.setData(Uri.parse("mailto:" + emailAddress));
startActivity(Intent.createChooser(emailIntent, "Select Email Client"));
}
});
if(personToDisplay.hasLocation()){
btLocation.setVisibility(View.VISIBLE);
btLocation.setText(personToDisplay.getLocation().toString());
}
CalendarEntry usefulCalInfo = personToDisplay.getCalendar().getMostUseful();
if(usefulCalInfo != null){
calInfo.setVisibility(View.VISIBLE);
calInfo.setText("Calendar: " + usefulCalInfo.toString());
}
if(personToDisplay.hasIM()){
imTable.setVisibility(View.VISIBLE);
}
for(IM mIM : personToDisplay.getIMList().values()){
switch(mIM.getId()){
case(IM.FXPAL_ID):
fxpalIMrow.setVisibility(View.VISIBLE);
fxpalIMstatus.setText(mIM.getStatus());
break;
case(IM.SKYPE_ID):
skypeIMrow.setVisibility(View.VISIBLE);
skypeIMstatus.setText(mIM.getStatus());
break;
case(IM.MS_LIVE_ID):
msLiveIMrow.setVisibility(View.VISIBLE);
msLiveIMstatus.setText(mIM.getStatus());
break;
case(IM.GTALK_ID):
gtalkIMrow.setVisibility(View.VISIBLE);
gtalkIMstatus.setText(mIM.getStatus());
break;
default:
}
}
}
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
switch(id) {
case DIALOG_CALL_OFFICE_ID:
case DIALOG_CALL_CELL_ID:
dialog = CommDialog.getCallDialog(displayName.getText().toString(), numToCall, numtype, IndividualViewActivity.this, db);
break;
case DIALOG_VIEW_CALENDAR:
return CalendarListDialog.getDialog(username, IndividualViewActivity.this, appCtx);
default:
dialog = null;
}
return dialog;
}
public boolean onCreateOptionsMenu(Menu menu){
menu.add(Menu.NONE, REFRESH_MENU_ID, Menu.NONE, "Refresh")
.setIcon(R.drawable.ic_menu_refresh)
.setAlphabeticShortcut('r');
return(super.onCreateOptionsMenu(menu));
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case REFRESH_MENU_ID:
refresh();
break;
}
return (super.onOptionsItemSelected(item));
}
void refresh() {
// update the location and report it to the server
ReportingService.startLocationRequest(appCtx, true);
// this may still retrieve the old location
updateInfo();
}
}
Please help me guys. I am stuck with this problem since long time.
Regards,
Rakesh