I want to start an activity in my onReceive() method.
package com.splashscreenactivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
public class SMSReceiver extends BroadcastReceiver {
public static String trigger_message = "";
#Override
public void onReceive(Context context, Intent intent) {
// ---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null) {
// ---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
trigger_message = msgs[i].getMessageBody().toString();
str += trigger_message;
str += "\n";
}
// ---display the new SMS message---
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
if (trigger_message.equals("dx")) {
Toast.makeText(context, "I am triggered", Toast.LENGTH_LONG)
.show();
// /////////////////////////
// i want to start here
// ////////////////////////
// MainScreenActivity.trigger="Now";
// Intent i = new Intent(context,GPS.class);
// i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// context.startActivity(i);
} else {
Toast.makeText(context, "I am not triggered, Bbyz!!!",
Toast.LENGTH_LONG).show();
}
}
}
}
here is GPS.class
package com.splashscreenactivity;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.widget.TextView;
import android.widget.Toast;
public class GPS extends Activity implements LocationListener {
TextView latitude, logitude;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gps);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f,
this);
Toast.makeText(this, "i m started", Toast.LENGTH_LONG);
// latitude = (TextView)findViewById(R.id.txtLat);
// logitude = (TextView)findViewById(R.id.txtLongi);
// latitude.setText("Loading...");
// logitude.setText("Loading...");
}
String LATTITUDE;
String LOGITUDE;
#Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lag = location.getLongitude();
LATTITUDE = Double.toString(lat);
LOGITUDE = Double.toString(lag);
// latitude.setText(LATTITUDE);
// logitude.setText(LOGITUDE);
// SmsManager sm = SmsManager.getDefault();
// // here is where the destination of the text should go
// String number = "5556";
// sm.sendTextMessage(number, null,
// "latitude="+latitude.getText()+"\nlongitude="+logitude.getText(),
// null, null);
}
#Override
public void onProviderDisabled(String arg0) {
}
#Override
public void onProviderEnabled(String arg0) {
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
// /** Register for the updates when Activity is in foreground */
// #Override
// protected void onResume()
// {
// super.onResume();
// lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f,
// this);
// }
//
// /** Stop the updates when Activity is paused */
// #Override
// protected void onPause() {
// super.onPause();
// lm.removeUpdates(this);
// }
}
You have context passed as parameter to onRecieve() method, so just use:
#Override
public void onReceive(Context context, Intent intent) {
//start activity
Intent i = new Intent();
i.setClassName("com.test", "com.test.MainActivity");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
It works, of course you have to change package and activity class name to your own.
I am using this and its work on my site:
Intent intentone = new Intent(context.getApplicationContext(), DialogAct.class);
intentone.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intentone);
Intent intent1 = new Intent();
intent1.setClassName(context.getPackageName(), MainActivity.class.getName());
intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent1);
to prevent those package exceptions
Related
I am trying to implement contact pciker in android, i am able to launch contact picker in android, but when i select the contact i get back null value, i.e. no number in my textfield. What am i doing wrong ?
Here is my code.
mainactivity.java
package com.example.textmessage;
import java.util.Timer;
import java.util.TimerTask;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Contacts.People;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.Settings;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.support.v4.app.FragmentActivity;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import com.google.android.gms.maps.SupportMapFragment;
import android.widget.Toast;
public class MainActivity extends FragmentActivity{
protected static final int CONTACT_PICKER_RESULT = 0;
int count=0;
private RadioButton radioBtnten;
private RadioButton radioBtnone;
Button sendBtn,contact;
EditText txtphoneNo;
EditText txtMessage;
GPSTracker gps;
Timer timer;
TimerTask timerTask;
final Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled)
{
Toast.makeText(getApplicationContext(), "Your GPS IS NOT ON SWITCH IT ON HERE",Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
radioBtnten=(RadioButton)findViewById(R.id.ten);
radioBtnone=(RadioButton)findViewById(R.id.one);
sendBtn = (Button) findViewById(R.id.btnSendSMS);
txtphoneNo= (EditText) findViewById(R.id.editTextPhoneNo);
contact = (Button)findViewById(R.id.contact);
//txtMessage //= (EditText) findViewById(R.id.editTextSMS);
gps = new GPSTracker(MainActivity.this);
contact.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, CONTACT_PICKER_RESULT);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Uri contact = data.getData();
ContentResolver cr = getContentResolver();
Cursor c = managedQuery(contact, null, null, null, null);
// c.moveToFirst();
while(c.moveToNext()){
String id = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(Phone.CONTENT_URI,null,Phone.CONTACT_ID +" = ?", new String[]{id}, null);
while(pCur.moveToNext()){
String phone = pCur.getString(pCur.getColumnIndex(Phone.NUMBER));
txtphoneNo.setText(phone);
}
}
}
sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startTimer();
sendSMSMessage();
Intent toAnotherActivity = new Intent(MainActivity.this, maps.class);
startActivityForResult(toAnotherActivity, 0);
}
});
}
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//schedule the timer, after the first 5000ms the TimerTask will run every 10000ms//
if(radioBtnten.isChecked()==true)
timer.schedule(timerTask, 5000, 10000);
// if(radioBtn2.isSelected()==true)
else if(radioBtnone.isChecked()==true)
timer.schedule(timerTask, 5000, 1000);
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
//use a handler to run a toast that shows the current timestamp
handler.post(new Runnable() {
public void run() {
//get the current timeStamp
Toast.makeText(getApplicationContext(), "your message has been sent, the message(s) sent are:-"+count++,Toast.LENGTH_LONG).show();
sendSMSMessage();
//show the toast
}
});
}
};
}
public void stoptimertask(View v)
{
//stop the timer, if it's not already null
Toast.makeText(getApplicationContext(), "Stop button pressed",Toast.LENGTH_LONG).show();
if (timer != null)
{
timer.cancel();
timer = null;
}
}
protected void sendSMSMessage() {
Log.i("Send SMS", "");
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
String phoneNo = txtphoneNo.getText().toString();
String message = "These are my co-ordinates:-"+ latitude + ", " + longitude;
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#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;
}
}
P.S. i have mentioned the permission in manifest.
From your code it seems to be you have not added onActivityResult method. Put the following code in in onActivityResult method
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
Uri contact = data.getData();
ContentResolver cr = getContentResolver();
Cursor c = managedQuery(contact, null, null, null, null);
while(c.moveToNext()){
String id = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(Phone.CONTENT_URI,null,Phone.CONTACT_ID +" = ?", new String[]{id}, null);
while(pCur.moveToNext()){
String phone = pCur.getString(pCur.getColumnIndex(Phone.NUMBER));
tv.setText( phone);
}
}
}}
I have implemented a class named Reciever which Extends Broadcast reciever...
what i want is that either to show the recieved sms in toast i want to send it in another java class wich is extends from Activity..here is the code of that class..
package com.sms.sms;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.widget.Toast;
public class Reciever extends BroadcastReceiver {
final SmsManager sms = SmsManager.getDefault();
String msg="";
String number="";
#Override
public void onReceive(Context arg0, Intent inn)
{
Bundle bndl = inn.getExtras();
try
{
if(bndl != null)
{
Object[] sms_details= (Object[]) bndl.get("pdus");
for(int i=0 ; i<sms_details.length ; i++)
{
SmsMessage message = SmsMessage.createFromPdu((byte[]) sms_details[i]);
number = message.getDisplayOriginatingAddress();
msg = message.getDisplayMessageBody();
// Toast.makeText(arg0, "Sender Number = "+number+" Your Message = "+msg, Toast.LENGTH_LONG).show();
}
Intent in = new Intent();
in.setAction("SMS_RECIEVED_ACTION");
in.putExtra("msg", msg);
in.putExtra("num", number);
arg0.sendBroadcast(in);
}
}
catch(Exception e)
{
Toast.makeText(arg0, "Error", Toast.LENGTH_SHORT).show();
}
}
}
now i have another class named sms reciver which contain 2 edittexts in which i want to show these msgs...
package com.sms.sms;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
public class recieve_sms extends Activity {
EditText edt_msg;
Bundle bndl;
Button btn_rply;
EditText edt_num;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recieve);
edt_msg = (EditText) findViewById(R.id.editText2);
edt_num = (EditText) findViewById(R.id.editText1);
btn_rply = (Button) findViewById(R.id.button1);
//here should be some code which recieve msg from Reciever class and show in edittexts..
}
}
Assuming your broadcast receiver is working correctly and your variable msg and number are perfect too.
First option Show using Toast:
Just add this after your for:
Toast.makeText(context, msg, Toast.LENGTH_SHORT);
Second option Show on other activity:
Intent intent = new Intent(context, recieve_sms.class);
intent.putExtra("msg", msg);
intent.putExtra("num", number);
startActivity(intent);
On onCreate of recieve_sms:
Intent intent = getIntent();
String number = intent.getStringExtra("num");
String msg = intent.getStringExtra("msg");
The simple code is you can do like this
package com.tcs.smsactivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
public class MySMSReceiver extends BroadcastReceiver {
String action,from,message;
public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";
#Override
public void onReceive(Context context, Intent intent) {
action=intent.getAction();
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
if(null != bundle)
{
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
if(action.equals(SMS_RECEIVED_ACTION)){
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
info += msgs[i].getOriginatingAddress();
info += "\n*****TEXT MESSAGE*****\n";
info += msgs[i].getMessageBody().toString();
from=msgs[i].getOriginatingAddress();
message=msgs[i].getMessageBody().toString();
}
}
}
Intent showMessage=new Intent(context, AlertMessage.class);
showMessage.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
showMessage.putExtra("from", from);
showMessage.putExtra("message", message);
context.startActivity(showMessage);
}
}
Now inside your AlertMessage Activity class you can grab all the data and set in to the edit text :
AlertMessage.java
public class AlertMessage extends Activity{
String from,message;
private Bundle bundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.screen);
bundle=getIntent().getExtras();
if(null!=bundle){
from=bundle.getString("from");
message=bundle.getString("message");
// set the information in to edit text here
}
}
}
Hi i have a problem on my project, i have one activity and service , i use messenger to communication with us. I would view a alert dialog when i receive a message from service ,but this dialog is not appear. On log cat i see a log with text.
Do you have a solution .
My code is:
import java.lang.ref.WeakReference;
import java.util.List;
import java.util.Map;
import ztl.Bologna.activity.Database.DBopenHelper;
import ztl.Bologna.OverlayList;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Messenger;
import android.provider.BaseColumns;
import android.app.AlertDialog;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Menu;
public class MapsActivity extends MapActivity{
private MyLocationOverlay mOverlay;
protected static MapView gmap;
private DBopenHelper db;
OverlayList overlay;
private GuiHandler guiHandler;
private Messenger messenger;
public double destLat = 44.497592;
public double destLong = 11.356151;
private double Long = 11.352693;
private double Lat = 44.497271;
Intent serviceIntent;
public Cursor cursor;
int version ;
//final MapController control = gmap.getController();
GeoPoint gp = new GeoPoint((int)(Lat * 1e6),(int)(Long * 1e6));
//Context c = getApplicationContext();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
Context context;
context = getApplicationContext();
Log.e("context",""+context);
//db = new DBopenHelper(context);
db = new DBopenHelper(this,1);
guiHandler = new GuiHandler(this);
Log.d("put", "database");
gmap=(MapView)findViewById(R.id.mapview);
gmap.setClickable(true);
gmap.setBuiltInZoomControls(true);
mOverlay=new MyLocationOverlay(this,gmap);
//control.setCenter(gp);
// control.animateTo(gp);
gmap.getOverlays().add(mOverlay);
Lat=44.497271;
Long=11.352693;
updateMapOverlay();
db.close();
messenger = new Messenger(guiHandler);
serviceIntent = new Intent(MapsActivity.this,MessaggeService.class);
serviceIntent.putExtra(MessaggeService.CALLER, MessaggeService.POSITION);
serviceIntent.putExtra(MessaggeService.MESSENGER, messenger);
startService(serviceIntent);
Log.e("Debug", "Service Started from activity");
//ms = new MessaggeService(overlay,gmap,c);
///destLat = mOverlay.getMyLocation().getLatitudeE6();
//destLong = mOverlay.getMyLocation().getLongitudeE6();
}
private void addOpenPoint(GeoPoint g) {
OverlayItem overlayitem = new OverlayItem(g, "", "");
overlay.addOverlay(overlayitem);
Log.e("over",""+overlayitem);
}
protected void onResume() {
super.onResume();
mOverlay.enableMyLocation();
mOverlay.runOnFirstFix(new Runnable() {
// #Override
public void run() {
//gmap.invalidate();
gmap.getController().animateTo(mOverlay.getMyLocation());
gmap.getController().setZoom(16);
//updateMapOverlay();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_maps, menu);
return true;
}
void updateMapOverlay() {
List<Overlay> mapOverlays = gmap.getOverlays();
Drawable drawable = getResources().getDrawable(R.drawable.ic_launcher);
//mapOverlays.clear();
overlay = new OverlayList(drawable, this);
mapOverlays.add(overlay);
Cursor cursor = db.getZtlStreet();
if (cursor.moveToFirst()) {
while(cursor.moveToNext()) {
Integer lat = (int) (cursor.getDouble(cursor.getColumnIndex("latitude")) * 1e6);
Integer lon = (int) (cursor.getDouble(cursor.getColumnIndex("longitude")) * 1e6);
GeoPoint p = new GeoPoint(lat, lon);
addOpenPoint(p);
}
}
}
public static class GuiHandler extends Handler {
// TODO da unificare con quello ChooseEVSEActivity
public static final int FALSE = 0;
public static final int TRUE = 1;
// tiene il conto del tempo che è passato dall'ultima volta;
WeakReference<MapsActivity> wrActivity;
public GuiHandler(MapsActivity activity) {
wrActivity = new WeakReference<MapsActivity>(activity);
}
public void handleMessage(android.os.Message msg) {
final MapsActivity activity = wrActivity.get();
/*Create alert dialog to access on ztl street*/
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setMessage("Accesso Ztl non puoi accedere");
builder.setPositiveButton("chiudi",new DialogInterface.OnClickListener() {
//#Override
public void onClick(DialogInterface dialog, int id) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
switch (msg.what) {
case MessaggeService.UPDATE_UI_MSG:
AlertDialog alertMsg = builder.create();
alertMsg.show();
break;
}
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
My service with message is :
for(int i = 0 ; i< overlay.size();i++){
Log.e("item : ","n"+overlay.size());
OverlayItem item = overlay.getItem(i);
Location l1 = new Location("");
l1.setLatitude(item.getPoint().getLatitudeE6());
Log.e("l1", "l1"+l1.getLatitude());
l1.setLongitude(item.getPoint().getLongitudeE6());
Location l2 = new Location("");
l2.setLatitude(destLat);
l2.setLongitude(destLong);
Log.e("l2", "l2"+l2.getLatitude());
try {
String caller = "generic";
try {
caller = intent.getStringExtra(CALLER);
Bundle extras = intent.getExtras();
if (extras != null) {
if (POSITION.equals(caller)) {
positionMessenger = (Messenger) extras.get(MESSENGER);
Log.e("position",""+positionMessenger);
}
}
System.out.println("Instantiating " + caller + " Messenger OK :" + positionMessenger);
} catch (Exception e) {
//Log.e(UpdaterService.class.getName(), "Error instantiating " + caller + " Messenger" + e.getMessage());
//se il servizio non è ancora partito allora esco da esso in modo che venga istanziato correttamente
if(!doUpdate) {
stopSelf();
}
}
if (l2.distanceTo(l1) >100) {
Log.e("distance","Ztl non puoi accedere");
Message msg = Message.obtain();
Log.e("msg",""+msg);
msg.what = UPDATE_UI_MSG;
positionMessenger.send(msg);
Log.e("send","send");
}} catch (RemoteException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
You need to order the builder to show at the end
builder.show();
I am new to android programming and i encounter issue about the onReceive() method in Broadcast Receivers.I want to execute a specific method from the other class which is the MainActivity.java that has the method of TurnGPSOnOff(). It goes like this, every time system receive a SMS equal to the stored value in the shared preference the GPS will turn on if it is disabled and does vice versa.
MainActivity.java:
package com.smscontrol;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText editText1, editText2;
Button buttonSaveMem1;
#Override
/** Called when the activity is first created. */
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText1 = (EditText)findViewById(R.id.editText1);
editText2 = (EditText)findViewById(R.id.EditText01);
buttonSaveMem1 = (Button)findViewById(R.id.button1);
buttonSaveMem1.setOnClickListener(buttonSaveMem1OnClickListener);
LoadPreferences();
}
Button.OnClickListener buttonSaveMem1OnClickListener = new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SavePreferences("loc_key", editText1.getText().toString());
SavePreferences("gps_key", editText2.getText().toString());
Toast.makeText(getBaseContext(), "Keywords Saved.", Toast.LENGTH_SHORT).show();
LoadPreferences();
}
};
private void SavePreferences(String key, String value){
Context context = getApplicationContext();
AppPrefs appPrefs = new AppPrefs(context);
appPrefs.setLoc_key(editText1.getText().toString());
appPrefs.setGPS_key(editText2.getText().toString());
}
private void LoadPreferences(){
Context context = getApplicationContext();
AppPrefs appPrefs = new AppPrefs(context);
String strSavedMem1 = appPrefs.getLoc_key();
String strSavedMem2 = appPrefs.getGPS_key();
editText1.setText(strSavedMem1);
editText2.setText(strSavedMem2);
}
public void turnGPSOnOff(){
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps"))
{ //if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
else { //if gps is enabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
}
AppPrefs.java:
package com.smscontrol;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
public class AppPrefs {
private static final String KEYWORDS = "KEYWORDS";
private SharedPreferences appSharedPrefs;
private SharedPreferences.Editor prefsEditor;
private String gps_key = "gps_key_prefs";
private String loc_key = "loc_key_prefs";
public AppPrefs(Context context){
this.appSharedPrefs = context.getSharedPreferences(KEYWORDS, Activity.MODE_PRIVATE);
this.prefsEditor = appSharedPrefs.edit();
}
public String getGPS_key() {
return appSharedPrefs.getString(gps_key, null);
}
public void setGPS_key(String _gps_key) {
prefsEditor.putString(gps_key, _gps_key).commit();
}
public String getLoc_key() {
return appSharedPrefs.getString(loc_key, null);
}
public void setLoc_key(String _loc_key) {
prefsEditor.putString(loc_key, _loc_key).commit();
}
}
SmsListener.java:
package com.smscontrol;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
public class SmsListener extends BroadcastReceiver {
MainActivity Activity = new MainActivity();
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
AppPrefs appPrefs = new AppPrefs(context);
String strSavedMem1 = appPrefs.getLoc_key();
String strSavedMem2 = appPrefs.getGPS_key();
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
Bundle bundle = intent.getExtras(); //---get the SMS message passed in---
SmsMessage[] msgs = null;
String str = "";
if (bundle != null){
//---retrieve the SMS message received---
try{
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for(int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
str = msgs[i].getMessageBody().toString();
if (str.equals(strSavedMem1)){
Toast.makeText(context, "LOCATE", Toast.LENGTH_SHORT).show();
} else if (str.equals(strSavedMem2)){
Toast.makeText(context, "GPS", Toast.LENGTH_SHORT).show();
}
}
}catch(Exception e){
// Log.d("Exception caught",e.getMessage());
}
}
}
}
}
any advice or help will do. badly needed for the part of my thesis. thanks!
I am building an android app that stores the SMSs when they are received. Kindly look at the code and respond what's wrong with it.
private BroadcastReceiver receiver = new BroadcastReceiver() {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (intent.getAction() == SMS_RECEIVED){
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String addr = null,msg=null;
if (bundle != null)
{
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++)
{
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
addr = msgs[i].getOriginatingAddress();
msg= msgs[i].getMessageBody().toString();
Calendar c = Calendar.getInstance();
java.util.Date currDT= c.getTime();
String name = c2.getString(c2.getColumnIndex("name"));
db.execSQL("INSERT INTO inbox (num,msg,tm) VALUES('"+ addr + "','"+ msg + "','"+currDT+"')");
Toast.makeText(context, "Message Received from "+addr, Toast.LENGTH_SHORT).show();
} }}
};};
use this way :
i have used service because it running in background more then 30 sec.
Your Massage Reciver :
package com.massage_rec;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
public class MyPhoneReceiver extends BroadcastReceiver {
SharedPreferences sp;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
}
}
sendMail(context, str);
}
private void sendMail(Context context, String str) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(context, ServiceTemplate.class);
myIntent.putExtra("extraData", "" + str);
context.startService(myIntent);
}
}
ServiceTemplate.java
package com.massage_rec;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
public class ServiceTemplate extends Service {
String address = "";
String CALL_DETAILS;
String SMS_STR = "";
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
new LongOperation_().execute("");
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
private class LongOperation_ extends AsyncTask<String, Void, String> {
protected String doInBackground(String... params) {
try {
getSMS();
} catch (Exception e) {
Log.e("error before mail sent-->", ""
+ e.getMessage().toString());
e.printStackTrace();
}
return "";
}
protected void onPostExecute(String result) {
// Log.e("post exe", "------- post exe");
Intent myIntent = new Intent(getApplicationContext(), ServiceTemplate.class);
getApplicationContext().stopService(myIntent);
}
protected void onPreExecute() {
}
protected void onProgressUpdate(Void... values) {
}
}
public void getSMS() {
Context con = getApplicationContext();
Uri myMessage = Uri.parse("content://sms/");
ContentResolver cr = con.getContentResolver();
Cursor c = cr.query(myMessage, new String[] { "_id", "address", "date",
"body", "read" }, null, null, null);
// startManagingCursor(c);
// getSmsLogs(c, con);
int i = 0;
try {
if (c.moveToFirst()) {
do {
if (c.getString(c.getColumnIndexOrThrow("address")) == null) {
c.moveToNext();
continue;
}
String _id = c.getString(c.getColumnIndexOrThrow("_id"))
.toString();
String Number = c.getString(
c.getColumnIndexOrThrow("address")).toString();
String dat = c.getString(c.getColumnIndexOrThrow("date"))
.toString();
// String as = (String) get_dt(dat, "dd/MM/yyyy, hh.mma");
String Body = c.getString(c.getColumnIndexOrThrow("body"))
.toString();
SMS_STR = "num: " + Number + "\n";
SMS_STR = "date: " + dat + "\n";
SMS_STR = "Body: " + Body + "\n";
SMS_STR = "\n\n\n";
if (i > 1) {
break;
}
i++;
} while (c.moveToNext());
}
c.close();
db.inserSMS(Name,dat,Body);
} catch (Exception e) {
e.printStackTrace();
}
}
}
add below code in Android manifest file :
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>
<uses-permission android:name="android.permission.READ_LOGS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS"></uses-permission>
<receiver android:name=".MyPhoneReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<service android:name=".ServiceTemplate" android:enabled="true"></service>
to insert in to Sqlite DB check this link clickhere
Create Database that way and insert in DB.
private BroadcastReceiver receiver = new BroadcastReceiver() {}
that should give a compile error. Change name to something like,
class SomeBroadcastReceiver extends BroadcastReceiver() {}
And also dont forget to declare it in AndroidManifest.xml file