Using sharedpref strings as inputs into sendTextMessage - android

I am creating an app that takes String's input by the user via EditText, puts them into a sharedpreference and then sends an automatic sms when an sms is received, using the strings from the sharedpreference to dictate the phone number and text message that will be automatically sent.
The app works perfectly as long as I hardcode the phone number and the text message to be sent. As soon as I try and put the Strings from the shared preferences into the SendSMS method then the app crashes and I get a debug error "hasUserDataHeader : false"
The below code is the version where i try to take the String from the Name EditText and use it as the message to be sent via the parameter TextMessage (see within the broadcast receiver for this line of code). If i were to replace this with "TextMessage" then it would be fine but obviously this doesn't make the text sent dynamic
Code below:
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Button;
import android.app.PendingIntent;
import android.content.Intent;
import android.telephony.SmsManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.widget.TextView;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.SharedPreferences;
public class MainActivity extends Activity {
int notificationID = 1;
String[] excuses;
String excuseSelected;
IntentFilter intentFilter;
private SharedPreferences prefs;
private String prefName = "MyPref";
private static final String NUMBER_KEY = "number";
private static final String NAME_KEY = "name";
private static final String EXCUSE_KEY = "excuse";
private BroadcastReceiver intentReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//---gather up all the necessary user input---
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
String textMessage = (String) prefs.getString(NAME_KEY, "");
sendSMS("0403579838", textMessage);
// }
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//---intent to filter for SMS messages received---
intentFilter = new IntentFilter();
intentFilter.addAction("SMS_RECEIVED_ACTION");
final Button btn1 = (Button)findViewById(R.id.buttonToggle);
excuses = getResources().getStringArray(R.array.excuses_array);
Spinner s1 = (Spinner) findViewById(R.id.spinnerExcuse);
final EditText EditTextNumber = (EditText) findViewById(R.id.editTextNumber);
final EditText EditTextName = (EditText) findViewById(R.id.editTextName);
//---Sorting the spinner view out for excuses selection---
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, excuses);
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3)
{
int index = arg0.getSelectedItemPosition();
excuseSelected = excuses[index];
}
public void onNothingSelected(AdapterView<?> arg0) {}
});
//---Setting the button to toggle between on and off---
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (btn1.getText().equals("Turn on"))
{
btn1.setText("Turn off");
//---register the receiver---
registerReceiver(intentReceiver, intentFilter);
//---get the SharedPreferences object---
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
//---set the user inputs to prefo's---
editor.putString(NUMBER_KEY, EditTextNumber.getText().toString());
editor.putString(NAME_KEY, EditTextName.getText().toString());
editor.putString(EXCUSE_KEY, excuseSelected);
}
else
{
btn1.setText("Turn on");
//---unregister the receiver---
unregisterReceiver(intentReceiver);
}
}
});
}
//---sends an SMS message to another device---
public void sendSMS(String phoneNumber, String message)
{
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
displayNotification();
}
protected void displayNotification()
{
Intent i = new Intent(this, NotificationView.class);
i.putExtra("notificationID", notificationID);
PendingIntent pendingIntent =
PendingIntent.getActivity(this, 0, i, 0);
NotificationManager nm = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
Notification notif = new Notification(
R.drawable.ic_launcher,
"SMS has been sent by GirlfriendMinder",
System.currentTimeMillis());
CharSequence from = "GirlfriendMinder";
CharSequence message = "SMS has been sent by GirlfriendMinder";
notif.setLatestEventInfo(this, from, message, pendingIntent);
//---100ms delay, vibrate for 250ms, pause for 100ms, and then vibrate for 500ms---
notif.vibrate = new long[] { 100, 250, 100, 500};
nm.notify(notificationID, notif);
}
#Override
protected void onDestroy() {
//---unregister the receiver---
unregisterReceiver(intentReceiver);
super.onPause();
}
}

In your code:
//---Setting the button to toggle between on and off---
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (btn1.getText().equals("Turn on"))
{
btn1.setText("Turn off");
//---register the receiver---
registerReceiver(intentReceiver, intentFilter);
//---get the SharedPreferences object---
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
//---set the user inputs to prefo's---
editor.putString(NUMBER_KEY, EditTextNumber.getText().toString());
editor.putString(NAME_KEY, EditTextName.getText().toString());
editor.putString(EXCUSE_KEY, excuseSelected);
}
else
{
btn1.setText("Turn on");
//---unregister the receiver---
unregisterReceiver(intentReceiver);
}
}
});
}
below:
editor.putString(EXCUSE_KEY, excuseSelected);
add
editor.commit();

