Back to project page MySms.
The source code is released under:
Apache License
If you think the Android project MySms listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
package com.henningta.mysms; /* w w w . ja v a 2 s . c o m*/ import android.app.Activity; import android.app.AlertDialog; import android.app.Fragment; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.database.DataSetObserver; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.ActionBarActivity; import android.text.Editable; import android.text.TextWatcher; import android.view.HapticFeedbackConstants; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import android.widget.Toast; import java.util.Calendar; public class MessagesFragment extends Fragment implements AdapterView.OnItemLongClickListener { public static final String TAG = "com.henningta.mysms.MessagesFragment"; private Activity activity; private Conversation conversation; private DatabaseHandler dbHandler; private MessageAdapter messageAdapter; private ListView lvMessages; private EditText etMessage; private String source; private Handler sendHandler; public static MessagesFragment newInstance(String source) { MessagesFragment fragment = new MessagesFragment(); Bundle args = new Bundle(); args.putString(Settings.KEY_SOURCE, source); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); source = getArguments().getString(Settings.KEY_SOURCE); sendHandler = new Handler(); setRetainInstance(true); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_messages, container, false); // initialize messages listview lvMessages = (ListView)view.findViewById(R.id.lvMessages); lvMessages.setOnItemLongClickListener(this); // initialize send button final ImageButton sendButton = (ImageButton)view.findViewById(R.id.sendButton); sendButton.setOnClickListener(new SendButtonListener(activity)); setImageButtonEnabled(false, sendButton); // initialize message EditText etMessage = (EditText)view.findViewById(R.id.etMessage); etMessage.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) {} @Override public void afterTextChanged(Editable s) { if (s == null || s.length() == 0) { setImageButtonEnabled(false, sendButton); } else { setImageButtonEnabled(true, sendButton); } } }); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); this.activity = getActivity(); dbHandler = new DatabaseHandler(activity); conversation = dbHandler.getConversation(source); if (conversation == null) { // create new conversation conversation = new Conversation(activity.getContentResolver(), source); } // initialize toolbar ((ActionBarActivity)activity).getSupportActionBar().setTitle(conversation.getName()); ((ActionBarActivity)activity).getSupportActionBar().setSubtitle(Settings.formatSource(source)); } @Override public void onResume() { super.onResume(); // mark conversation as being read conversation.setHasNewMessages(false); dbHandler.updateConversation(conversation); // refresh main page Intent conversationIntent = new Intent(Settings.ACTION_CONVERSATION); activity.sendBroadcast(conversationIntent); // initialize message adapter messageAdapter = new MessageAdapter(activity, R.layout.message_list_item, dbHandler.getMessages(source)); lvMessages.setAdapter(messageAdapter); lvMessages.setSelection(messageAdapter.getCount() - 1); // register objects messageAdapter.registerDataSetObserver(messageAdapterDataSetObserver); activity.registerReceiver(messageReceiver, new IntentFilter(Settings.ACTION_MESSAGE)); } @Override public void onPause() { super.onPause(); // unregister objects messageAdapter.unregisterDataSetObserver(messageAdapterDataSetObserver); activity.unregisterReceiver(messageReceiver); } /** * Set enabled status of image button and change icon accordingly */ private void setImageButtonEnabled(boolean enabled, ImageButton item) { Drawable originalIcon = getResources().getDrawable(R.drawable.ic_action_send_now); Drawable disabledIcon = getResources().getDrawable(R.drawable.ic_action_send_disabled); Drawable icon = enabled ? originalIcon : disabledIcon; item.setEnabled(enabled); item.setImageDrawable(icon); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { menu.clear(); inflater.inflate(R.menu.messages, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { /*switch (item.getItemId()) { case android.R.id.home: // navigate up //NavUtils.navigateUpFromSameTask(activity); return true; }*/ return super.onOptionsItemSelected(item); } private class SendButtonListener implements View.OnClickListener { private Context context; public SendButtonListener(Context context) { this.context = context; } @Override public void onClick(View v) { final String messageText = etMessage.getText().toString().trim(); if (messageText.equals("")) { Toast.makeText(context, "Please type a message to send", Toast.LENGTH_SHORT).show(); return; } new Thread(new Runnable() { @Override public void run() { long time = Calendar.getInstance().getTimeInMillis(); conversation.setTime(time); if (dbHandler.getConversation(source) == null) { // add conversation to database dbHandler.addConversation(conversation); } else { // update conversation time in database dbHandler.updateConversation(conversation); } // add message to database final Message message = new Message(source, messageText, time, Message.STATUS_SENDING); dbHandler.addMessage(message); // send sms if (!SmsTools.sendSMS(activity, message, conversation.getSource())) { message.setStatus(Message.STATUS_FAILED); dbHandler.updateMessage(message); activity.runOnUiThread(new Runnable() { public void run() { Toast.makeText(activity, "Error: message failed to send", Toast.LENGTH_SHORT).show(); } }); } sendHandler.post(new Runnable() { @Override public void run() { // refresh UI messageAdapter.add(message); etMessage.setText(""); } }); } }).start(); } } @Override public boolean onItemLongClick(AdapterView<?> adapter, View v, final int position, long id) { v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY, HapticFeedbackConstants.LONG_PRESS); final Message message = (Message)adapter.getItemAtPosition(position); String[] options = { "Copy message text", "Delete message" }; AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle("Message Options") .setItems(options, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: // copy message text to clipboard String text = message.getText(); String label = conversation.getSource() + ": message " + String.valueOf(position); copyStringToClipboard(activity, label, text); Toast.makeText(activity, "Message copied to clipboard", Toast.LENGTH_SHORT).show(); break; case 1: // delete message from database dbHandler.deleteMessage(message); messageAdapter.remove(message); break; default: break; } } }); AlertDialog dialog = builder.create(); dialog.show(); return false; } private void copyStringToClipboard(Context context, String label, String text) { android.content.ClipboardManager clipboard = (android.content.ClipboardManager)context.getSystemService(Context.CLIPBOARD_SERVICE); android.content.ClipData clip = android.content.ClipData.newPlainText(label, text); clipboard.setPrimaryClip(clip); } /** * Observes changes made to data in messageAdapter */ private DataSetObserver messageAdapterDataSetObserver = new DataSetObserver() { @Override public void onChanged() { super.onChanged(); // scroll to bottom of messages lvMessages.setSelection(messageAdapter.getCount() - 1); } }; /** * Broadcast receiver to update UI */ private BroadcastReceiver messageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Intent conversationIntent = new Intent(Settings.ACTION_CONVERSATION); boolean refreshOnly = intent.getBooleanExtra(Settings.KEY_REFRESH, false); if (refreshOnly) { // refresh messages page and main page messageAdapter.clear(); messageAdapter.addAll(dbHandler.getMessages(source)); context.sendBroadcast(conversationIntent); return; } String updateSource = intent.getStringExtra(Settings.KEY_SOURCE); String text = intent.getStringExtra(Settings.KEY_MESSAGE); long time = intent.getLongExtra(Settings.KEY_TIME, -1); if (updateSource == null || text == null || time == -1) { Toast.makeText(context, "Unexpected error", Toast.LENGTH_SHORT).show(); return; } if (!source.equals(updateSource)) { // message in different conversation than current return; } // add message to adapter Message message = dbHandler.getMessage(updateSource, text, time); messageAdapter.add(message); // mark conversation as being read conversation.setHasNewMessages(false); dbHandler.updateConversation(conversation); // refresh main page context.sendBroadcast(conversationIntent); } }; }