.getStringExtra returning null value instead String - android

Getting value in putExtra But cant retrieve in getStringExtra.
public class StartNotificationReceiver extends BroadcastReceiver{
private void sendTodayNotification() {
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date todateDate = new Date();
String TodayDate_String = dateFormat.format(todateDate);
String Val=AppSettingsPref.getStringValue(context, AppSettingsPref.KEY_TODAY_DATE_AND_TIME, "");
if(!Val.equals(TodayDate_String))
{
AppSettingsPref.saveString(context, AppSettingsPref.KEY_TODAY_DATE_AND_TIME, TodayDate_String);
final HGDate englishDate = new HGDate(context);
englishDate.setGregorian(Calendar.YEAR, Calendar.MONTH + 1, 1);
final HGDate islamicDateToday = new HGDate(englishDate);
islamicDateToday.toHigri();
int islamicDayToday = islamicDateToday.getDay();
int islamicMonthToday = islamicDateToday.getMonth();
String otherMonth = Dates.islamicMonthName(context, islamicDateToday.getMonth() - 1);
int adjustedDate = AppSettingsPref.getIntValue(context, AppSettingsPref.CURRENT_ADJUSTMENT_KEY, 0);
String todayDateTimeinhijri = islamicDateToday.getDay() + (adjustedDate) + " "
+ otherMonth + " " + islamicDateToday.getYear();
Intent intent = new Intent(context,NotificationReceiver.class);
-------->intent.putExtra("todayDateTimeinhijri", todayDateTimeinhijri.toString());<-----------
databaseAccess = DatabaseAccess.getInstance(context);
databaseAccess.open();
ArrayList<Event> events = databaseAccess.showEventsByMuslimType(muslimType);
for (int i = 0; i < events.size(); i++) {
Event event = events.get(i);
String[] date = event.getHejriDate().split("-");
int islamicDayOfEvent = Integer.parseInt(date[0].trim());
int islamicMonthOfEvent = Integer.parseInt(date[1].trim());
boolean isViladat = event.isVilaadat;
if (islamicDayToday == islamicDayOfEvent && islamicMonthToday == islamicMonthOfEvent) {
makeNotification(event);
}
}
}
intent.putExtra("todayDateTimeinhijri", todayDateTimeinhijri.toString());
This is where .getStringExtra is getting null value
public class NotificationReceiver extends BroadcastReceiver{
public void onReceive(Context context, Intent intent) {
this.context = context;
}
todayDateTime2 = intent.getStringExtra("todayDateTimeinhijri");
}
The extra code is removed for better understanding
Thanks in advance
Help will be appreciated.
cant find solution.

Where do you send (or start) the intent with the parameter "todayDateTimeinhijri"?
If you don't send the intent the NotificationReceiver isn't able to receive anything.
//example activity using receiver and send intent via broadcast ( sendBroadcast(intent) )
public class Example extends AppCompatActivity {
private NotificationReceiver mNotificationReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNotificationReceiver = new NotificationReceiver();
IntentFilter intentFilter = new IntentFilter("your_action");
registerReceiver(mNotificationReceiver, intentFilter);
StartNotificationReceiver mStartNotificationReceiver = new StartNotificationReceiver(getApplicationContext());
mStartNotificationReceiver.sendTodayNotification();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mNotificationReceiver != null) {
unregisterReceiver(mNotificationReceiver);
}
}
private class NotificationReceiver extends BroadcastReceiver {
Context context;
#Override
public void onReceive(Context context, Intent intent) {
this.context = context;
String action = intent.getAction();// should be "your_action"
String todayDateTime2 = intent.getStringExtra("todayDateTimeinhijri");
Log.i("NotificationReceiver","action: " + action );
Log.i("NotificationReceiver","dateTime: " + todayDateTime2 );
}
}
public class StartNotificationReceiver {
private Context context;
public StartNotificationReceiver(Context ctx){
this.context = ctx;
}
public void sendTodayNotification() {
Intent intent = new Intent("your_action");
intent.putExtra("todayDateTimeinhijri", "your String value");
context.sendBroadcast(intent);
}
}
}