Related

Creating a sms reader app to read the incoming messages via text to speech and run in background but it does meet the requirements

**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();
}
}

Access SharedPreferences from another class (non-activity)

I'm trying to pass the values from the MainActivity class into SMSReceiver class using SharedPreferences but the values that returned isn't true
i used this and this but it seems it doesn't work
Edit : i'm using a service in my program so i can't call the members like MainActivity.MyPREFENRECES, SMSreceiver.rK because after i kill the activity i get null exception
Edit I'm calling the method run in the layout
any help please ??
MainActivity.java
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.media.AudioManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.Toast;
public class MainActivity extends Activity {
public static final String MyPREFERENCES = "MyPrefs" ;
public static Switch smsSwitch;
private EditText ringKey,vibrateKey,silentKey;
private AudioManager myAudioManager;
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
smsSwitch = (Switch)findViewById(R.id.smsSwitch);
ringKey = (EditText)findViewById(R.id.ringWord);
vibrateKey = (EditText)findViewById(R.id.vibrateWord);
silentKey = (EditText)findViewById(R.id.silentWord);
myAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
smsSwitch.setChecked(true);
if (sharedpreferences.contains(SMSreceiver.rK))
{
ringKey.setText(sharedpreferences.getString(SMSreceiver.rK, ""));
}
if (sharedpreferences.contains(SMSreceiver.sK))
{
silentKey.setText(sharedpreferences.getString(SMSreceiver.sK, ""));
}
if (sharedpreferences.contains(SMSreceiver.vK))
{
vibrateKey.setText(sharedpreferences.getString(SMSreceiver.vK, ""));
}
smsSwitch.setChecked(sharedpreferences.getBoolean("checked",false));
}
public void vibrate(View view){
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
}
public void ring(View view){
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}
public void silent(View view){
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
}
public void mode(View view){
int mod = myAudioManager.getRingerMode();
if(mod == AudioManager.RINGER_MODE_NORMAL){
Toast.makeText(getApplicationContext(), "Normal Mode", Toast.LENGTH_SHORT).show();
}
else if(mod == AudioManager.RINGER_MODE_SILENT){
Toast.makeText(getApplicationContext(), "Silent Mode", Toast.LENGTH_SHORT).show();
}
else if(mod == AudioManager.RINGER_MODE_VIBRATE){
Toast.makeText(getApplicationContext(), "Vibrate Mode", Toast.LENGTH_SHORT).show();
}
else{
}
}
public void run(View view){
String r = ringKey.getText().toString();
String v = vibrateKey.getText().toString();
String s = silentKey.getText().toString();
boolean c = smsSwitch.isChecked();
Editor editor = sharedpreferences.edit();
editor.putString("ring", r);
editor.putString("vibrate", v);
editor.putString("silent", s);
editor.putBoolean("checked",c);
editor.commit();
}
}
SMSreceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
public class SMSreceiver extends BroadcastReceiver
{
private final String TAG = this.getClass().getSimpleName();
public static final String SMS_BUNDLE = "pdus";
public static SharedPreferences sharedpreference;
public static String rK="ring";
public static String vK="vibrate";
public static String sK="silent";
#Override
public void onReceive(Context context, Intent intent)
{
Intent startServiceIntent = new Intent(context, MainActivity.class);
context.startService(startServiceIntent);
sharedpreference = context.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
Bundle intentExtras = intent.getExtras();
if (intentExtras != null) {
Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
for (int i = 0; i < sms.length; ++i) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);
String smsBody = smsMessage.getMessageBody().toString();
AudioManager am = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
if(sharedpreference.getBoolean("checked",true)) {
if (smsBody.contains(sharedpreference.getString(rK,"ring"))) {
am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Toast.makeText(context, "Normal Mode Activated", Toast.LENGTH_SHORT).show();
} else if (smsBody.contains(sharedpreference.getString(vK,"vibrate"))) {
am.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
Toast.makeText(context, "Vibrate Mode Activated", Toast.LENGTH_SHORT).show();
} else if (smsBody.contains(sharedpreference.getString(sK,"silent"))) {
am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
Toast.makeText(context, "Silent Mode Activated", Toast.LENGTH_SHORT).show();
}
}
}
}
}
}

