Store SMS when received - android

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

Related

Read SMS and perform action

I have been searching for a long time but sadly I found no solution for my problem, or I just dont understand how to do that.
I want to read a sms and then do some stuff if the text equals my string text.
Broadcast Receiver is registered in manifest
When I erase the part where I ask for number, and just tell it to make a toast depending on the sms body, it works.
package com.journaldev.broadcastreceiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
import android.telephony.SmsManager
public class SmsReceiver extends BroadcastReceiver {
String msg1 = "Testmessage 1";
String msg2 = "Testmessage 2";
}
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = 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]);
if(msgs[i].getOriginatingAddress().equals("01XXXX")) {
String msg = msgs[i].getMessageBody();
if (msg == msg1) {
Toast.makeText(context, " Test 1", Toast.LENGTH_SHORT).show(); //just an example for tests
}
else if (msg == msg2) {
Toast.makeText(context, "Test 2", Toast.LENGTH_SHORT).show();//just an example for tests
}
}
}
}
}
String value comparision should use mystr1.equals(mystr2) or mystr1.equalsIgnoreCase(mystr2) function.
If you use mystr1==mystr2 then you are checking for variables reference("pointer") to the same object instance.
Okay thanks for help, comparing messages works now and I also found the problem with the Number.
It was:
if(msgs[i].getOriginatingAddress().equals("01XXXX")) {
I changed it to:
if (PhoneNumberUtils.compare(number, sender)){
Here my full code:
package com.example.ossas.smsreader;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.PhoneNumberUtils;
import android.telephony.SmsMessage;
import android.widget.Toast;
public class IncomingSms extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String number = "0XXXX";
String msg1 = "Testmessage 1";
String msg2 = "Testmessage 2";
Bundle bundle = intent.getExtras();
SmsMessage[] msgs;
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]);
String sender = msgs[i].getOriginatingAddress();
if (PhoneNumberUtils.compare(number, sender)){
String msg = msgs[i].getMessageBody();
if (msg.equals(msg1)) {
Toast.makeText(context, "Testmessage 1", Toast.LENGTH_SHORT).show(); //just an example for tests
} else if (msg.equals(msg2)) {
Toast.makeText(context, "Testmessage 2", Toast.LENGTH_SHORT).show();//just an example for tests
}
}
}
}
}
}

display incoming sms as textview android

i'm trying to develop app(tester) that display a incoming message as textview
i have incoming listener SMS class look like this (based on this code)
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.util.Log;
import android.widget.Toast;
public class IncomingSms extends BroadcastReceiver {
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage
.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage
.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
Log.i("SmsReciver", "senderNum: " + senderNum
+ ", message: " + message);
} // end of for loop
} // bundle
} catch (Exception e) {
// TODO: handle exception
Log.e("SmsReciver", "Exception smsReciver" + e);
}
}
}
i want to pass the "String message" in there to my mainactivity....so i can dispaly it as texview...any chance to do it? thank you
You could implement your broadcast receiver directly from within the Activity that is supposed to display the message in a TextView.

How can I keep track of sent and received messages in an android messaging app?