Putting the extra in the intent does not send it. There sould be a sendBroadcast() call or similar somewhere.

Related

Send service result to activity

I've got a BroadcastReceiver which checks if Internet connection is available then it starts a service which retrieves an ArrayList from the DB:
public class NetworkWatcher extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
Intent retrieveVehicleList = new Intent(context, RetrieveVehicleListService.class);
if (info != null)
{
if (info.isConnected())
{
context.startService(retrieveVehicleList);
}
else
{
context.stopService(retrieveVehicleList);
}
}
}
}
public class RetrieveVehicleListService extends IntentService
{
private static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
private NotificationCompat.Builder builder;
private ArrayList<Vehicle> vehicles;
private void parseVehiclesFromMap(ArrayList vehicles)
{
for (int i = 0; i < vehicles.size(); i++)
{
final Vehicle v = new Vehicle();
HashMap vehicleMap = (HashMap) vehicles.get(i);
v.setPlate(vehicleMap.get("plate").toString());
v.setKm(vehicleMap.get("km") == null ? null : Integer.parseInt(vehicleMap.get("km").toString()));
v.setFuelQuantity(Double.parseDouble(vehicleMap.get("fuel_quantity").toString()));
v.setEffectiveFuelEconomy(Double.parseDouble(vehicleMap.get("fuel_economy").toString()));
v.setInsuranceDate(vehicleMap.get("insurance_date") == null ? null : new LocalDate(vehicleMap.get("insurance_date").toString()));
v.setMatriculationDate(new LocalDate(vehicleMap.get("matriculation_date").toString()));
v.setLatitude(vehicleMap.get("latitude") == null ? null : Double.parseDouble(vehicleMap.get("latitude").toString()));
v.setLongitude(vehicleMap.get("longitude") == null ? null : Double.parseDouble(vehicleMap.get("longitude").toString()));
v.setFuelType(FuelType.fromInt(Integer.parseInt(vehicleMap.get("id_fuel").toString())));
this.vehicles.add(v);
}
}
private void sendRequest(int userID)
{
Response.Listener<String> listener = new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
try
{
HashMap json = new ObjectMapper().readValue(response, HashMap.class);
String errorCode = json.get("error_code").toString();
switch (errorCode)
{
case "0":
parseVehiclesFromMap((ArrayList) json.get("vehicles"));
break;
default:
// TODO gestire
break;
}
}
catch (IOException e)
{
// TODO gestire
e.printStackTrace();
}
}
};
VehicleListRequest request = new VehicleListRequest(String.valueOf(userID), listener, null);
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);
}
#Override
protected void onHandleIntent(Intent intent)
{
SharedPreferences sp = getSharedPreferences(getString(clyky.cartracker.R.string.sharedPreferencesName), Context.MODE_PRIVATE);
int userID = sp.getInt("id_user", SplashActivity.DEFAULT_USER_ID);
if (userID != SplashActivity.DEFAULT_USER_ID)
{
sendRequest(userID);
}
}
public RetrieveVehicleListService()
{
super("RetrieveVehicleList");
vehicles = new ArrayList<>();
}
}
I want my MainActivity gets that ArrayList from RetrieveVehicleListService when the activity is started. How could I do that?
Thanks in advance.
Use LocalBroadcast reciever to send data from service to activity. Add following code to your activty
private BroadcastReceiver BReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
//put here whaterver you want your activity to do with the intent received
ArrayList<String> arrayList=intent.getStringArrayListExtra("arrayList");
}
};
protected void onResume(){
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(bReceiver, new IntentFilter("message"));
}
protected void onPause (){
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(bReceiver);
}
and use following method to send broadcast from service
private void sendBroadcast (boolean success){
Intent intent = new Intent ("message"); //put the same message as in the filter you used in the activity when registering the receiver
intent.putExtra("success", success);
intent.putStringArrayListExtra("arrayList", arrayList);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
Use Local Broadcast Receiver :
send broadcast using below code
Intent intent = new Intent("YourAction");
Bundle bundle = new Bundle();
bundle .putSerializable("ARRAYLIST",(Serializable)vehicles);
intent.putExtra("BUNDLE",bundle);
intent.putExtras(intent)
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
And receive broadcast in your activity:
private MyBroadcastReceiver myReceiver;
#Override
public void onResume(){
myReceiver = new MyReceiver();
final IntentFilter intentFilter = new IntentFilter("YourAction");
LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, intentFilter);
}
#Override
public void onPause(){
if(myReceiver != null)
LocalBroadcastManager.getInstance(this).unregisterReceiver(myReceiver);
myReceiver = null;
}
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Here you have the received broadcast
// And if you added extras to the intent get them here too
// this needs some null checks
Intent intent = getIntent();
Bundle args = intent.getBundleExtra("BUNDLE");
ArrayList<Object> object = (ArrayList<Object>)args.getSerializable("ARRAYLIST");
}
}