Using shared preferences in Activity recognition app

I want to save the details of activities of user even if he closed the app by pressing back button or changed the orientation.I used shared prefences but i don't know how it works.i saw in different programmings using sharepreferences to save data.But i can't do it.Is there any changes i have to do.
Here is my code:
package tmt.niranjan.travellingtrack;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
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.ActivityRecognitionClient;
public class MainActivity extends Activity implements GooglePlayServicesClient.ConnectionCallbacks,GooglePlayServicesClient.OnConnectionFailedListener {
private ActivityRecognitionClient arclient;
private PendingIntent pIntent;
private BroadcastReceiver receiver;
private TextView tvActivity;
public static final String SHARED_PREFERENCES =
"tmt.niranjan.travellingtrack.SHARED_PREFERENCES";
public static final String KEY_LOG_FILE_NUMBER =
"tmt.niranjan.travellingtrack.KEY_LOG_FILE_NUMBER";
public static final String KEY_LOG_FILE_NAME =
"tmt.niranjan.travellingtrack.KEY_LOG_FILE_NAME";
public static final String KEY_LOG_FILE_NAME1 =
"tmt.niranjan.travellingtrack.KEY_LOG_FILE_NAME";
public static final String KEY_PREVIOUS_ACTIVITY_TYPE =
"tmt.niranjan.travellingtrack.KEY_PREVIOUS_ACTIVITY_TYPE";
private SharedPreferences mpref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvActivity = (TextView) findViewById(R.id.Actrec);
mpref = getApplicationContext().getSharedPreferences(
SHARED_PREFERENCES, Context.MODE_PRIVATE);
int resp =GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if(resp == ConnectionResult.SUCCESS){
arclient = new ActivityRecognitionClient(this, this, this);
arclient.connect();
}
else{
Toast.makeText(this, "Please install Google Play Service.", Toast.LENGTH_SHORT).show();
}
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Editor editor = mpref.edit();
String v = "Type:"+intent.getExtras().getInt("Type")+" "+"Activity :" + intent.getStringExtra("Activity") + " " + "Confidence : " + intent.getExtras().getInt("Confidence") + "\n";
editor.putInt(KEY_PREVIOUS_ACTIVITY_TYPE,intent.getExtras().getInt("Type"));
editor.putString(KEY_LOG_FILE_NAME, "Activity");
editor.putInt(KEY_LOG_FILE_NUMBER, intent.getExtras().getInt("Confidence"));
editor.putString(KEY_LOG_FILE_NAME1,v);
tvActivity.setText(v);
editor.commit();
}
};
IntentFilter filter = new IntentFilter();
filter.addAction("tmt.niranjan.myactivityrecognition.ACTIVITY_RECOGNITION_DATA");
registerReceiver(receiver, filter);
}
#Override
protected void onDestroy() {
super.onDestroy();
if(arclient!=null){
arclient.removeActivityUpdates(pIntent);
arclient.disconnect();
}
Toast.makeText(this, "ondestroycalled", Toast.LENGTH_SHORT).show();
unregisterReceiver(receiver);
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
Toast.makeText(this, "Connection Failed", Toast.LENGTH_SHORT).show();
}
#Override
public void onConnected(Bundle arg0) {
Intent intent = new Intent(this, ActivityRecognitionService.class);
pIntent = PendingIntent.getService(this, 0, intent,PendingIntent.FLAG_UPDATE_CURRENT);
arclient.requestActivityUpdates(1000, pIntent);
}
#Override
public void onDisconnected() {
}
}
You are missing editor.apply(); before editor.commit();
Give it a go and see if it works
Here is code that I use and works fine, so if it is not editor.apply then it would suggest that nothing is being set from your intents.getextra, have you debugged to see if these contain a value?
SharedPreferences.Editor editor = prefs.edit();
editor.putString("key_pref_branch_code", mainObject.getString("Code"));
editor.putString("key_pref_branch_id", mainObject.getString("ID"));
editor.putString("key_pref_branch_name", mainObject.getString("Name"));
editor.putString("key_pref_json_url", "http://xxxxx:8080/storehandler.ashx");
editor.apply();
editor.commit();