I'm new to Android development (but not to Java) and I'm writing my own Android messaging app that hopefully should take the place of the default SMS app. My question is - how does the default SMS app keep track of sent and received messages and how might I accomplish the same task? Specifically, I can't figure out how to find, store, and display a conversation history between the device user and a member of their contact list. I don't have any preliminary code yet, because frankly, I have no idea where to begin.
EDIT: Trying to set up a BroadcastReceiver as a first step (gotta start somewhere) but I'm struggling getting my app to fire when the notification comes through the device (I'm using emulators).
Here is my BroadcastReceiver Class (based on example from below)
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Telephony;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
public class smsBroadcastReceiver extends BroadcastReceiver {
private static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
private static final String TAG = "smsBroadcastReceiver";
private static final String SMS_SENT = "android.provider.Telephony.SMS_SENT";
final SmsManager mySMSManager = SmsManager.getDefault();
String phoneNumber, message;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(SMS_RECEIVED)) handleIncMessage(intent.getExtras(), context);
else if (intent.getAction().equals(SMS_SENT)) sendSMS(intent.getExtras(), context);
}
void sendSMS(Bundle bundle, Context context){
phoneNumber = bundle.getString(Intent.EXTRA_PHONE_NUMBER);
Log.e("info", "Outgoing Number: " + phoneNumber);
context.sendBroadcast(new Intent("onNewMsgSend"));
}
void handleIncMessage(Bundle bundle, Context context) {
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
//database stuff...
final SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
String sendingNum = messages[i].getDisplayOriginatingAddress();
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
String message = messages[i].getDisplayMessageBody();
Intent msgIntent = new Intent(context, conversationView.class);
msgIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(msgIntent);
// Log.i(TAG, "SENDER: " + sendingNum +"; Message: " + message);
System.out.println("SENDER: " + sendingNum +"; Message: " + message);
}
context.sendBroadcast(new Intent("onNewMsg"));
}
}
}
My best guess is that I'm doing something wrong in my Activities, but I'm not sure what. Do I need to send my intent to my main (launching) activity and then delegate the intent from there, or can I send it to an activity that isn't the launcher (which is what I'm trying to do now)?
EDIT: BroadcastReceiver problem solved.
Try this way,hope this will help you to solve your problem
Step 1.
This is your first home class
public class MainActivity extends Activity {
Context context;
Activity act;
ListView lvsms;
public static String msg = "msg", phoneNo = "phoneNo", time = "time";
public static String typeMsg = "0";
public static String typeSend = "1";
// String typeDeliver = "2";
TextView smsno_record;
SimpleCursorAdapter adapter1;
BroadcastReceiver onNewMsg = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
}
};
BroadcastReceiver onNewMsgSend = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
}
};
// BroadcastReceiver deliveredreceiver = new BroadcastReceiver() {
// #Override
// public void onReceive(Context context, Intent intent) {
//
// }
// };
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(onNewMsg);
unregisterReceiver(onNewMsgSend);
// unregisterReceiver(deliveredreceiver);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerReceiver(onNewMsg, new IntentFilter("onNewMsg"));
registerReceiver(onNewMsgSend, new IntentFilter("onNewMsgSend"));
// registerReceiver(deliveredreceiver, new IntentFilter(
// "deliveredreceiver"));
setContentView(R.layout.complete_sms_data);
context = MainActivity.this;
act = MainActivity.this;
lvsms = (ListView) findViewById(R.id.lvsms);
smsno_record = (TextView) findViewById(R.id.smsno_record);
smsdetails(typeMsg);// sendboxSMS();
}
void smsdetails(String type) {
Database db = new Database(context);
// ArrayList<HashMap<String, String>> al = db.getRecord(type);
LinkedList<HashMap<String, String>> al = db.getRecord(type);
Log.e("test", "sms al :- " + al.size());
db.close();
for (int i = 0; i < al.size(); i++) {
HashMap<String, String> hm = al.get(i);
String name = getName(getContentResolver(), hm.get(phoneNo));
hm.put("name", hm.get(phoneNo) + " " + name);
Log.e("test", "name :- " + name);
}
if (al.size() > 0) {
lvsms.setVisibility(View.VISIBLE);
CustomAdapter adapter = null;
if (type.equals(typeMsg)) {
Log.e("test", "if condition 1st");
adapter = new CustomAdapter((Activity) context, al);
lvsms.setAdapter(adapter);
// adapter = new SimpleAdapter(context, al,
// R.layout.list_items_msgs, new String[] { "name", msg,
// time }, new int[] { R.id.txtPhoneNo,
// R.id.txtMsg, R.id.txtTime });
} else if (type.equals(typeSend)) {
Log.e("test", "if condition 2st");
adapter = new CustomAdapter((Activity) context, al);
lvsms.setAdapter(adapter);
// adapter = new SimpleAdapter(context, al,
// R.layout.list_items_msgs, new String[] { "name", msg,
// time }, new int[] { R.id.txtPhoneNo,
// R.id.txtMsg, R.id.txtTime });
}
// else if (type.equals(typeDeliver)) {
// adapter = new SimpleAdapter(context, al,
// R.layout.list_items_msgs, new String[] { "name", msg,
// time }, new int[] { R.id.txtPhoneNo,
// R.id.txtMsg, R.id.txtTime });
// }
lvsms.setAdapter(adapter);
smsno_record.setVisibility(View.GONE);
} else {
Log.e("test", "else condition ");
lvsms.setAdapter(null);
lvsms.setVisibility(View.GONE);
}
}
}
Step 2.
This is your receiver for sms
public class Receiver extends BroadcastReceiver {
final SmsManager sms = SmsManager.getDefault();
String phoneNumber, message;
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(
"android.provider.Telephony.SMS_RECEIVED")) {
handleIncomingMsg(intent.getExtras(), context);
} else if (intent.getAction().equals(
"android.provider.Telephony.SMS_SENT")) {
sendSMS(intent.getExtras(), context);
}
}
void handleIncomingMsg(Bundle bundle, Context context) {
Object[] pdusObj = (Object[]) bundle.get("pdus");
Database db = new Database(context);
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage
.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
Intent in1 = new Intent(context, MainActivity.class);
in1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(in1);
Log.i("SmsReceiver", "senderNum: " + senderNum + "; message: "
+ message);
db.insertRecord(senderNum, message, MainActivity.typeMsg);
}
context.sendBroadcast(new Intent("onNewMsg"));
db.close();
}
void sysAlert(String title, String msg, Context context) {
AlertDialog alert = new AlertDialog.Builder(context).setTitle(title)
.setMessage(msg)
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).create();
alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alert.setCanceledOnTouchOutside(false);
alert.show();
}
public void onDestroy() {
telephony.listen(null, PhoneStateListener.LISTEN_NONE);
}
TelephonyManager telephony;
MyPhoneStateListener phoneListener;
boolean ring = false;
boolean callReceived = false;
void handleCalls(Context context) {
if (phoneListener == null) {
phoneListener = new MyPhoneStateListener(context);
telephony = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(phoneListener,
PhoneStateListener.LISTEN_CALL_STATE);
}
}
void sendSMS(Bundle bundle, Context context) {
phoneNumber = bundle.getString(Intent.EXTRA_PHONE_NUMBER);
Log.e("info", "Outgoing Number: " + phoneNumber);
Database db = new Database(context);
db.insertRecord(phoneNumber, "hii", MainActivity.typeSend);
//
// }
db.close();
context.sendBroadcast(new Intent("onNewMsgSend"));
}
}
Sept 3.
Put permissions in mainfest
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

Android ListView items ID

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
}
}
}

Start Activity inside onReceive BroadcastReceiver

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

Categories

Resources