Here there is an activity called groupchat. Here I am having the static object activeEventMO.
In this groupchat activity the chatting function is going on. If user1 send a message to user2 that message received by gcmIntent class. in this gcmIntent class I have added the code for notification. Here if user1 send a message for a particular event notification received for user2. If user2 clicks that notification it will take to the user to that chat window that means groupchat activity.
for that in gcmIntent class I used parcelable to send the eventMO to groupchat activity. if user1 send a message to user2 for event2 user2 receives a notification. if user2 clciks the notification it show the chatwindow of event1. because when first time I send the eventid1 by sing eventMO. So it holds the eventid1 forever. it cannot refreshed.
This is my groupchat activity code
public class GroupChatActivity extends Activity {
private static ListView listViewMessages;
private static List<ChatMO> listChatMessageObjectses = new ArrayList<ChatMO>();
private static MessagesListAdapter adapter;
private static Handler UIHandler;
private static int RESULT_LOAD_IMAGE = 1;
private EditText inputMsg;
private String formatDate;
private Context context;
private String dateResult;
private static EventMO activeEventMO = null;
private UserDelegate userDelegate = new UserDelegate();
private MediaDelegates mediaDelegates = new MediaDelegates();
private MessageDelegates messageDelegates = new MessageDelegates();
private SharedPreferences sharedpreferences;
private List<UserMO> eventUserMOs = new ArrayList<>();
private Gson gson = new Gson();
private UserMO userMO = new UserMO();
private MessageMO messageMO = new MessageMO();
private File imgFile;
private MediaMO mediaMO = new MediaMO();
// this method is for store the current event id to eventMO coz eventMO globally declared as static
public void getevent()
{
activeEventMO = (EventMO) getIntent().getParcelableExtra("eventMo");
}
public static void messageHandler(final MessageMO messageMo) {
UIHandler = new Handler(Looper.getMainLooper());
UIHandler.post(new Runnable() {
public void run() {
Log.e("messageHandler", messageMo.getEventTitle());
ChatMO chatMO = new ChatMO();
chatMO.setMessage(messageMo.getMessage());
chatMO.setSelf(0);
chatMO.setFromName(messageMo.getfromUserName());
chatMO.setDate(messageMo.getDate());
Log.e("handler", "eventMO" + activeEventMO);
Log.e("handler", "messageMO" + messageMo);
if (activeEventMO.getEventId() == messageMo.getEventId()) {
listChatMessageObjectses.add(chatMO);
listViewMessages.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
});
}
#Override
protected void onStart() {
super.onStart();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("APPSTATUS", 1);
editor.putLong("eventId", activeEventMO.getEventId());
editor.commit();
Log.i("App", "start");
AppActivityStatus.setActivityStarted();
AppActivityStatus.setActivityContext(context);
}
#Override
protected void onPause() {
super.onPause();
AppActivityStatus.setActivityStoped();
}
#Override
protected void onResume() {
super.onPause();
AppActivityStatus.setActivityStarted();
}
#Override
protected void onStop() {
super.onStop();
Log.i("App", "stop");
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("APPSTATUS", 2);
editor.commit();
AppActivityStatus.setActivityStoped();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.image_upload, menu);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ChatMO chatMO = new ChatMO();
chatMO.setMessage_type(Constants.IS_TYPE_CHAT_IMAGE);
chatMO.setMessage(picturePath);
chatMO.setSelf(1);
chatMO.setIs_delete(0);
chatMO.setFromName("");
chatMO.setEvent_id(activeEventMO.getEventId());
messageMO.setMessage("");
messageMO.setRingeeUserId(userMO.getRingeeUserId());
// messageMO.setDate(messageMO.getDate());
messageMO.setMobileNumber(userMO.getMobileNumber());
messageMO.setEventId(activeEventMO.getEventId());
messageMO.setEventTitle(activeEventMO.getText());
Log.e("sendbutton", "eventtitle" + messageMO.getEventTitle());
messageMO.setfromUserName(userMO.getUserName());
messageMO.setMessageType(Constants.MESSAGE_TYPE_MSG);
mediaMO.setRingeeUserId(userMO.getRingeeUserId());
mediaMO.setIsType(Constants.IS_TYPE_CHAT_IMAGE);
imgFile = new File(picturePath);
listChatMessageObjectses.add(chatMO);
listViewMessages.setAdapter(adapter);
adapter.notifyDataSetChanged();
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... arg0) {
return mediaDelegates.insertChatFile(context, imgFile, messageMO, eventUserMOs, mediaMO);
}
#Override
protected void onPostExecute(String mediaBo) {
Toast.makeText(getApplicationContext(), "uploaded Status" + mediaBo, Toast.LENGTH_LONG).show();
if (!mediaBo.equals("null")) {
MediaMO mediaMO1 = gson.fromJson(mediaBo, new TypeToken<MediaMO>() {
}.getType());
}
}
}.execute(null, null, null);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
// noinspection SimplifiableIfStatement
if (id == R.id.ic_menu_gallery) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
return super.onOptionsItemSelected(item);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final List<ChatMO> chatMOs1 = new ArrayList<>();
activeEventMO = new EventMO();
setContentView(R.layout.chat_main);
context = getApplicationContext();
String message = "";
DatabaseHelper dbHelper = new DatabaseHelper(context);
listChatMessageObjectses = chatMOs1;
inputMsg = (EditText) findViewById(R.id.inputMsg);
listViewMessages = (ListView) findViewById(R.id.list_view_messages);
activeEventMO = (EventMO) getIntent().getParcelableExtra("eventMo");
Log.e("oncreate", "eventMO" +activeEventMO);
List<ChatMO> chatMOs = dbHelper.getGroupChatMessageForEvent(activeEventMO.getEventId());
Log.e("oncreate", "chatMOs" + chatMOs);
for (ChatMO chatMO1 : chatMOs) {
message = chatMO1.getMessage();
chatMO1.getEvent_id();
chatMO1.getFromName();
int messageType = chatMO1.getMessage_type();
chatMO1.getDate();
chatMO1.isSelf();
if (messageType == 0) {
chatMOs1.add(chatMO1);
}
}
adapter = new MessagesListAdapter(context, chatMOs1);
//adapter functionality added for show the previous chat list of event/invite
listViewMessages.setAdapter(adapter);
sharedpreferences = getSharedPreferences(Constants.SHARED_PREFERENCE_NAME, context.MODE_PRIVATE);
// by default first primary user is current user in sql lite
// user table
userMO = dbHelper.getUserData(1);
here i am passing the eventMO in gcmIntent
Intent groupChatActFrag = new Intent(getApplicationContext(), GroupChatActivity.class);
EventMO eventMO = new EventMO();
eventMO.setEventId(messageMO.getEventId());
Log.e("gcm","evetid"+eventMO.getEventId());
groupChatActFrag.putExtra("eventMo", eventMO);
groupChatActFrag.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("MessageMO", gson.toJson(messageMO));
editor.commit();
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, groupChatActFrag, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_dialog_info).setContentTitle(messageMO.getEventTitle())
.setStyle(new NotificationCompat.BigTextStyle().bigText(messageMO.getfromUserName())).setContentText(messageMO.getMessage()).setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
mBuilder.setContentIntent(contentIntent);
mBuilder.setAutoCancel(true);
Log.e("gcm","eventid"+messageMO.getEventId());
mNotificationManager.notify((int) (long) eventMO.getEventId(), mBuilder.build());
}
can you please tell me how to fix this issue thanks in advance
To refresh a variable after you activity or fragment has been destroyed you need to store in the saved bundled provided you in the method
public void onSavedInstanceState(final Bundle bundle)
And reset values with the bundle provided in the method
public void onCreate(final Bundle savedInstance)
Here is some good documentation
enter code here[Recreating an Activity - Android][1]
Related
I have a problem. I want to use the method onNewIntent() in a fragment. I have fortunately received one really good answer ( Please have a look ). I tried to work with this code snipped, but unfortunately the NFC tag cannot be read. What is it that I am doing wrong?
I hope you can help me with this issue. I would be very thankful for every answer.
The new code was always inserted between the comment lines // NEW INTENT
UserFragmentGeldaufladen
public class UserFragmentGeldaufladen extends Fragment {
private Button btn_user_geldaufladen, btn_user_main_geldsendenAbort;
private EditText edittext_user_geldaufladen;
private Dialog epicDialog;
private NfcAdapter nfcAdapter;
private PendingIntent pendingIntent;
private boolean writeMode;
private IntentFilter writeTagFilters[];
private Context context;
private Tag myTag;
private interface RetrievalEventListener<T> {
abstract void onDataRetrieved(T t);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_user_geldaufladen, container, false);
btn_user_geldaufladen = view.findViewById(R.id.btn_user_geldaufladen);
edittext_user_geldaufladen = view.findViewById(R.id.edittext_user_geldaufladen);
context = view.getContext();
epicDialog = new Dialog(view.getContext());
nfcAdapter = NfcAdapter.getDefaultAdapter(view.getContext());
if (nfcAdapter == null) {
// Stop here, we definitely need NFC
Toast.makeText(view.getContext(), "This device doesn't support NFC.", Toast.LENGTH_LONG).show();
}
// NEW INTENT
Intent i = new Intent(context, UserHomeActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // -> this will be require, if you will be update your fragment from BroadcastReceiver or Service
startActivity(i);
// NEW INTENT
readFromIntent( getActivity().getIntent());
pendingIntent = PendingIntent.getActivity(context, 0, new Intent(context, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
btn_user_geldaufladen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
transaction();
}
});
return view;
}
// NEW INTENT
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//get first time intent
Intent intent = getActivity().getIntent();
((UserHomeActivity)getActivity()).setOnNewIntentListener(new OnNewIntentListener() {
#Override
public void newIntent(Intent intent) {
readFromIntent(intent);
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
myTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
}
}
});
}
// NEW INTENT
private void readFromIntent(Intent intent) {
String action = intent.getAction();
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage[] msgs = null;
if (rawMsgs != null) {
msgs = new NdefMessage[rawMsgs.length];
for (int i = 0; i < rawMsgs.length; i++) {
msgs[i] = (NdefMessage) rawMsgs[i];
}
}
buildTagViews(msgs);
}
}
private void buildTagViews(NdefMessage[] msgs) {
if (msgs == null || msgs.length == 0) return;
String text = "";
// String tagId = new String(msgs[0].getRecords()[0].getType());
byte[] payload = msgs[0].getRecords()[0].getPayload();
String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16"; // Get the Text Encoding
int languageCodeLength = payload[0] & 0063; // Get the Language Code, e.g. "en"
// String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");
try {
// Get the Text
text = new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);
} catch (UnsupportedEncodingException e) {
Log.e("UnsupportedEncoding", e.toString());
}
System.out.println(text);
}
/***
* Initiates the transaction
*/
private void transaction() {
String amount_geldaufladen = String.valueOf(edittext_user_geldaufladen.getText());
if(!amount_geldaufladen.isEmpty() && Integer.parseInt(amount_geldaufladen) > 0) {
showWaitingPopup();
}
}
/***
* Shows that the user should confirm the payment
*/
private void showWaitingPopup() {
epicDialog.setContentView(R.layout.user_main_popup_waiting);
epicDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
btn_user_main_geldsendenAbort = (Button) epicDialog.findViewById(R.id.btn_user_main_geldsendenAbort);
btn_user_main_geldsendenAbort.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firebaseTransaction(new RetrievalEventListener<Integer>() {
#Override
public void onDataRetrieved(Integer integer) {
if(integer == 1) {
// do something
}
}
});
epicDialog.dismiss();
}
});
epicDialog.show();
}
/***
* Accesses the Firebase database and handles everything
*/
private void firebaseTransaction(final RetrievalEventListener<Integer> retrievalEventListener) {
// do Something
retrievalEventListener.onDataRetrieved(1);
}
/*
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
readFromIntent(intent);
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
myTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
}
}
*/
#Override
public void onPause(){
super.onPause();
WriteModeOff();
}
#Override
public void onResume(){
super.onResume();
WriteModeOn();
}
/******************************************************************************
**********************************Enable Write********************************
******************************************************************************/
private void WriteModeOn(){
writeMode = true;
nfcAdapter.enableForegroundDispatch((Activity) context, pendingIntent, writeTagFilters, null);
}
/******************************************************************************
**********************************Disable Write*******************************
******************************************************************************/
private void WriteModeOff(){
writeMode = false;
nfcAdapter.disableForegroundDispatch((Activity) context);
}
}
UserHomeActivity
public class UserHomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, UserOnFragmentBtnSelected {
Toolbar toolbar;
DrawerLayout drawer;
ActionBarDrawerToggle toggle;
NavigationView navigationView;
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
Fragment fragment;
String username;
// NEW INTENT
private OnNewIntentListener mOnNewIntentListener;
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (mOnNewIntentListener != null) {
mOnNewIntentListener.newIntent(intent);
}
}
public void setOnNewIntentListener(OnNewIntentListener onNewIntentListener) {
this.mOnNewIntentListener = onNewIntentListener;
}
// NEW INTENT
OnNewIntentListener
public interface OnNewIntentListener {
void newIntent(Intent intent);
}
sorry my question is may be very simple for all of you. But I am new and need solution for it. If you can help me for solve it.
I have one quote application which have function for check new quote from server in main activity, its checking with server on loading Main Activity that there new quotes available or not and if available its opening one popup window for go setting activity for download new quotes, and if user press setting button than its taking user to setting activity. I need some changes in it. I want automatic download new quotes from main activity without go setting activity. both activity are like below
Thanks
public class MainActivity extends Activity {
SharedPreferences mSharedPreferences;
//String qotdId;
private AdView mAdView;
private InterstitialAd mInterstitial;
public static boolean active;
DAO db;
String siteUrl, updatesUrl;
int lastAuthor, lastQuote;
private ConnectionDetector cd;
#Override
protected void onStart() {
mInterstitial = new InterstitialAd(this);
mInterstitial.setAdUnitId(getResources().getString(R.string.admob_publisher_interstitial_id));
mInterstitial.loadAd(new AdRequest.Builder().build());
super.onStart();
active = true;
}
#Override
protected void onStop() {
super.onStop();
active = false;
}
// ==============================================================================
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
mAdView = (AdView) findViewById(R.id.adView);
mAdView.loadAd(new AdRequest.Builder().build());
/* Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (isFirstRun) {
//show start activity
startActivity(new Intent(MainActivity.this, SettingsActivity.class));
Toast.makeText(MainActivity.this, "Please Push Download Button And Save Status in Your Mobile For Just One Time", Toast.LENGTH_LONG)
.show();
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("isFirstRun", false).commit();
*/
// Parse push notification
Parse.initialize(this, getString(R.string.parse_application_id), getString(R.string.parse_client_key));
ParseAnalytics.trackAppOpened(getIntent());
PushService.setDefaultPushCallback(this, MainActivity.class);
ParseInstallation.getCurrentInstallation().saveInBackground();
db = new DAO(this);
db.open();
cd = new ConnectionDetector(MainActivity.this);
siteUrl = getResources().getString(R.string.siteUrl);
updatesUrl = siteUrl + "site/get_updates/" + String.valueOf(lastAuthor) + "/" + String.valueOf(lastQuote);
if (cd.isConnectingToInternet()) {
// Internet Connection is not present
Intent checkUpdates = new Intent(MainActivity.this, CheckUpdatesService.class);
startService(checkUpdates);
}
// generateKeyHash();
final ImageButton quotes = (ImageButton) findViewById(R.id.quotes);
quotes.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,
QuotesActivity.class);
intent.putExtra("quotesType", 1);
intent.putExtra("itemSelected", 0);
startActivity(intent);
}
});
final ImageButton authors = (ImageButton) findViewById(R.id.authors);
authors.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,
AuthorsActivity.class);
startActivity(intent);
}
});
final ImageButton favorites = (ImageButton) findViewById(R.id.favorites);
favorites.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,
QuotesActivity.class);
intent.putExtra("quotesType", 2);
startActivity(intent);
}
});
final ImageButton settings = (ImageButton) findViewById(R.id.settings);
settings.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,
SettingsActivity.class);
startActivity(intent);
}
});
}
}
And my other activity
public class SettingsActivity extends PreferenceActivity {
static final int TIME_DIALOG_ID = 999;
private AdView mAdView;
private InterstitialAd mInterstitial;
private static final String MY_PREFERENCES = "my_preferences";
#Override
protected void onStart() {
mInterstitial = new InterstitialAd(this);
mInterstitial.setAdUnitId(getResources().getString(R.string.admob_publisher_interstitial_id));
mInterstitial.loadAd(new AdRequest.Builder().build());
super.onStart();
}
#Override
protected void onStop() {
//unregisterReceiver(receiver);
super.onStop();
}
// ==========================================================================================================//
DAO db;
// Progress dialog
ProgressDialog pDialog;
PreferenceScreen preferenceScreen;
private static SharedPreferences mSharedPreferences;
UpdateClass update;
// Internet Connection detector
private ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
Preference more, rate, about, check, share,status,background, progress = null;
PreferenceCategory socialsCategory;
private MyDownloadReceiver receiver;
// ==============================================================================
//////////////////// First Load /////////////////
public static boolean isFirst(Context context){
final SharedPreferences reader = context.getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
final boolean first = reader.getBoolean("is_first", true);
if(first){
final SharedPreferences.Editor editor = reader.edit();
editor.putBoolean("is_first", false);
editor.commit();
}
return first;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.config);
mAdView = (AdView) findViewById(R.id.adView);
mAdView.loadAd(new AdRequest.Builder().build());
//TWITTER_CONSUMER_KEY = getResources().getString(
// R.string.TWITTER_CONSUMER_KEY);
//TWITTER_CONSUMER_SECRET = getResources().getString(
// R.string.TWITTER_CONSUMER_SECRET);
//TWITTER_CALLBACK_URL = "oauth://"
// + getApplicationContext().getPackageName()
// + ".SettingsActivity";
//uiHelper = new UiLifecycleHelper(this, callback);
//uiHelper.onCreate(savedInstanceState);
db = new DAO(this);
db.open();
addPreferencesFromResource(R.layout.settings);
// Shared Preferences
mSharedPreferences = getApplicationContext().getSharedPreferences(
"MyPref", 0);
check = (Preference) findPreference("check");
about = (Preference) findPreference("about");
more = (Preference) findPreference("more");
rate = (Preference) findPreference("rate");
status = (Preference) findPreference("status");
share = (Preference) findPreference("share");
background = (Preference) findPreference("background");
socialsCategory = (PreferenceCategory) findPreference("socials");
preferenceScreen = getPreferenceScreen();
check.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
update = new UpdateClass(SettingsActivity.this);
update.handleUpdates();
//if (mInterstitial.isLoaded()) {
// mInterstitial.show();
//}
return false;
}
});
// ==============================================================================
about.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
Intent intent = new Intent(SettingsActivity.this,
AboutActivity.class);
startActivity(intent);
if (mInterstitial.isLoaded()) {
mInterstitial.show();
}
return false;
}
});
// ==============================================================================
background
.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference,
Object newValue) {
if (newValue.equals(true)) {
db.updateSetting("background", "1");
} else {
db.updateSetting("background", "0");
}
return true;
}
});
// ==============================================================================
// ==============================================================================
rate.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
final String appPackageName = "com.karopass.hindishayari2016";
try {startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id="+ appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("http://play.google.com/store/apps/details?id="+ appPackageName)));
}
return true;
}
});
// ==============================================================================
more.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
final String developerName = "karopass";
try {startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q="+ developerName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("https://play.google.com/store/search?q="+ developerName)));
}
return true;
}
});
share.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "आज ही डाउनलोड करे हिंदी शायरी एप्लीकेशन और पाइए बेस्ट हिंदी शायरी.इस एप्लीकेशन में 3000 से भी ज्यादा बढ़िया हिंदी शायरी का कलेक्शन है जिसे आप पढने या शेर करने के लिए यूज कर सकते है !! आज ही डाउनलोड करे !! http://play.google.com/store/apps/details?id=com.karopass.hindishayari2016";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, " ");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
return false;
}
});
// ==============================================================================
status.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
final String appPackageName = "com.karopass.hindi_status_2016";
try {startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id="+ appPackageName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("http://play.google.com/store/apps/details?id="+ appPackageName)));
}
return true;
}
});
// ==============================================================================
IntentFilter filter = new IntentFilter(MyDownloadReceiver.ACTION);
filter.addCategory(Intent.CATEGORY_DEFAULT);
receiver = new MyDownloadReceiver();
registerReceiver(receiver, filter);
}
void showProgressBar() {
progress = new MyProgressBarPreference(this);
preferenceScreen.addPreference(progress);
}
void setDownloadProgress(int percent) {
if (progress != null) {
((MyProgressBarPreference)progress).setProgress(percent);
((MyProgressBarPreference)progress).setLabel("Please wait... " +percent + "%"+" Downloading Done");
}
}
void hideProgressBar()
{
if (progress != null)
preferenceScreen.removePreference(progress);
}
public class MyDownloadReceiver extends BroadcastReceiver {
public static final String ACTION = "com.karopass.hindishayari2016.intent.action.DOWNLOAD";
public static final int INITIALIZE = 0x001;
public static final int DOWNLOAD = 0x002;
public static final int FINISH = 0x003;
public static final String EXTRA_STATUS = "status";
public static final String EXTRA_PERCENT = "percent";
#Override
public void onReceive(Context context, Intent intent) {
int status = intent.getIntExtra(EXTRA_STATUS, -1);
Log.d("DESOLF", "receive broadcast : " + status);
switch(status) {
case INITIALIZE:
showProgressBar();
break;
case DOWNLOAD:
int percent = intent.getIntExtra(MyDownloadReceiver.EXTRA_PERCENT, 0);
setDownloadProgress(percent);
break;
case FINISH:
hideProgressBar();
//Toast.makeText(SettingsActivity.this, "Downloaded successfully", Toast.LENGTH_LONG).show();
if (mInterstitial.isLoaded()) {
mInterstitial.show();
}
break;
default:
}
}
}
public class MyProgressBarPreference extends Preference {
public MyProgressBarPreference(Context context) {
super(context);
}
public MyProgressBarPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyProgressBarPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
private ImageView mStatusIcon;
private ProgressBar mProgressBar;
private TextView mStatusText ;
private int lastReqProgress=-1;
private int lastReqMax=-1;
private String lastLabel;
#Override
protected View onCreateView(ViewGroup parent) {
LayoutInflater li = (LayoutInflater) getSystemService(Service.LAYOUT_INFLATER_SERVICE);
View myLayout=li.inflate(R.layout.download_progress, null, false);
RotateAnimation anim = new RotateAnimation(0.0f, 360.0f,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
anim.setInterpolator(new LinearInterpolator());
anim.setRepeatCount(Animation.INFINITE);
anim.setDuration(700);
mStatusIcon = (ImageView) myLayout.findViewById(R.id.status_icon);
mStatusIcon.startAnimation(anim);
mProgressBar=(ProgressBar) myLayout.findViewById(R.id.status_progress);
mStatusText=(TextView) myLayout.findViewById(R.id.status_text);
mStatusIcon.setImageResource(R.drawable.rotate);
mProgressBar.setProgress(0);
mStatusText.setText(0 + "%");
return myLayout;
}
public void setIcon(int resId) {
mStatusIcon.setImageResource(resId);
}
public void setProgress(int value){
if (mProgressBar!=null){
mProgressBar.setProgress(value);
} else {
lastReqProgress=value;
}
}
public void setMax(int value){
if (mProgressBar!=null){
int savedprogress=mProgressBar.getProgress();
mProgressBar.setMax(0);
mProgressBar.setMax(value);
mProgressBar.setProgress(savedprogress);
} else {
lastReqMax=value;
}
}
public void setLabel(String text){
if (lastLabel!=null){
mStatusText.setText(text);
} else {
lastLabel=text;
}
}
}
}
You can try this code:
Intent i = new Intent(MainActivity.this, SecondActivity.class);
startActivity(i);
Don't forget to add your Second Activity in the AndroidManifest.xml:
<activity android:label="#string/app_name" android:name="SecondActivity"/>
Android Page
I'm using this code:
public class ActivityMain extends Activity {
private static final String TAG = "MainActivity";
private ServiceSpeechRecognition service;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
ServiceSpeechRecognition.MyBinder b = (ServiceSpeechRecognition.MyBinder) binder;
service = b.getService();
Log.e(TAG, "Service connected");
}
public void onServiceDisconnected(ComponentName className) {
savePrefs();
service = null;
Log.e(TAG, "Service disconnected");
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e(TAG, "onCreate");
setContentView(R.layout.activity_ui_main);
getPackageManager().setComponentEnabledSetting(new ComponentName(this, getPackageName() + ".MainActivity-Alias"), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
}
#Override
protected void onResume() {
super.onResume();
Log.e(TAG, "onResume");
GoogleSearchApi.registerQueryGroup(this, ReceiverGoogleSearch.group);
// Load prefs
SharedPreferences prefs = ActivityMain.getPrefs(this);
String key_phrase = prefs.getString(Preferences.KEY_PHRASE_KEY, Preferences.DEFAULT_KEY_PHRASE);
boolean require_charge = prefs.getBoolean(Preferences.KEY_REQUIRE_CHARGER, true);
// Update Ui
EditText text = (EditText) findViewById(R.id.key_phrase);
text.setText(key_phrase);
CheckBox checkbox = (CheckBox) findViewById(R.id.require_battery);
checkbox.setChecked(require_charge);
// If should, start intent
if (!require_charge || Util.isCharging(this)) {
bindIntent();
}
}
#Override
protected void onPause() {
if (service != null) {
Log.e(TAG, "Unbind");
unbindService(mConnection);
}
super.onPause();
}
private void bindIntent() {
Log.e(TAG, "Bind intent");
Intent intent = new Intent(this, ServiceSpeechRecognition.class);
startService(intent);
bindService(intent, mConnection, 0);
}
public void setKeyPhrase(View view) {
savePrefs();
if (service != null) {
EditText text = (EditText) findViewById(R.id.key_phrase);
String key_phrase = text.getText().toString();
service.setKeyPhrase(key_phrase);
}
Toast.makeText(this, R.string.str_key_phrase_updated, Toast.LENGTH_SHORT).show();
}
public void setRequireCharge(View view) {
savePrefs();
CheckBox checkbox = (CheckBox) view;
boolean require_charge = checkbox.isChecked();
if (service != null) {
service.setRequiresCharge(require_charge);
} else if (!require_charge || Util.isCharging(this)) {
bindIntent();
}
}
public void savePrefs() {
EditText text = (EditText) findViewById(R.id.key_phrase);
String key_phrase = text.getText().toString();
CheckBox checkbox = (CheckBox) findViewById(R.id.require_battery);
boolean require_charge = checkbox.isChecked();
SharedPreferences.Editor prefs = ActivityMain.getPrefs(this).edit();
prefs.putString(Preferences.KEY_PHRASE_KEY, key_phrase);
prefs.putBoolean(Preferences.KEY_REQUIRE_CHARGER, require_charge);
prefs.commit();
}
public static SharedPreferences getPrefs(Context context) {
return context.getSharedPreferences(Preferences.KEY, Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS);
}
}
this is an activity in which starts a service.. The problem is that the service starts as soon as the activity it opens. I would create a button or checkbox to start it. But now when I open the activity it starts the service. I didn't write any startService() in the onCreate() method.
Here You Start Your Service in On Resume so Replace
private void bindIntent() {
Log.e(TAG, "Bind intent");
Intent intent = new Intent(this, ServiceSpeechRecognition.class);
startService(intent);
bindService(intent, mConnection, 0);
}
to
private void bindIntent() {
Log.e(TAG, "Bind intent");
Intent intent = new Intent(this, ServiceSpeechRecognition.class);
bindService(intent, mConnection, 0);
}
Put below code in your button click event.
Intent intent = new Intent(this, ServiceSpeechRecognition.class);
startService(intent);
Thats it....
I have an application where the user may send recipes to others with the application.
Right now, the app is able to send the notification, however, when the notification is clicked, it does not open the intended activity (SmsViewActivity) it simply closes the drawer.
Here is the code for the SmsViewActivity:
public class SmsViewActivity extends Activity {
private static final String TAG = "SmsViewActivity";
private static final String SMS_FOOD = "food_recieved";
private FoodJSONSerializer mSerializer;
public Button mSaveButton, mDismissButton;
public int mNotificationId;
public String message;
private EditText mTitleField;
private CheckBox mImperialCheckBox;
private CheckBox mMetricCheckBox;
private EditText mServingsField;
private EditText mDirectionsField;
private Spinner mMetricSpinner;
private Spinner mImperialSpinner;
Food mFood;
private String msg;
private Activity mActivity;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
mActivity = this;
setContentView(R.layout.sms_view);
mSaveButton = (Button) findViewById(R.id.save_button_sms);
mDismissButton = (Button) findViewById(R.id.dismiss_button_sms);
this.msg = getIntent().getStringExtra("message");
try {
JSONObject jsonRecipe = new JSONObject(this.msg);
this.mFood = new Food(jsonRecipe);
Log.i(TAG, "Food = " + mFood);
} catch (JSONException e) {
e.printStackTrace();
}
mNotificationId = getIntent().getIntExtra("notificationid", 0);
if (mNotificationId == 0) {
Log.e(TAG, "Could not retrieve notification ID.");
Toast.makeText(this, "A fatal error has occurred in SMS viewer.",
Toast.LENGTH_LONG).show();
finish();
}
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager notificationMgr = (NotificationManager) getSystemService(ns);
notificationMgr.cancel(mNotificationId);
this.mTitleField = (EditText) findViewById(R.id.food_title_sms);
this.mTitleField.setText(mFood.getTitle());
this.mServingsField = (EditText) findViewById(R.id.food_servings_sms);
this.mServingsField.setText(Integer.toString(mFood.getServings()));
this.mDirectionsField = (EditText) findViewById(R.id.directions_text_sms);
this.mDirectionsField.setText(mFood.getDirections());
this.mSaveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
FoodStorage.get(mActivity).addFood(mFood);
finish();
}
});
this.mDismissButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
backToList();
finish();
}
});
}
public void backToList() {
Intent i = new Intent(this, FoodListFragment.class);
startActivity(i);
}
}
Also here is the receiver Activity:
#Override
public void onReceive(Context context, Intent intent) {
mContext = context;
Bundle bundle = intent.getExtras();
Map<String, String> msgTexts = new LinkedHashMap<String, String>();
if (bundle != null){
Object[] pdus = (Object[]) bundle.get("pdus");
for (Object pdu : pdus) {
SmsMessage message = SmsMessage.createFromPdu((byte[]) pdu);
String incomingMsg = message.getMessageBody();
String originatingNumber = message.getOriginatingAddress();
Log.i(TAG, "Rcvd: from " + originatingNumber + " Msg: " + incomingMsg);
msgTexts.put(originatingNumber, incomingMsg);
smsMessage = incomingMsg;
}
}
processMessages(msgTexts, mNextNotificationId);
}
public void processMessages( Map<String, String> msgTexts, int notificationId ){
for (Entry<String, String> entry : msgTexts.entrySet()) {
Log.i(TAG, "Processing message: " + entry.getValue());
Intent notificationIntent = new Intent(mContext, SmsViewActivity.class);
notificationIntent.putExtra("message", entry.getValue());
notificationIntent.putExtra("sender", entry.getKey());
notificationIntent.putExtra("notificationid", notificationId);
PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder = new NotificationCompat.Builder(mContext)
.setSmallIcon(R.drawable.ic_launcher)
.setTicker("Recipe Received")
.setContentTitle("Recipe Received")
.setContentIntent(resultPendingIntent)
.setContentText("from " + entry.getKey())
.setWhen(System.currentTimeMillis());
NotificationManager notificationMgr = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationMgr.notify(notificationId++, mBuilder.build());
}
}
Try changing the intent flag to:
PendingIntent.FLAG_CANCEL_CURRENT
Otherwise it just updates the existing intent. It should be possible to have an onNewIntent handler in your activity, but I found this works more reliably.
I want to send an sms if i click the alert box button.I have an listview with checkbox after clicking the checkbox,above i put an buttonselected,After click that button it shows one alert box which contains the selected things with "ok" alertsetbutton.What i need is after clicking the ok button,i have to send an sms and an email with the selected content.
How can i do this.
Main activity.java
public class MainActivity extends Activity implements FetchDataListener,OnClickListener
{
private static final int ACTIVITY_CREATE=0;
private ProgressDialog dialog;
ListView lv;
private List<Application> items;
private Button btnGetSelected;
//private ProjectsDbAdapter mDbHelper;
//private SimpleCursorAdapter dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
//mDbHelper = new ProjectsDbAdapter(this);
//mDbHelper.open();
//fillData();
//registerForContextMenu(getListView());
lv =(ListView)findViewById(R.id.list);
btnGetSelected = (Button) findViewById(R.id.btnget);
btnGetSelected.setOnClickListener(this);
initView();
}
private void initView()
{
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
String url = "http://dry-brushlands-3645.herokuapp.com/posts.json";
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
//mDbHelper.open();
//Cursor projectsCursor = mDbHelper.fetchAllProjects();
//startManagingCursor(projectsCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
//String[] from = new String[]{ProjectsDbAdapter.KEY_TITLE};
// and an array of the fields we want to bind those fields to (in this case just text1)
//int[] to = new int[]{R.id.text1};
/* Now create a simple cursor adapter and set it to display
SimpleCursorAdapter projects =
new SimpleCursorAdapter(this, R.layout.activity_row, projectsCursor, from, to);
setListAdapter(projects);
*/
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
/*dataAdapter = new SimpleCursorAdapter(
this, R.layout.activity_row,
projectsCursor,
from,
to,
0);
setListAdapter(dataAdapter);
*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.activity_main, menu);
super.onCreateOptionsMenu(menu);
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
createProject();
return super.onMenuItemSelected(featureId, item);
}
private void createProject() {
Intent i = new Intent(this, ProjectEditActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
initView();
}
#Override
public void onFetchComplete(List<Application> data)
{
this.items = data;
// dismiss the progress dialog
if ( dialog != null )
dialog.dismiss();
// create new adapter
ApplicationAdapter adapter = new ApplicationAdapter(this, data);
// set the adapter to list
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
CheckBox chk = (CheckBox) view.findViewById(R.id.checkbox);
Application bean = items.get(position);
if (bean.isSelected()) {
bean.setSelected(false);
chk.setChecked(false);
} else {
bean.setSelected(true);
chk.setChecked(true);
}
}
});
}
// Toast is here...
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onFetchFailure(String msg)
{
// dismiss the progress dialog
if ( dialog != null )
dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
StringBuffer sb = new StringBuffer();
// Retrive Data from list
for (Application bean : items) {
if (bean.isSelected()) {
sb.append(Html.fromHtml(bean.getContent()));
sb.append(",");
}
}
showAlertView(sb.toString().trim());
}
#SuppressWarnings("deprecation")
private void showAlertView(String str) {
AlertDialog alert = new AlertDialog.Builder(this).create();
if (TextUtils.isEmpty(str)) {
alert.setTitle("Not Selected");
alert.setMessage("No One is Seleceted!!!");
} else {
// Remove , end of the name
String strContactList = str.substring(0, str.length() - 1);
alert.setTitle("Selected");
alert.setMessage(strContactList);
}
alert.setButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "default");
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
dialog.dismiss();
}
});
/*buttonSendSms_intent.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String smsNumber = edittextSmsNumber.getText().toString();
String smsText = edittextSmsText.getText().toString();
Uri uri = Uri.parse("smsto:" + smsNumber);
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.putExtra("sms_body", smsText);
startActivity(intent);
}});*/
alert.show();
}
#Override
public void onBackPressed() {
AlertDialog alert_back = new AlertDialog.Builder(this).create();
alert_back.setTitle("Quit?");
alert_back.setMessage("Are you sure want to Quit?");
alert_back.setButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert_back.setButton2("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
MainActivity.this.finish();
}
});
alert_back.show();
}
#Override
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
// TODO Auto-generated method stub
}
}
Here alert.setbutton is the crucial button,from there only i need,I already put sms code its not working properly.
Here i add my asynctask also.
public class FetchDataTask extends AsyncTask<String, Void, String>
{
private final FetchDataListener listener;
private String msg;
public FetchDataTask(FetchDataListener listener)
{
this.listener = listener;
}
#Override
protected String doInBackground(String... params)
{
if ( params == null )
return null;
// get url from params
String url = params[0];
try
{
// create http connection
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
// connect
HttpResponse response = client.execute(httpget);
// get response
HttpEntity entity = response.getEntity();
if ( entity == null )
{
msg = "No response from server";
return null;
}
// get response content and convert it to json string
InputStream is = entity.getContent();
return streamToString(is);
}
catch ( IOException e )
{
msg = "No Network Connection";
}
return null;
}
#Override
protected void onPostExecute(String sJson)
{
if ( sJson == null )
{
if ( listener != null )
listener.onFetchFailure(msg);
return;
}
try
{
// convert json string to json object
JSONObject jsonObject = new JSONObject(sJson);
JSONArray aJson = jsonObject.getJSONArray("post");
// create apps list
List<Application> apps = new ArrayList<Application>();
for ( int i = 0; i < aJson.length(); i++ )
{
JSONObject json = aJson.getJSONObject(i);
Application app = new Application();
app.setContent(json.getString("content"));
// add the app to apps list
apps.add(app);
}
//notify the activity that fetch data has been complete
if ( listener != null )
listener.onFetchComplete(apps);
}
catch ( JSONException e )
{
e.printStackTrace();
msg = "Invalid response";
if ( listener != null )
listener.onFetchFailure(msg);
return;
}
}
/**
* This function will convert response stream into json string
*
* #param is
* respons string
* #return json string
* #throws IOException
*/
public String streamToString(final InputStream is) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ( (line = reader.readLine()) != null )
{
sb.append(line + "\n");
}
}
catch ( IOException e )
{
throw e;
}
finally
{
try
{
is.close();
}
catch ( IOException e )
{
throw e;
}
}
return sb.toString();
}
}
call this method from your button clicking event.
sendSMS("Any text like your name","Your number","Your sms text");
method :
public static void sendSMS(String status, String phoneNumber, String message) {
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}
Also declare this permission in your manifest :
<uses-permission android:name="android.permission.SEND_SMS"/>
Simple.
Put this in the click listener for the OK Button
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);