Activity that can update a Service via Button

I am trying to update a service from an activity. The Activity saves data to the sql lite database on the phone when the user clicks on a button. What I would like to do here, is when this button is clicked, the service is refreshed and uses the new data.
I was using start/stopservice on the button, but the app crashes and skips around to different activities.
I thought my question was similar to Android: Update / Refresh a running service and
Broadcast Receiver within a Service
However, I'm not updating a widget or another android native component. The service is a custom class.
Please note that a Broadcast receiver starts this service on Boot of the phone.
Also, Logcat window dosen't scroll the readouts. It jerks up and down. So I don't have an error log to show you.
How do I create a function that would allow the service to update when the user clicks on the button in an activity?
Here is my activity (button is at the bottom):
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import org.joda.time.DateTime;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.google.android.gcm.demo.app.R;
import com.google.android.gcm.demo.app.EventList.DataView;
import com.google.android.gcm.demo.app.EventList.EventDetails;
import com.google.android.gcm.demo.app.sqllite.DatabaseSqlite;
public class AlertDetails extends Activity {
Integer id;
String name;
String date;
String startTime;
String endTime;
String location;
int alertState;
Bundle bundle;
String alertTime;
String s;
private TextView mTitleDisplay;
private TextView mDateDisplay;
private TextView mTimeDisplay;
private TextView mTimeEndDisplay;
private TextView mLocationDisplay;
private TextView mAlertDisplay;
private String update_alarmTime;
String eventYear;
String eventDay;
String eventMonth;
String eventdate;
Context context;
Intent alarmServiceControl;
DatabaseSqlite entry = new DatabaseSqlite(AlertDetails.this);
// Intent startServiceIntent = new Intent(context, AlarmsService.class);
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alertview);
bundle = getIntent().getExtras();
id = bundle.getInt("id");
name = bundle.getString("eventName");
date = bundle.getString("date");
startTime = bundle.getString("startTime");
endTime = bundle.getString("endTime");
location = bundle.getString("location");
alertState = bundle.getInt("alertState");
alertTime = bundle.getString("alertTime");
alertTime = "10:00:00";// need to be hooked up correctly to get the right
// capture our View elements
mTitleDisplay = (TextView) findViewById(R.id.titleDisplay);
mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
mTimeDisplay = (TextView) findViewById(R.id.timeDisplay);
mTimeEndDisplay = (TextView) findViewById(R.id.timeEndDisplay);
mLocationDisplay = (TextView) findViewById(R.id.locationDisplay);
mAlertDisplay = (TextView) findViewById(R.id.alertDisplay);
// set start
mTimeDisplay.setText(startTime);
mTimeEndDisplay.setText(endTime);
// set title
mTitleDisplay.setText(name);
// set Date
eventYear = date.substring(0, 4);
eventDay = date.substring(5, 7);
eventMonth = date.substring(8, 10);
mDateDisplay.setText(eventDay + "-" + eventMonth + "-" + eventYear);
eventdate = eventDay + "/" + eventMonth + "/" + eventYear;
// set location
mLocationDisplay.setText(location);
if (alertState == 0) {
entry.open();
mAlertDisplay.setText("Alert is ON and Set to " +entry.getAlert(id));
entry.close();
}
if (alertState == 1) {
mAlertDisplay.setText("Alert is OFF");
}
Button button1 = (Button) findViewById(R.id.btnSetAlert);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (alertState == 0) {
alertState++;
mAlertDisplay.setText("Alert is OFF");
entry.open();
entry.updateAlertState(id, alertState);
entry.close();
} else {
//turn alarm on
entry.open();
mAlertDisplay.setText("Alert is ON and Set to " +entry.getAlert(id));
alertState = 0;
entry.updateAlertState(id, alertState);
entry.close();
}
// TODO check if service is running
stopService(new Intent(AlertDetails.this,
AlarmsService.class));
startService(new Intent(AlertDetails.this,
AlarmsService.class));
Intent intent = new Intent(AlertDetails.this,
AlertView.class);
startActivity(intent);
}
});
}
}
Here is the service I'd like to update:
package com.google.android.gcm.demo.app.Alerts;
import java.util.Calendar;
import java.util.List;
import com.google.android.gcm.demo.app.sqllite.DatabaseSqlite;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class AlarmsService extends Service {
DatabaseSqlite db = new DatabaseSqlite(this);
List<Alerts> listAlerts;
PendingIntent pendingIntent;
String tag = "alerttService";
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Created from Alerts service ...",
Toast.LENGTH_LONG).show();
Log.i(tag, "Service created...");
}
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("TAG", "started onstart command Created from Alerts service .");
return super.onStartCommand(intent, flags, startId);// START_STICKY;
}
#Override
public void onStart(final Intent intent, int startId) {
super.onStart(intent, startId);
Toast.makeText(this, "Created from Alerts service started...",
Toast.LENGTH_LONG).show();
Log.i(tag, "Service started. ..");
// for looops
Thread thread = new Thread() {
#Override
public void run() {
Boolean x = true;
while (x) {
db.open();
listAlerts = db.getAlarmsForService();
db.close();
int alerts=listAlerts.size();
for (int i = 0; i < alerts; i++) {
Alerts item = listAlerts.get(i);
item.getRowId();
item.getRemoteServerId();
String alertInMills = item.getAlertDateInMills();
String alertDuration = item.getAlertDurationInMinutes();
String eventName = item.getEventName();
// intent.putExtra("eventState", item.getEventState());
// intent.putExtra("startTime", item.getStartTime());
// intent.putExtra("alertState", item.getAlertState());
// intent.putExtra("eventName", item.getEventName());
// intent.putExtra("location", item.getLocation());
// intent.putExtra("alertTime", item.getAlertTime());
// intent.putExtra("date", item.getDate());
long longAlertInMills = Long.parseLong(alertInMills);
pendingIntent = PendingIntent.getService(AlarmsService.this, 0,intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
// go to data base for time in mills
calendar.setTimeInMillis(longAlertInMills);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
pendingIntent);
//
System.out.println(calendar.toString());
}
//
System.out.println("thread");
x = false;
}
}
};
thread.start();
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed...", Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
BroadCast Receiver:
package com.google.android.gcm.demo.app.Alerts;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class AlarmsBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "BootReceiver";
Intent startServiceIntent;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
startServiceIntent = new Intent(context, AlarmsService.class);
context.startService(startServiceIntent);
Log.d("TAG", "alarmBroadcastReceiver");
System.out.println("alarm broadcast ...");
}
}
}