android not receiving broadcast

i my app i am sending an broadcast from the onTaskRemoved() method of a service. But i am not getting the broadcast in the broadcastReciever. This is my code
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Log.e("TaskRemoved","TaskRemoved");
commonSessionManager.setConnected(false);
broadCastUpdate(GymMainActivity.APP_REMOVED_FROM_RECENTS);
}
public void broadCastUpdate(String action){
Intent intent=new Intent();
intent.putExtra(GymMainActivity.APP_REMOVED_FROM_RECENTS,action);
sendBroadcast(intent);
}
private BroadcastReceiver mGattUpdateReciever = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (WRONG_DATA.equalsIgnoreCase(action)) {
Toast.makeText(GymMainActivity.this, "Please measure your vitals again", Toast.LENGTH_SHORT).show();
isFalseDataSent = true;
}
if (ACTION_GATT_CONNECTED.equalsIgnoreCase(action)) {
Toast.makeText(GymMainActivity.this, "connected", Toast.LENGTH_SHORT).show();
runOnUiThread(new Runnable() {
#Override
public void run() {
if (!isFinishing()) {
ShowConnectDialog();
}
}
});
} else if (ACTION_GATT_DISCONNECTED.equalsIgnoreCase(action)) {
Toast.makeText(GymMainActivity.this, "disconnected", Toast.LENGTH_SHORT).show();
} else if (ACTION_DATA_AVAILABLE.equalsIgnoreCase(action)) {
connectDialog.dismiss();
String[] result = intent.getStringArrayExtra(EXTRA_DATA);
for (int i = 0; i < result.length; i++) {
Log.e("result " + i, result[i]);
}
Log.e("isDisplayed", isDisplayed + "");
if (!isDisplayed) {
if (isFalseDataSent) {
mBluetoothController.powerOff();
isFalseDataSent = false;
}
commonSessionManager.setConnected(true);
Intent vitalDataIntent = new Intent(GymMainActivity.this, GymVitalDisplayActivity.class);
vitalDataIntent.putExtra("userDataBundle",userDataBundle());
vitalDataIntent.putExtra("vitalData", result);
startActivity(vitalDataIntent);
finish();
isDisplayed = true;
}
}
if(action.equalsIgnoreCase(APP_REMOVED_FROM_RECENTS)){
Toast.makeText(GymMainActivity.this,"APP_REMOVED_FROM_RECENTS",Toast.LENGTH_SHORT).show();
btnScan.setVisibility(View.VISIBLE);
if(btnConnect.getVisibility()==View.VISIBLE){
btnConnect.setVisibility(View.GONE);
}
if(txtConnected.getVisibility()==View.VISIBLE){
txtConnected.setVisibility(View.GONE);
}
}
}
};
private static IntentFilter makeGattUpdateIntentFilter() {
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ACTION_GATT_CONNECTED);
intentFilter.addAction(ACTION_GATT_DISCONNECTED);
intentFilter.addAction(ACTION_DATA_AVAILABLE);
intentFilter.addAction(WRONG_DATA);
intentFilter.addAction(APP_REMOVED_FROM_RECENTS);
return intentFilter;
}
public final static String ACTION_GATT_CONNECTED =
"com.example.demo.le.ACTION_GATT_CONNECTED";
public final static String ACTION_GATT_DISCONNECTED =
"com.example.demo.le.ACTION_GATT_DISCONNECTED";
public final static String ACTION_DATA_AVAILABLE =
"com.example.demo.le.ACTION_DATA_AVAILABLE";
public final static String EXTRA_DATA =
"com.example.demo.le.EXTRA_DATA";
public final static String WRONG_DATA =
"com.example.demo.le.WRONG_DATA";
public final static String APP_REMOVED_FROM_RECENTS="com.example.demo.le.APP_REMOVED_FROM_RECENTS";
i am receiving all the broadcast except APP_REMOVED_FROM_RECENTS.
It may be because you're not setting the action on the intent but as an extra. Change your code to that and see if it works:
public void broadCastUpdate(String action){
Intent intent=new Intent(action);
sendBroadcast(intent);
}

