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!
Related
I want to get the sending status of each phone number, so I define a variable statusMap to record the status, 0 means success, 1 means failed. And I assign value to statusMap at onReceive function, but after that the statusMap's value is still empty. how can I change a static value in onReceive function
package com.mem.memsms;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;
import android.os.Bundle;
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.telephony.SmsManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class SendMessage extends Activity {
private EditText editText;
private Button button;
private Intent intent;
private SendBroadcast mSendReceiver;
private HashMap<String, String> hashMap;
private HashMap<String, String> statusMap = new HashMap<String, String>();
private Queue<String> numbers;
String SENT_SMS_ACTION = "SENT_SMS_ACTION";
String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_message);
editText = (EditText) this.findViewById(R.id.message);
intent = getIntent();
hashMap = (HashMap<String, String>) intent.getSerializableExtra("data");
numbers = new LinkedList<String>();
button = (Button) this.findViewById(R.id.sendmessage);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
numbers.clear();
editText.setEnabled(false);
final String text = editText.getText().toString();
if (text.trim() == "") {
editText.setHint(R.string.msg_null);
return;
}
Iterator<Entry<String, String>> iter = hashMap.entrySet()
.iterator();
while (iter.hasNext()) {
Map.Entry<String, String> entry = (Map.Entry<String, String>) iter
.next();
String number = entry.getKey();
String content = entry.getValue();
numbers.offer(number);
Sendmsg(number, content + text);
}
intent.putExtra("data2", statusMap);
setResult(RESULT_OK, intent);
//Log.i("msg", "statusMap length is" + statusMap.size());
// back to contacts
SendMessage.this.finish();
}
});
}
private class SendBroadcast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String n = numbers.poll();
switch (getResultCode()) {
case RESULT_OK:
Log.i("msg", "c:ok" + n);
statusMap.put(n, "0");
break;
default:
Log.i("msg", "c:failed" + n);
statusMap.put(n, "1");
break;
}
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
this.unregisterReceiver(mSendReceiver);
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
mSendReceiver = new SendBroadcast();
IntentFilter mSendFilter = new IntentFilter(SENT_SMS_ACTION);
this.registerReceiver(mSendReceiver, mSendFilter);
super.onResume();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.send_message, menu);
return true;
}
private void Sendmsg(String number, String content) {
Intent sentIntent = new Intent(SENT_SMS_ACTION);
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, sentIntent,
0);
//sentIntent.putExtra("status", statusMap);
SmsManager manager = SmsManager.getDefault();
manager.sendTextMessage(number, null, content, sentPI, null);
}
}
Remove this:
intent.putExtra("data2", statusMap);
setResult(RESULT_OK, intent);
//Log.i("msg", "statusMap length is" + statusMap.size());
// back to contacts
SendMessage.this.finish();
code from onClick and put it in onReceive:
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String n = numbers.poll();
switch (getResultCode()) {
case RESULT_OK:
Log.i("msg", "c:ok" + n);
statusMap.put(n, "0");
break;
default:
Log.i("msg", "c:failed" + n);
statusMap.put(n, "1");
break;
}
if(hashMap.size()==statusMap.size()){
intent.putExtra("data2", statusMap);
SendMessage.this.setResult(RESULT_OK, intent);
//Log.i("msg", "statusMap length is" + statusMap.size());
// back to contacts
SendMessage.this.finish();
}
}
The problem was that the onClick event is completed first that is you call set result and finish this activity and then onReceive is getting called so by the time your map is updated result was already sent
I am creating a project in which I am getting data from a server and displaying it through table view. Here is the code for Main activity class
package com.example.e_quates;
import java.net.URL;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
//import com.websmithing.broadcasttest.BroadcastService;
//import com.websmithing.broadcasttest.BroadcastService;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup.LayoutParams;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
//import java.sql.SQLException;
public class MainActivity extends Activity {
List<String> strs = new ArrayList<String>();
ResultSet rs=null;
TableLayout tl;
TableRow[] tr;
TextView[] tv;
private Intent intent;
private static final String TAG = "E-Quates";
int count=1;
public static DB db = new DB(<connection string>);
String query = "select top(10) SymbolName,LTP,Net_change,Bid_vol,Ask,Ask_vol,High_Index from NCDX_LiveData_new";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
strs=db.sqlexec(query);
db.closeConnection();
Log.e("connected ","success");
System.out.println("connection sucess");
tl=(TableLayout)findViewById(R.id.table);
Log.e("first row","created");
tr=new TableRow[strs.size()/7];
tv=new TextView[strs.size()];
//int i=0;
for(int i=0,j=-1;i<strs.size();i++)
{
Log.e("index "+i,"value is "+strs.get(i));
if(i%7==0)
{
j++;
Log.e("inside if","value "+i);
tr[j]=new TableRow(this);
tr[j].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
}
tv[i] = new TextView(this);
tv[i].setText(strs.get(i));
tv[i].setId(i);
tv[i].setBackgroundResource(R.drawable.row_shape);
tr[j].addView(tv[i]);
}
for(int i=0,j=-1;i<strs.size()/7;i++)
{
tl.addView(tr[i]);
Log.e("adding row",""+i);
}
//Thread.sleep(5000);
}
catch(Exception E)
{
System.out.println(E.toString());
}
intent = new Intent(this, BroadcastService.class);
}
public void onResume() {
super.onResume();
startService(intent);
Log.e("service","called");
registerReceiver(broadcastReceiver, new IntentFilter(BroadcastService.BROADCAST_ACTION));
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
stopService(intent);
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.e("in the","receiver");
updateUI(intent);
}
};
private void updateUI(Intent intent) {
strs.clear();
//String dummy = null;
Log.e("inside ","UI update");
//db.sqlexec(query);
try
{
strs = intent.getStringArrayListExtra("TAG");
//application_main apm=((application_main) getApplicationContext());
for(int i=0;i<strs.size();i++)
{
Log.e("inside for","loo[");
tv[i].setText(strs.get(i));
}
}
catch(Exception e)
{
Log.e("exception occured in intent value",e.toString());
}
//Log.e("value is ",dummy.toString());
//Thread.sleep(5000);
}
}
Here is my DB class
package com.example.e_quates;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
//import android.widget.*;
class DB extends Activity
{
List<String> strs = new ArrayList<String>();
ResultSet rs=null;
Connection conn=null;
private Intent intent;
#SuppressLint("NewApi")
String query = "select top(10) SymbolName,LTP,Net_change,Bid_vol,Ask,Ask_vol,High_Index from NCDX_LiveData_new";
public DB(String db_connect_string,String db_userid,String db_password) {
System.out.println("inside DB");
Log.e("inside DB","");
try
{
StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Log.e("Inside first","try block");
Class.forName("net.sourceforge.jtds.jdbc.Driver");
conn = DriverManager.getConnection(db_connect_string, db_userid, db_password);
Log.e("Connection sucessfull","");
}catch (Exception e)
{
e.printStackTrace();
}
}
public List<String> sqlexec(String sql)
{
try
{
Statement stmt = null;
strs.clear();
try {
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
Log.e("##########################################################################3","result in rs");
while (rs.next()) {
strs.add(rs.getString("SymbolName"));
strs.add(rs.getString("LTP"));
strs.add(rs.getString("Net_change"));
strs.add(rs.getString("Bid_vol"));
strs.add(rs.getString("Ask"));
strs.add(rs.getString("Ask_vol"));
strs.add(rs.getString("High_Index"));
Log.e("symbolname",rs.getString("SymbolName"));
}
}catch (Exception e)
{
e.printStackTrace();
}
}
catch(Exception e)
{
Log.e("error:",e.toString());
}
Log.e("return ","to main");
int size=strs.size();
Log.e("array size in DB",""+size);
//Log.e("set string",String.valueOf(apm.getState()));
Log.e("application ","initialized");
return strs;
}
public void closeConnection()
{
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
And here is the service class
package com.example.e_quates;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
public class BroadcastService extends Service {
List<String> strs_array1 = new ArrayList<String>();
private static final String TAG = "E-Quates";
public static final String BROADCAST_ACTION = "com.example.e_quates";
private final Handler handler = new Handler();
Intent intent;
String query = "select top(10) SymbolName,LTP,Net_change,Bid_vol,Ask,Ask_vol,High_Index from NCDX_LiveData_new";
int counter = 0;
DB db1=new DB(<connection string>);
//String dummy;
#Override
public void onCreate() {
super.onCreate();
//db1.forService();
intent = new Intent(BROADCAST_ACTION);
}
#Override
public void onStart(Intent intent, int startId) {
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 3000); // 3 second
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
DisplayLoggingInfo();
handler.postDelayed(this, 3000); // 3 seconds
}
};
private void DisplayLoggingInfo() {
Log.d(TAG, "entered DisplayLoggingInfo");
strs_array1=db1.sqlexec(query);
intent.putStringArrayListExtra(TAG, (ArrayList<String>)strs_array1);
sendBroadcast(intent);
Log.e("Broadcast","done");
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
handler.removeCallbacks(sendUpdatesToUI);
super.onDestroy();
}
}
The problem is that when I am calling the DB class's sqlexec() function from main activity class it is return correct value but while is I am calling it service class it is not returning the SQL output. I have tried every possible combination of calling the sqlexec() function inside the service class,but same problem is occurring.
the function db.sqlexec(query) is not returning any value..
I have referred the link for help:
Don't do any initialization in the Service constructor. Android constructs Android components (Activity, Service, BroadcastReceiver, ContentProvider) using its own mechanisms. Move all your initialization code from the constructor to the onCreate() method.
EDIT: Clarify my instructions
I am referring to this code:
List<String> strs_array1 = new ArrayList<String>();
private static final String TAG = "E-Quates";
public static final String BROADCAST_ACTION = "com.example.e_quates";
private final Handler handler = new Handler();
Intent intent;
String query = "select top(10) SymbolName,LTP,Net_change,Bid_vol,Ask,Ask_vol,High_Index from NCDX_LiveData_new";
int counter = 0;
DB db1=new DB(<connection string>);
These variables will be initialized in the constructor (even though you haven't explicitly created a constructor, one will be created for you). The constants aren't a problem, but these may cause you a problem:
private final Handler handler = new Handler();
DB db1=new DB(<connection string>);
You will want to be creating the Handler in onCreate(). I don't know what your DB class is doing, but you probably want to be creating that instance also in onCreate().
EDIT 2
I now see the code for your DB class. You can't do this like this! Your DB class extends Activity. You cannot create an instance of this class like this:
DB db1=new DB(<connection string>);
Android components (Activity, Service, BroadcastReceiver, ContentProvider) are created by the Android framework using its own mechanisms.
Why does your DB class extend Activity? It doesn't need to.
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 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