android BroadCastReceiver not working within an activity

I have want to develop an sms notifier. The thing is when SMS is receiced a textbox in the activity just change to "SMS Received" text.
SMS is successfully sending but BroadCastReceiver is not working, please help.
my code:
package com.shahid.todolist;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
* SmsManager smsManager = SmsManager.getDefault();
*
* String sendTo = "03129912287"; String myMessage =
* "Android supports programmatic SMS messaging!";
* smsManager.sendTextMessage(sendTo, null, myMessage, null, null);
*/
final EditText phoneNo = (EditText) findViewById(R.id.phoneNo);
final TextView display = (TextView) findViewById(R.id.txtDisplay);
Button buttonOne = (Button) findViewById(R.id.button1);
buttonOne.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
SmsManager smsManager = SmsManager.getDefault();
display.setText("Sending SMS...");
String sendTo = phoneNo.getText().toString();
String myMessage = "This is Shahid from Android";
smsManager.sendTextMessage(sendTo, null, myMessage, null, null);
}
});
// ---
final BroadcastReceiver receiver = new BroadcastReceiver() {
private static final String queryString = "#echo ";
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
#Override
public void onReceive(Context context, Intent _intent) {
if (_intent.getAction().equals(SMS_RECEIVED)) {
display.setText("SMS Received");
}
}
};
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
You have to register your broadcast when it is within your activity.
#Override
protected void onResume() {
IntentFilter filter = new IntentFilter();
filter.addAction(BroadcastReceiver.SMS_RECEIVED); // Provide you intent filter for message received.
registerReceiver(receiver, filter);
super.onResume();
}
#Override
protected void onPause() {
unregisterReceiver(receiver);
super.onPause();
}
In case this helps someone, in my case the problem was that I was using special characters like brackets in my text. Once I removed those characters it started working

Categories

Resources