How can I call a Method of an activity from background service?

I want to update my ChatMessageAdapter by received new data from background service so that I want to call UpdateAdapter method from background to update adapter.
here is my ServiceClass:
public class MyService extends Service{
private String loginUserInfoId;
SessionManager session;
DatabaseHelper db;
MessageListActivity mLA;
long totalSize = 0;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
db = new DatabaseHelper(getApplicationContext());
mLA = new MessageListActivity();
session = new SessionManager(getApplicationContext());
session.checkLogin();
HashMap<String, String> user = session.getUserDetails();
loginUserInfoId = user.get(SessionManager.KEY_USER_INFO_ID);
if(isInternetOn()) {
new syncMessageFromServer().execute();
new SyncPendingMessageToServer();
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
private class syncMessageFromServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
//progressBar.setProgress(0);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String str = "";
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://192.168.1.2/AndroidApp/GetAllMessage/" + loginUserInfoId);
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
JSONArray jArray = new JSONArray(str);
for (int i = 0; i <= jArray.length() - 1; i++) {
JSONObject row = jArray.getJSONObject(i);
ChatMessage cm = new ChatMessage();
String offlineFileURL = "";
/******* Firstly take data in model object ******/
cm.setOriginalMsgThreadId(row.getString("MessageThreadId"));
cm.setSenderUserInfoId(row.getString("SenderUserId")); cm.setReceiverUserInfoId(row.getString("MultipleReceiversId"));
cm.setMessageStatus("SENT");
cm.setIsPending(0);
cm.setMessageText(row.getString("MessageText"));
cm.setMediaURL(offlineFileURL);
cm.setThumbImage(offlineFileURL);
cm.setMediaMIMEType("");
cm.setMediaSize(0);
cm.setMediaName("");
cm.setLatitude("");
cm.setLongitude("");
cm.setSendTimeStamp(row.getString("SendTime"));
cm.setReceiveTimeStamp(row.getString("ReadTime"));
mLA.UpdateAdapter(ChatMessage cm);
long messageThreadId = db.SendMessage(cm);
}
} catch (JSONException e) {
e.printStackTrace();
}
return str;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(isInternetOn()) {
new syncMessageFromServer().execute();
}
}
}
}
and this is my MessageActivityList Class:
public class MessageListActivity extends ActionBarActivity {
private String receiverUserInfoId;
private String loginUserInfoId;
private String orgMsgThreadId;
private String userName;
private String uploadedFileURL = "";
DatabaseHelper db;
SessionManager session;
private ChatMessageAdapter chatMessageAdapter;
private EditText chatText;
private ImageButton buttonSend;
private ListView listView;
private static final String TAG = MessageListActivity.class.getSimpleName();
// Camera activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private Uri fileUri; // file url to store image/video
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message_list);
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll()
.penaltyLog()
.build());
db = new DatabaseHelper(getApplicationContext());
session = new SessionManager(getApplicationContext());
session.checkLogin();
HashMap<String, String> user = session.getUserDetails();
loginUserInfoId = user.get(SessionManager.KEY_USER_INFO_ID);
Intent intent=getIntent();
Bundle extra = intent.getExtras();
receiverUserInfoId=extra.getString("UserInfoId");
orgMsgThreadId = extra.getString("OrgMessageThreadId");
userName=extra.getString("UserName");
setTitle(userName);
listView = (ListView) findViewById(R.id.messageList);
chatMessageAdapter = new ChatMessageAdapter(getApplicationContext(), R.layout.activity_single_message);
listView.setAdapter(chatMessageAdapter);
buttonSend = (ImageButton) findViewById(R.id.buttonSend);
chatText = (EditText) findViewById(R.id.chatText);
chatText.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
if(chatText.getText().toString().trim().length() > 0){
sendChatMessage();
}
}
return false;
}
});
buttonSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
sendChatMessage();
}
});
listView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
// listView.setAdapter(chatMessageAdapter);
//to scroll the list view to bottom on data change
chatMessageAdapter.registerDataSetObserver(new DataSetObserver() {
#Override
public void onChanged() {
super.onChanged();
listView.setSelection(chatMessageAdapter.getCount() - 1);
}
});
setListData();
}
public void UpdateAdapter(ChatMessage cm) {
chatMessageAdapter.add(cm);
}
}
What to do for calling this UpdateAdapter method to update my ChatMessage received by the server?
You should be using a LocalBroadcastReceiver.
Register for receiving the updates in onResume and unregister in onPause.
U can use Broadcast receiver for updating the UI from service.
Register the broadcast receiver in onCreate() of ur Activity:
private UpdateReceiver updateReceiver;
if (UpdateReceiver == null)
{
updateReceiver = new UpdateReceiver();
IntentFilter intentFilter = new
IntentFilter("REFRESH_DATA");
registerReceiver(updateReceiver, intentFilter);
}
Unregister in onDestroy() of ur Activity
if (updateReceiver != null) unregisterReceiver(updateReceiver);
Define the Broadcast receiver in ur Activity :
private class UpdateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("REFRESH_DATA")) {
//update adapter from here
}
}
}
In ur service in which situation u want to update the adapter, there call sendBroadcast. Like:
Intent intent=new Intent("REFRESH_DATA");
//u can pass the data through putExtras
sendBroadcast(intent);
use Broadcast receiver for updating the UI from service and register the broadcast receiver in onCreate() of ur MainActivity where you want to recieve
code will like below
private UpdateReceiver updateReceiver;
if (UpdateReceiver == null)
{
updateReceiver = new UpdateReceiver();
IntentFilter intentFilter = new
IntentFilter("REFRESH_DATA");
registerReceiver(updateReceiver, intentFilter);
}
and create class to check update is recieved or not
private class UpdateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("REFRESH_DATA")) {
//update adapter from here
}
}
}
register a BroadcastReceiver inside your activity. call that method in onReceive method of this receiver. and from your Service sendBroadcast to this receiver, remember to add the required data to your intent and fetch data from onReceive method intent.

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" />

