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
Related
when I listen push message from BroadcastReceiver I can take message but it makes slow other services for example I am sending "Message is taken" to my web service when I take push message but I can't send to my webservice it works very slowly when I listen to BroadcastReceiver for take message and when I delete BroadcastReceiver I can send message to my webservice very fastly
package jsonparse;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.androidhive.pushnotifications.MapsActivity;
import com.androidhive.pushnotifications.R;
import com.androidhive.pushnotifications.ServerUtilities;
import com.androidhive.pushnotifications.WakeLocker;
import com.daasuu.ahp.AnimateHorizontalProgressBar;
import com.google.android.gcm.GCMRegistrar;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static com.androidhive.pushnotifications.CommonUtilities.DISPLAY_MESSAGE_ACTION;
import static com.androidhive.pushnotifications.CommonUtilities.EXTRA_MESSAGE;
import static com.androidhive.pushnotifications.CommonUtilities.SENDER_ID;
public class ListViewAdapter extends BaseAdapter implements OnClickListener{
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
//ProgressBar mprogressBar;
TextView fulness;
TextView location_info;
TextView descrip;
JSONObject jsonobject;
private Handler mHandler = new Handler();
private int mProgressStatus=0;
String get_enlem,get_boylam;
double dble_get_enlem,dble_get_boylam;
String dest_city_name,dest_state_name,dest_country_name;
NetworkInfo ni;
ConnectivityManager cm;
String get_location;
String device_id;
String sonuc;
SharedPreferences prefs;
String get_groupID, get_customerID;
String get_desc;
String get_toplam;
// Asyntask
AsyncTask<Void, Void, Void> mRegisterTask;
public static String name;
public static String email;
Context con;
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
/*
TextView rank;
TextView country;
TextView population;
ImageView flag;
*/
TextView location;
AnimateHorizontalProgressBar progressBar;
Button cop_toplandi;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
//rank = (TextView) itemView.findViewById(R.id.rank);
//country = (TextView) itemView.findViewById(R.id.country);
//population = (TextView) itemView.findViewById(R.id.population);
//Get Device IMEI number
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
device_id = telephonyManager.getDeviceId();
Log.i("IMEI NUMBER", device_id);
// Getting name, email from intent
Intent i = ((Activity) context).getIntent();
name = i.getStringExtra("get_message_name");
email = i.getStringExtra("email");
Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(context);
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(context);
context.registerReceiver(mHandleMessageReceiver, new IntentFilter(
DISPLAY_MESSAGE_ACTION));
// Get GCM registration id
final String regId = GCMRegistrar.getRegistrationId(context);
// Check if regid already presents
if (regId.equals("")) {
// Registration is not present, register now with GCM
GCMRegistrar.register(context, SENDER_ID);
} else {
// Device is already registered on GCM
if (GCMRegistrar.isRegisteredOnServer(context)) {
// Skips registration.
// Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG).show();
} else {
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context contextm = context;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
// Register on our server
// On server creates a new user
ServerUtilities.register(contextm, name, email, regId);
return null;
}
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
}
}
}
};
handler.postDelayed(r, 1000);
prefs = context.getSharedPreferences("login_page", context.MODE_PRIVATE);
get_groupID = prefs.getString("user_groupID", "alınmadı");
get_customerID = prefs.getString("user_customerID", "alınmadı");
if (get_groupID.equals("null")) {
get_groupID = "0";
}
if (get_customerID.equals("null")) {
get_customerID = "0";
}
location = (TextView) itemView.findViewById(R.id.location);
progressBar = (AnimateHorizontalProgressBar) itemView.findViewById(R.id.animate_progress_bar);
fulness = (TextView) itemView.findViewById(R.id.txt_percentage_of_fulness);
descrip = (TextView) itemView.findViewById(R.id.txt_desc);
get_location = resultp.get(MainActivity.COUNTRY);
cop_toplandi = (Button) itemView.findViewById(R.id.secret_button);
cop_toplandi.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context.getApplicationContext(),"Başarıyla Gönderildi",Toast.LENGTH_SHORT).show();
new Send_save_status().execute();
}
});
location_info = (TextView) itemView.findViewById(R.id.location_info);
// Locate the ImageView in listview_item.xml
//flag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
//rank.setText(resultp.get(MainActivity.RANK));
//country.setText(resultp.get(MainActivity.COUNTRY));
//population.setText(resultp.get(MainActivity.POPULATION));
location.setText(resultp.get(MainActivity.COUNTRY));
location_info.setText(resultp.get(MainActivity.Location_info));
String get_descrip = resultp.get(MainActivity.DESCB);
if(get_descrip != "0"){
descrip.setText(resultp.get(MainActivity.DESCB));
cop_toplandi.setVisibility(View.VISIBLE);
}
get_enlem = resultp.get(MainActivity.POPULATION);
get_boylam = resultp.get(MainActivity.FLAG);
get_toplam = resultp.get(MainActivity.Toplam);
//dble_get_enlem = Double.parseDouble(get_enlem);
//dble_get_boylam = Double.parseDouble(get_boylam);
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
//imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), flag);
// Capture ListView item click
String a = resultp.get(MainActivity.RANK);
int b = Integer.parseInt(a);
progressBar.setMax(100);
progressBar.setProgress(b);
//progressBar.setProgressWithAnim(b);
fulness.setText("%"+(b*1));
//mprogressBar = (ProgressBar) itemView.findViewById(R.id.progressBar);
//mprogressBar.setProgress(b);
/*
ObjectAnimator anim = ObjectAnimator.ofInt(mprogressBar, "progress", 0, 80);
anim.setDuration(5000);
anim.setInterpolator(new DecelerateInterpolator());
anim.start();
*/
/*
//Get location name from latitude and longitude
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(dble_get_enlem, dble_get_boylam, 1);
} catch (IOException e) {
e.printStackTrace();
}
dest_city_name = addresses.get(0).getAddressLine(0);
dest_state_name = addresses.get(0).getAddressLine(1);
dest_country_name = addresses.get(0).getAddressLine(2);
location_info.setText(dest_city_name + " " + dest_country_name);
*/
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
ni = cm.getActiveNetworkInfo();
if (ni != null && ni.isConnected()) {
Toast.makeText(context,context.getString(R.string.progressdialog_message), Toast.LENGTH_SHORT).show();
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, MapsActivity.class);
// Pass all data rank
intent.putExtra("level", resultp.get(MainActivity.RANK));
// Pass all data country
intent.putExtra("imei", resultp.get(MainActivity.COUNTRY));
// Pass all data population
intent.putExtra("enlem",resultp.get(MainActivity.POPULATION));
// Pass all data flag
intent.putExtra("boylam", resultp.get(MainActivity.FLAG));
// Start SingleItemView Class
context.startActivity(intent);
}else{
Toast.makeText(context.getApplicationContext(),context.getApplicationContext().getString(R.string.network_connection),Toast.LENGTH_SHORT).show();
}
}
});
return itemView;
}
#Override
public void onClick(View v) {
switch (v.getId()){
}
}
/**
* Receiving push messages
* */
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
// Waking up mobile if it is sleeping
WakeLocker.acquire(context);
//context.sendBroadcast(new Intent("com.google.android.intent.action.GTALK_HEARTBEAT"));
//context.sendBroadcast(new Intent("com.google.android.intent.action.MCS_HEARTBEAT"));
// Showing received message
//lblMessage.append(newMessage + "\n");
//Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();
//descrip.setText(newMessage);
// Intent go = new Intent(context.getApplicationContext(),IsEmri.class);
//context.startActivity(go);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Acil Durum!!!");
builder.setMessage(newMessage)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// TODO: handle the OK
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
// Releasing wake lock
WakeLocker.release();
}
};
/*
Send GroupID and customerID every five minutes to services
*/
private class Send_save_status extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
}
#Override
protected Void doInBackground(Void... params) {
//Toast.makeText(getApplicationContext(), getApplicationContext().getString(R.string.gprs_adres) + address, Toast.LENGTH_LONG).show();
// make sure you close the gps after using it. Save user's battery power
//mGPSService.closeGPS();
StringBuilder str_url = new StringBuilder();
str_url.append("http://78.186.62.169:8090/TrackBinSvc.svc/saveStatus/");
Log.i("str_url1", "" + str_url);
str_url.append(device_id + "/");
Log.i("strl_url2", "" + str_url);
str_url.append(get_location + "/");
Log.i("strl_url3", "" + str_url);
str_url.append("opened" + "/");
Log.i("strl_url3", "" + str_url);
str_url.append(get_groupID + "/");
Log.i("strl_url3", "" + str_url);
str_url.append(get_customerID);
Log.i("strl_url3", "" + str_url);
String str = str_url.toString();
//"http://192.168.0.39:8090/TrackBinSvc.svc/Get_All_Mobile/admin/1234"
try {
jsonobject = JSONfunctions
.getJSONfromURL(str);
// Locate the array name in JSON
sonuc = jsonobject.getString("SendUpdateCordinatesResult");
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
}
}
}
Problem is: The broadcast receiver that you are registering is implemented on the Main thread. The broadcast receiver handler is ALWAYS EXECUTED ON THE MAIN THREAD, thus, making your entire process slower. To implement receiver's own thread, you can explicitly do so by providing it's own Handler thread.
Register your broadcast receiver like this:
HandlerThread receiverHandlerThread = new HandlerThread("threadName");
receiverHandlerThread.start();
Looper looper = receiverHandlerThread.getLooper();
Handler handler = new Handler(looper);
context.registerReceiver(mHandleMessageReceiver,newIntentFilter(DISPLAY_MESSAGE_ACTION),null,handler);
I am developing an application in android wrein I call a service that will upload a xml file to the server on click of a button.Problem is when I click the button first time it dosent get uploaded but when I click the button second time its gets uploaded...so let me know if there is any solution..pls help me.
Here is code below which extends service
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.IBinder;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;
public class Uploader extends Service
{
String info;
String phot_loc;
int category;
String phonenumber = null,profile_name=null,email_id=null;
double longi;
double latti;
Runnable runner;
//UIhandler to display the status of upload on response from server
Handler uiHandler = new Handler();
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
if(intent!=null)
{
info=intent.getStringExtra("info");
phot_loc=intent.getStringExtra("photo_loc");
category=intent.getIntExtra("category",0);
phonenumber=intent.getStringExtra("phone_number");
profile_name=intent.getStringExtra("profile_name");
email_id=intent.getStringExtra("email_id");
longi=intent.getDoubleExtra("longitude",0);
latti=intent.getDoubleExtra("latitude",0);
phonenumber=intent.getStringExtra("phone_number");
Log.d("UploadService","Indide upload Activity");
Thread t=new Thread(runner);
t.start();
}
//this will perform the uploading process
runner=new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
try
{
Log.d("UploadService","Indide upload Activity RIUNNER");
String xml = createXml();
RestClient client = new RestClient("http://3pixelart.com/complaint_process.php",xml);
//Log.d("UploadService", xml);
try {
client.Execute();
MyRunnable r = new MyRunnable("Complaint Uploaded Successfully");
uiHandler.post(r);
}
catch(Exception e)
{
Log.e("UploadService", "Exception in uploading :"+e.getMessage());
MyRunnable r = new MyRunnable("There was an error while registering complaint. Pls try again "+ e.getMessage());
uiHandler.post(r);
}
}
catch(Exception e)
{
Log.e("UploadService", "Exception:"+e.getMessage());
MyRunnable r=new MyRunnable("Error in uploading the complaint..");
uiHandler.post(r);
}
}
};
}
public String createXml() {
Log.d("UploadService","Indide upload Activity create xml 1");
Log.d("UploadService","Indide upload Activity create xml 2");
Date d = new Date();
//SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm a");
//String time = formatter.format(d);
Log.d("UploadService","Indide upload Activity create xml 3");
String imageData = getBase64ImageData();
SimpleDateFormat fileNameFormatter = new SimpleDateFormat("ddMMyyHHmm");
Log.d("UploadService","Indide upload Activity create xml 5");
String filename = "image"+fileNameFormatter.format(d)+".png";
String finaldata="<?xml version=\"1.0\"?>";
finaldata+="<ClientRequest><MobileNumber>"+phonenumber+"</MobileNumber><Longitude>";
finaldata+=longi+"</Longitude><Lattitude>"+latti+"</Lattitude>";
finaldata+="<Category>"+category+"</Category>";
finaldata+="<Profilename>"+profile_name+"</Profilename><Email>"+email_id+"</Email>";
finaldata+="<FileName>"+filename+"</FileName><Image>"+imageData+"</Image><Info>";
finaldata+=info+"</Info></ClientRequest>";
Log.d("UploadService","The DATA IS : "+finaldata);
return finaldata;
}
private String getBase64ImageData() {
// TODO Auto-generated method stub
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap bitmapOrg = BitmapFactory.decodeFile(phot_loc,options);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
String encodedImage = Base64.encodeToString(ba, Base64.DEFAULT);
//Log.d("UploadService", encodedImage);
bitmapOrg=null;
System.gc();
return encodedImage;
}
//this is used to display the status of uploading for this u require UIHandler
public class MyRunnable implements Runnable{
private String message=null;
public MyRunnable(String message) {
// TODO Auto-generated constructor stub
this.message=message;
}
public void run() {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
};
}
and this is my activity which strats that service
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class ComplaintActivity extends Activity implements OnClickListener
{
boolean pic_taken=false;
Button bpicture,bregister;
EditText description;
ImageView iv1;
int category=0;
private static final int TAKE_PICTURE = 1;
String Provider_name="";
Location currentLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_complaint);
bpicture=(Button) findViewById(R.id.button1);
bregister=(Button) findViewById(R.id.button2);
iv1=(ImageView) findViewById(R.id.taken_pic);
description=(EditText)findViewById(R.id.editText1);
bpicture.setOnClickListener(ComplaintActivity.this);
bregister.setOnClickListener(ComplaintActivity.this);
LocationManager manager=(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
List <String> l1=manager.getProviders(true);
if(l1.contains(LocationManager.GPS_PROVIDER))
{
Provider_name=LocationManager.GPS_PROVIDER;
}
if(l1.contains(LocationManager.NETWORK_PROVIDER))
{
Provider_name=LocationManager.NETWORK_PROVIDER;
}
currentLocation=manager.getLastKnownLocation(Provider_name);
Toast.makeText(ComplaintActivity.this, "GPS PROVIDERS "+Provider_name+"Lattti:"+currentLocation.getLatitude()+"Long:"+currentLocation.getLongitude(), Toast.LENGTH_LONG).show();
LocationListener listener=new MyLocationListener();
manager.requestLocationUpdates(Provider_name, 0, 0, listener);
}
class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
currentLocation=location;
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(arg0==bpicture)
take_picture();
if(arg0==bregister)
register_complaint();
}
private void take_picture() {
// TODO Auto-generated method stub
Intent int_cam=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri Outputfile=Uri.parse("file:///sdcard/temppic.jpg");
int_cam.putExtra(MediaStore.EXTRA_OUTPUT,Outputfile);
startActivityForResult(int_cam,TAKE_PICTURE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
//Log.d("BAKRA","INSIDE CAMEra Activity>>>>>>>>>>>");
if(requestCode==1)
{
//Log.d("BAKRA","INSIDE FIRST IF >>>>>>>>>>>");
if(resultCode==RESULT_OK)
{
// Log.d("BAKRA","INSIDE SECONG IF >>>>>>>>>>>");
if(data==null)
{
// Log.d("BAKRA","INSIDE THIRD IF >>>>>>>>>>>");
pic_taken=true;
BitmapFactory.Options opt=new BitmapFactory.Options();
opt.inSampleSize=8;
Bitmap bitorg=BitmapFactory.decodeFile("sdcard/temppic.jpg", opt);
// Log.d("BAKRA","INSIDE CAME>>>>>>>>>>>");
iv1.setImageBitmap(bitorg);
}
}
}
}
private void register_complaint() {
// TODO Auto-generated method stub
if(!pic_taken)
{
Toast.makeText(ComplaintActivity.this, "Please Take the Picture Related to the Query", Toast.LENGTH_LONG).show();
return;
}
if(description.getText().toString().equals(""))
{
Toast.makeText(ComplaintActivity.this, "Please Enter Details About the Complaint",Toast.LENGTH_LONG).show();
return;
}
else
{
Intent up=new Intent(ComplaintActivity.this,Uploader.class);
up.putExtra("category",getIntent().getIntExtra("Selected",1));
up.putExtra("info", description.getText().toString());
up.putExtra("photo_loc", "/sdcard/temppic.jpg");
up.putExtra("latitude", currentLocation.getLatitude());
up.putExtra("longitude", currentLocation.getLongitude());
SQLiteDatabase db=openOrCreateDatabase("LBA", MODE_PRIVATE, null);
Cursor c=db.rawQuery("select * from users", null);
String phonenumber = null,profile_name=null,email_id=null;
if(c.moveToFirst())
{
profile_name=c.getString(c.getColumnIndex("profilename"));
email_id=c.getString(c.getColumnIndex("emailid"));
phonenumber=c.getString(c.getColumnIndex("phonenumber"));
}
up.putExtra("phone_number", phonenumber);
up.putExtra("profile_name", profile_name);
up.putExtra("email_id", email_id);
startService(up);
Toast.makeText(ComplaintActivity.this, "Uploading to Server...",Toast.LENGTH_LONG).show();
finish();
}
}
}
onStartCommand intent:
This may be null if the service is being restarted after its process
has gone away, and it had previously returned anything except
START_STICKY_COMPATIBILITY.
http://developer.android.com/reference/android/app/Service.html
So try use:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
rather than finish();
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'm trying to send parameters string through putExtra function to the activity from the service, I have this code for my Server.java:
package com.winacro.andRHOME;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class Server extends Service{
IBinder mBinder = new LocalBinder();
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public class LocalBinder extends Binder {
public Server getServerInstance() {
return Server.this;
}
}
public void switchSpeaker(int hr, int min){
Toast.makeText(Server.this, hr +" , " +min, Toast.LENGTH_LONG).show();
String sendMessage = "1";
/* Intent myIntent = new Intent(Server.this, andRHOME.class);
myIntent.putExtra("sendMessage","1");
startActivity(myIntent);
PendingIntent pi = PendingIntent.getService(Server.this, 0, myIntent, 0);
AlarmManager almmgr = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar cldr = Calendar.getInstance();
int min1 = cldr.get(Calendar.MINUTE);
cldr.setTimeInMillis(System.currentTimeMillis());
cldr.add(Calendar.SECOND, 30);
almmgr.set(AlarmManager.RTC_WAKEUP, cldr.getTimeInMillis(), pi);*/
}
}
And This is the code for the Activity of whose sendMessage() method I want to access or pass in string variables too but My app is getting crashed, kindly help here!
package com.winacro.andRHOME;
import android.app.Activity;
import android.app.Application;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
/**
* This is the main Activity that displays the current chat session.
*/
public class andRHOME extends Activity {
// Debugging
private static final String TAG = "andRHOME";
private static final boolean D = true;
// Message types sent from the BluetoothChatService Handler
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
// Key names received from the BluetoothChatService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
private static final int REQUEST_ENABLE_BT = 3;
String inp;
// Layout Views
private TextView mTitle;
//private ListView mConversationView;
//private EditText mOutEditText;
//private Button mSendButton;
private ToggleButton TB1;
private ToggleButton TB2;
private ToggleButton TB3;
private ToggleButton TB4;
// Name of the connected device
private String mConnectedDeviceName = null;
// Array adapter for the conversation thread
private ArrayAdapter<String> mConversationArrayAdapter;
// String buffer for outgoing messages
public StringBuffer mOutStringBuffer;
// Local Bluetooth adapter
private BluetoothAdapter mBluetoothAdapter = null;
// Member object for the chat services
public BluetoothChatService mChatService = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(D) Log.e(TAG, "+++ ON CREATE +++");
// Set up the window layout
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
// Set up the custom title
mTitle = (TextView) findViewById(R.id.title_left_text);
mTitle.setText(R.string.app_name);
mTitle = (TextView) findViewById(R.id.title_right_text);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
Bundle bundle = getIntent().getExtras();
inp = bundle.getString("sendMessage");
sendMessage(inp);
}
#Override
public void onStart() {
super.onStart();
if(D) Log.e(TAG, "++ ON START ++");
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
} else {
if (mChatService == null) setupChat();
}
}
#Override
public synchronized void onResume() {
super.onResume();
if(D) Log.e(TAG, "+ ON RESUME +");
// Performing this check in onResume() covers the case in which BT was
// not enabled during onStart(), so we were paused to enable it...
// onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
if (mChatService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
// Start the Bluetooth chat services
mChatService.start();
}
}
}
private void setupChat() {
Log.d(TAG, "setupChat()");
// Initialize the array adapter for the conversation thread
mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
//mConversationView = (ListView) findViewById(R.id.in);
// mConversationView.setAdapter(mConversationArrayAdapter);
// Initialize the compose field with a listener for the return key
//mOutEditText = (EditText) findViewById(R.id.edit_text_out);
// mOutEditText.setOnEditorActionListener(mWriteListener);
// Initialize the send button with a listener that for click events
//mSendButton = (Button) findViewById(R.id.button_send);
/*mSendButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
//TextView view = (TextView) findViewById(R.id.edit_text_out);
String message = "0";
sendMessage(message);
}
});*/
TB1 = (ToggleButton) findViewById(R.id.toggleButton1);
TB1.setOnClickListener(new OnClickListener() {
public void onClick(View v){
if (TB1.isChecked()){
String message = "1";
sendMessage(message);
} else if (!TB1.isChecked()){
String message = "6";
sendMessage(message);
}
}
});
TB2 = (ToggleButton) findViewById(R.id.ToggleButton01);
TB2.setOnClickListener(new OnClickListener() {
public void onClick(View v){
if (TB2.isChecked()){
String message = "0";
sendMessage(message);
} else if (!TB2.isChecked()){
String message = "5";
sendMessage(message);
}
}
});
TB3 = (ToggleButton) findViewById(R.id.ToggleButton02);
TB3.setOnClickListener(new OnClickListener() {
public void onClick(View v){
if (TB3.isChecked()){
String message = "2";
sendMessage(message);
} else if (!TB3.isChecked()){
String message = "7";
sendMessage(message);
}
}
});
TB4 = (ToggleButton) findViewById(R.id.ToggleButton03);
TB4.setOnClickListener(new OnClickListener() {
public void onClick(View v){
if (TB4.isChecked()){
String message = "3";
sendMessage(message);
} else if (!TB4.isChecked()){
String message = "8";
sendMessage(message);
}
}
});
// Initialize the BluetoothChatService to perform bluetooth connections
mChatService = new BluetoothChatService(this, mHandler);
// Initialize the buffer for outgoing messages
mOutStringBuffer = new StringBuffer("");
}
#Override
public synchronized void onPause() {
super.onPause();
if(D) Log.e(TAG, "- ON PAUSE -");
}
#Override
public void onStop() {
super.onStop();
if(D) Log.e(TAG, "-- ON STOP --");
}
#Override
public void onDestroy() {
super.onDestroy();
// Stop the Bluetooth chat services
if (mChatService != null) mChatService.stop();
if(D) Log.e(TAG, "--- ON DESTROY ---");
}
private void ensureDiscoverable() {
if(D) Log.d(TAG, "ensure discoverable");
if (mBluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
/**
* Sends a message.
* #param message A string of text to send.
*/
private void sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
// Check that there's actually something to send
if (message.length() > 0) {
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
mChatService.write(send);
// Reset out string buffer to zero and clear the edit text field
mOutStringBuffer.setLength(0);
//mOutEditText.setText(mOutStringBuffer);
}
}
// The action listener for the EditText widget, to listen for the return key
private TextView.OnEditorActionListener mWriteListener =
new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
// If the action is a key-up event on the return key, send the message
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
String message = view.getText().toString();
sendMessage(message);
}
if(D) Log.i(TAG, "END onEditorAction");
return true;
}
};
// The Handler that gets information back from the BluetoothChatService
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
mTitle.setText(R.string.title_connected_to);
mTitle.append(mConnectedDeviceName);
mConversationArrayAdapter.clear();
break;
case BluetoothChatService.STATE_CONNECTING:
mTitle.setText(R.string.title_connecting);
break;
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
mTitle.setText(R.string.title_not_connected);
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
String writeMessage = new String(writeBuf);
mConversationArrayAdapter.add("Me: " + writeMessage);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
mConversationArrayAdapter.add(mConnectedDeviceName+": " + readMessage);
break;
case MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(), "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
Toast.LENGTH_SHORT).show();
break;
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(D) Log.d(TAG, "onActivityResult " + resultCode);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, true);
}
break;
case REQUEST_CONNECT_DEVICE_INSECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, false);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a chat session
setupChat();
} else {
// User did not enable Bluetooth or an error occured
Log.d(TAG, "BT not enabled");
Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void connectDevice(Intent data, boolean secure) {
// Get the device MAC address
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BLuetoothDevice object
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
// Attempt to connect to the device
mChatService.connect(device, secure);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent serverIntent = null;
switch (item.getItemId()) {
case R.id.scan:
// Launch the DeviceListActivity to see devices and do scan
serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
return true;
case R.id.timer:
// Launch the DeviceListActivity to see devices and do scan
Intent myIntent = new Intent("com.winacro.andRHOME.Timer");
startActivity(myIntent);
return true;
/*case R.id.discoverable:
// Ensure this device is discoverable by others
ensureDiscoverable();
return true;*/
}
return false;
}
}
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