Notifications not Showing up in Android while using Tabs

I am writing an app in which i am using two tabs, one to get list of facebook friends and second tab to get list of phonebook friends
And In Phonebook friends tab i am also getting friends birthdays and also showing reminder for that, and i am able to get reminder as well if i will try it alone, without combined to another Tab (i.e.: with Facebook Tab)
It means once i combined it in Tabs, then i am not getting any birthday Notifications.
I am using below class to get Notifications for Phonebook friends birthdays:
public class BirthdayReminder extends ListActivity {
// TODO: call/write message on birthday
// TODO: hideNotificationPref
private final DateFormatSymbols dateSymbols = new DateFormatSymbols();
private Database db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getListView().setFastScrollEnabled(true);
this.db = new Database(getContentResolver());
// debug code
// Debug.logDatabase(this);
// start BirthdayBroadcastReceiver if it is activated
Preferences prefs = Preferences.getInstance(getApplicationContext());
if (prefs.getActivateService()) {
BirthdayBroadcastReceiver.restart(getApplicationContext());
}
}
#Override
protected void onResume() {
super.onResume();
updateView();
}
private void updateView() {
// create new list adapter
MultiListAdapter listAdapter = new MultiListAdapter();
List<ListAdapter> adapterList = listAdapter.getListAdapters();
// load birthday and contact information
List<Contact> contacts = this.db.getAllContacts();
List<BirthContact> birthContacts = BirthContactHelper.createBirthContactList(contacts);
// group all contacts by known and unknown birthday
SortedSet<BirthContact> knownBirthdays = new TreeSet<BirthContact>(new BirthContactBirthdayComparator());
SortedSet<BirthContact> unknownBirthdays = new TreeSet<BirthContact>(new BirthContactNameComparator());
for (BirthContact birthContact : birthContacts) {
DateOfBirth dateOfBirth = birthContact.getDateOfBirth();
if (dateOfBirth != null) {
knownBirthdays.add(birthContact);
} else {
unknownBirthdays.add(birthContact);
}
}
Integer currentMonth = null;
BirthContactAdapter currentBirthContactAdapter = null;
String[] monthStrs = this.dateSymbols.getMonths();
for (BirthContact birthContact : knownBirthdays) {
int month = birthContact.getDateOfBirth().getDate().get(Calendar.MONTH);
if (currentMonth == null || currentMonth != month) {
currentMonth = month;
currentBirthContactAdapter = new BirthContactAdapter(this);
adapterList.add(new CategoryAdapter(this, monthStrs[currentMonth]));
adapterList.add(currentBirthContactAdapter);
}
currentBirthContactAdapter.add(birthContact);
}
adapterList.add(new CategoryAdapter(this, getResources().getString(R.string.unknownBirthdays)));
adapterList.add(new BirthContactAdapter(this, unknownBirthdays));
setListAdapter(listAdapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
BirthContact birthContact = (BirthContact) l.getAdapter().getItem(position);
Intent editorIntent = new Intent(this, BirthdayEditor.class);
editorIntent.putExtra(BirthdayEditor.CONTACT_ID, birthContact.getContact().getId());
startActivity(editorIntent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.layout.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.preferences:
startActivity(new Intent(this, PreferenceWindow.class));
return true;
case R.id.quit:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
I am using below code to call two different classes while click on a particular tab.
but whenever i change it to tab, i am not getting any notification, TabSample.java:
public class TabSample extends TabActivity {
String response;
#SuppressWarnings("unused")
private static JSONArray jsonArray;
public static TabHost mTabHost;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bundle extras = getIntent().getExtras();
if (extras == null) {
return;
}
response = getIntent().getStringExtra("FRIENDS");
try {
jsonArray = new JSONArray(response);
} catch (JSONException e) {
FacebookUtility.displayMessageBox(this,
this.getString(R.string.json_failed));
}
setTabs();
}
private void setTabs() {
addTab("", R.drawable.tab_menu, com.chr.tatu.sample.friendslist.facebook.FriendsList.class);
addTab("", R.drawable.tab_contact, com.chr.tatu.sample.friendslist.contacts.BirthdayReminder.class);
}
Notification:
public class BirthdayBroadcastReceiver extends BroadcastReceiver {
private static final String TIMED = "timed";
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getBooleanExtra(TIMED, false)) {
notifyBirthdays(context);
}
start(context);
}
private static PendingIntent createPendingIntent(Context context) {
Intent intent = new Intent(context, BirthdayBroadcastReceiver.class);
intent.putExtra(TIMED, true);
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
public static void start(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = createPendingIntent(context);
Preferences prefs = Preferences.getInstance(context);
Time nextUpdateTime = prefs.getUpdateTime();
Calendar wakeUpCal = Calendar.getInstance();
wakeUpCal.set(Calendar.HOUR_OF_DAY, nextUpdateTime.getHours());
wakeUpCal.set(Calendar.MINUTE, nextUpdateTime.getMinutes());
wakeUpCal.set(Calendar.SECOND, wakeUpCal.getActualMinimum(Calendar.SECOND));
wakeUpCal.set(Calendar.MILLISECOND, wakeUpCal.getActualMinimum(Calendar.MILLISECOND));
if (wakeUpCal.before(Calendar.getInstance())) {
wakeUpCal.add(Calendar.DAY_OF_MONTH, 1);
}
alarmManager.set(AlarmManager.RTC_WAKEUP, wakeUpCal.getTimeInMillis(), pendingIntent);
}
public static void stop(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = createPendingIntent(context);
alarmManager.cancel(pendingIntent);
pendingIntent.cancel();
}
public static void restart(Context context) {
stop(context);
start(context);
}
private void notifyBirthdays(Context context) {
Calendar today = CalendarUtils.todaysCalendar();
Database db = new Database(context.getContentResolver());
Preferences prefs = Preferences.getInstance(context);
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Resources res = context.getResources();
List<Contact> contacts = db.getAllContacts();
// calculate next birthdays
SortedMap<Integer, List<String>> nextBirthdays = new TreeMap<Integer, List<String>>();
for (Contact contact : contacts) {
Integer timeSpanToNextBirthday = null;
for (RawContact rawContact : contact.getRawContacts()) {
for (DateOfBirth dateOfBirth : rawContact.getDatesOfBirth()) {
int timeSpan = CalendarUtils.timeSpanToNextBirthday(today, dateOfBirth.getDate());
if (timeSpanToNextBirthday == null || timeSpanToNextBirthday > timeSpan) {
timeSpanToNextBirthday = timeSpan;
}
}
}
if (timeSpanToNextBirthday != null && timeSpanToNextBirthday <= prefs.getDaysBeforeReminder()) {
List<String> infoNames = nextBirthdays.get(timeSpanToNextBirthday);
if (infoNames == null) {
infoNames = new ArrayList<String>();
nextBirthdays.put(timeSpanToNextBirthday, infoNames);
}
infoNames.add(contact.getName());
}
}
// collect all sentences for the notification
List<String> notificationTexts = new ArrayList<String>();
int countBirthdays = 0;
for (Integer days : nextBirthdays.keySet()) {
List<String> birthdayList = nextBirthdays.get(days);
String names = StringUtils.join(birthdayList, ", ").toString();
notificationTexts.add(getBirthdayText(res, days, names));
countBirthdays += birthdayList.size();
}
// cancel all notifications (clear old once)
notificationManager.cancelAll();
// create new notification
if (notificationTexts.size() > 0) {
String titleText = String.format(res.getQuantityString(R.plurals.notificationTitle, countBirthdays),
countBirthdays);
Intent intent = new Intent(context, BirthdayReminder.class);
Notification notification = new Notification(R.drawable.balloons2, titleText, System.currentTimeMillis());
if (countBirthdays > 1) {
notification.number = countBirthdays;
}
PendingIntent pi = PendingIntent.getActivity(context, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
notification.setLatestEventInfo(context, titleText, StringUtils.join(notificationTexts, ", "), pi);
notificationManager.notify(0, notification);
}
}
private String getBirthdayText(Resources res, int days, String names) {
String text;
switch (days) {
case 0:
text = String.format(res.getString(R.string.notificationText_today), names);
break;
case 1:
text = String.format(res.getString(R.string.notificationText_tomorrow), names);
break;
default:
text = String.format(res.getString(R.string.notificationText_other), days, names);
}
return text;
}
}
Are you using correct package name with Notifications Service class, like i have made same type of project few months ago and i was struggling at same movement and when i got my mistake that was just silly:
It is the correct way:
<receiver android:name="packagename.BirthdayBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>

Categories

Resources