how to use setter in broadcast receiver? - java

I have java class to programatically send an SMS from an android application. I want to generate a report after sending the meesage for that i need the status of the message activity which are
sending status;
receiving status;
Both the status are displaying properly in the toast , But when i tries to set the setter for these it returns me the default values. May be because the
mContext.registerReceiver(new BroadcastReceiver() ........... is on a different thread , How i can set the setter or can fetch te sending status from this function block?
public class SMSSending
{
private String phoneNo;
private String message;
private Context mContext;
Settings.Global global;
public void setSendingStatus(String sendingStatus) {
this.sendingStatus = sendingStatus;
}
private String sendingStatus;
public void setReceivingStatus(String receivingStatus) {
this.receivingStatus = receivingStatus;
}
private String receivingStatus;
public SMSSending(String phoneNo, Context mContext, String testID)
{
this.phoneNo = phoneNo;
this.mContext = mContext;
message = "This is a test message from " + testID;
}
public String getSendingStatus()
{
return sendingStatus;
}
public String getReceivingStatus()
{
return receivingStatus;
}
public void sendingMessage()
{
try
{
sendingStatus = "Failed to send SMS message";
receivingStatus = "Failed to deliver SMS ";
String SENT = "sent";
String DELIVERED = "delivered";
PendingIntent sentPI = PendingIntent.getBroadcast(mContext, 0, new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(mContext, 0,new Intent(DELIVERED), 0);
//setSendingStatus("Transmission successful");
//Register for SMS send action
mContext.registerReceiver(new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
switch (getResultCode())
{
case Activity.RESULT_OK:
sendingStatus = "Transmission successful";
break;
default:
sendingStatus = "Transmission failure";
break;
}
// Save sendingStatus in Database as test report for sending message.
Toast.makeText(mContext, sendingStatus,Toast.LENGTH_LONG).show();
setSendingStatus(sendingStatus);
}
}, new IntentFilter(SENT));
/* Register for Delivery event */
mContext.registerReceiver(new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
receivingStatus = "SMS Delivered Succesfully";
// Save sendingStatus in Database as test report for receiving message.
// This function will only be executed if message has been successful received
Toast.makeText(mContext, receivingStatus, Toast.LENGTH_LONG).show();
setReceivingStatus(receivingStatus);
}
},new IntentFilter(DELIVERED));
enter code here
//Send SMS
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, sentPI, deliveredPI);
}
catch (Exception ex)
{
sendingStatus = "Failed to send SMS message";
receivingStatus = "Failed to deliver SMS ";
}
}

Related

How to send message to multiple numbers using Service?

I want to send message to multiple numbers. I tried to use SMS manager. But it's not working.
I am doing it onPostExecute method of an AsyncTask. But I want to create a service and send messages from that service because user can close the application before messages sending gets complete so it should be working in background.
I have created a arraylist of numbers. Now this I want to send to service and send message to each number.
My attempt:
#Override
public void doPostExecute(JSONArray response) throws JSONException {
ArrayList<String> numbers = new ArrayList<>();
for (int i = 0; i < response.length(); i++) {
JSONObject subObject1 = response.getJSONObject(i);
String status = subObject1.getString("status");
if (status.equals("1")) {
JSONObject invitation = subObject1.getJSONObject("invitation");
String number = invitation.getString("invitee_no");
numbers.add(number);
} else {
}
}
try {
SmsManager sms = SmsManager.getDefault();
PendingIntent sentPI;
String SENT = "SMS_SENT";
sentPI = PendingIntent.getBroadcast(InviteContactsActivity.this, 0,new Intent(SENT), 0);
sms.sendTextMessage(phoneNumber, null, message, sentPI, null);
sms.sendTextMessage("8655864341", null, "Hi,add me to your unique contact list.",sentPI, null);
} catch (Exception e) {
e.printStackTrace();
}
}
I have added permission for send sms in manifest.
<uses-permission android:name="android.permission.SEND_SMS"/>
How can I do this? Can anyone help please? Thank you..
EDIT:
I tried to write service like below:
public class MessageService extends Service {
ArrayList<String> numbers = new ArrayList<>();
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
numbers = intent.getStringArrayListExtra("numbers");
for(int i=0;i<numbers.size();i++) {
sendMsg(numbers.get(i));
}
return super.onStartCommand(intent, flags, startId);
}
public void sendMsg(final String num){
String SENT = "SMS_SENT";
final SmsManager sms = SmsManager.getDefault();
final PendingIntent sentPI = PendingIntent.getBroadcast(MessageService.this, 0,new Intent(SENT), 0);
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
sms.sendTextMessage("8655864341", null, "Hi MyApp SMS", sentPI, null);
}
}, 2000);
}
#Override
public IBinder onBind(Intent intent)
{
// numbers = intent.getStringArrayListExtra("numbers");
return null;
}
}
And calling it from an activity:
Intent serviceIntent = new Intent(this,MessageService.class);
serviceIntent.putStringArrayListExtra("numbers",numbers);
startService(serviceIntent);
Added service in manifest:
<uses-permission android:name="android.permission.SEND_SMS" />
<receiver android:name=".SmsSentReceiver"/> <receiver android:name=".SmsDeliveredReceiver"/>
<service android:name=".helper.MessageService"></service>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".Activities.MainActivity" />
But as I do debug and check service is not getting called.
What's going wrong?
EDIT :
Tried this way with broadcast receiver :
public class MessageService extends Service {
ArrayList<String> numbers = new ArrayList<>();
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
numbers = intent.getStringArrayListExtra("numbers");
for (String number:numbers) {
sendSMS("8655864341","Hello");
}
// sendMsg(numbers.get(i));
return super.onStartCommand(intent, flags, startId);
}
public void sendMsg(final String num){
String SENT = "SMS_SENT";
final SmsManager sms = SmsManager.getDefault();
final PendingIntent sentPI = PendingIntent.getBroadcast(MessageService.this, 0,new Intent(SENT), 0);
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
sms.sendTextMessage("7303668514", null, "Hi MyApp SMS", sentPI, null);
}
}, 2000);
}
#Override
public IBinder onBind(Intent intent)
{
// numbers = intent.getStringArrayListExtra("numbers");
return null;
}
private void sendSMS (String phoneNumber, String message){
ArrayList<PendingIntent> sentPendingIntents = new ArrayList<PendingIntent>();
ArrayList<PendingIntent> deliveredPendingIntents = new ArrayList<PendingIntent>();
PendingIntent sentPI = PendingIntent.getBroadcast(getApplicationContext(), 0,
new Intent(getApplicationContext(), SmsSentReceiver.class), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(getApplicationContext(), 0,
new Intent(getApplicationContext(), SmsDeliveredReceiver.class), 0);
try {
SmsManager sms = SmsManager.getDefault();
ArrayList<String> mSMSMessage = sms.divideMessage(message);
for (int i = 0; i < mSMSMessage.size(); i++) {
sentPendingIntents.add(i, sentPI);
deliveredPendingIntents.add(i, deliveredPI);
}
sms.sendMultipartTextMessage(phoneNumber, null, mSMSMessage,
sentPendingIntents, deliveredPendingIntents);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "SMS sending failed...", Toast.LENGTH_SHORT).show();
}
}
public class SmsDeliveredReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(context, "SMS delivered", Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(context, "SMS not delivered", Toast.LENGTH_SHORT).show();
break;
}
}
}
public class SmsSentReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(context, "SMS Sent", Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(context, "SMS generic failure", Toast.LENGTH_SHORT)
.show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(context, "SMS no service", Toast.LENGTH_SHORT)
.show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(context, "SMS null PDU", Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(context, "SMS radio off", Toast.LENGTH_SHORT).show();
break;
}
}
}
Getting this exception:
java.lang.RuntimeException: Unable to instantiate receiver com.example.siddhi.contactsapp.helper.MessageService$SmsSentReceiver: java.lang.InstantiationException: class com.example.siddhi.contactsapp.helper.MessageService$SmsSentReceiver has no zero argument constructor
Not getting message..
You can do something like this :
Use a for loop for your Numbers list and inside that Use a handler to maintain some time gap between each sent message, say 2 seconds and send the message.
OR
You can define a Broadcast Receiver inside your Service which will check for the Message Delivery Report and if Delivered then send another Message.
First Link
Second Link
Hope it Helps :)
Edit :
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
ArrayList<String> numberlist=new ArrayList<String>();
for(int i=0;i<numberlist.size();i++) {
sendMsg(numberlist.get(i));
}
return super.onStartCommand(intent, flags, startId);
}
public void sendMsg(final String num){
String SENT = "SMS_SENT";
final SmsManager sms = SmsManager.getDefault();
final PendingIntent sentPI = PendingIntent.getBroadcast(MyService.this, 0,new Intent(SENT), 0);
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
sms.sendTextMessage(num, null, "Hi MyApp SMS", sentPI, null);
}
}, 2000);
}
try to send SMS OnPost Method or run your AsynTask on Main Thread.
follow this link its help you

Android: send sms after receiving one

I' writing an app to send phone location after receiving an SMS request. Receiving SMS's works and sending SMS works too. What to do to make it send SMS after receiving one?
MainActivity
final static String gpsLocationProvider = LocationManager.GPS_PROVIDER;
final static String networkLocationProvider = LocationManager.NETWORK_PROVIDER;
static String loc;
public LocationManager locationManager;
static TextView messageBox;
public void sendSMS(String phoneNumber, String message)
{
PendingIntent pi = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, pi, null);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
messageBox = (TextView)findViewById(R.id.messageBox);
locationManager =
(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Location lastKnownLocation_byGps =
locationManager.getLastKnownLocation(gpsLocationProvider);
Location lastKnownLocation_byNetwork =
locationManager.getLastKnownLocation(networkLocationProvider);
if (lastKnownLocation_byGps != null) {
loc = "gps " + lastKnownLocation_byGps.getLatitude();
}
if (lastKnownLocation_byNetwork != null) {
loc = "net lat:" + lastKnownLocation_byNetwork.getLatitude() + " long:" + lastKnownLocation_byNetwork.getLongitude();
}
}
public static void updateMessageBox(String msg) {
messageBox.setText(msg);
}
Receiver
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle=intent.getExtras();
Object[] messages=(Object[])bundle.get("pdus");
SmsMessage[] sms=new SmsMessage[messages.length];
for(int n=0;n<messages.length;n++){
sms[n]=SmsMessage.createFromPdu((byte[]) messages[n]);
}
for(SmsMessage msg:sms){
MainActivity.updateMessageBox("\nFrom: "+msg.getOriginatingAddress()+"\n"+
"Message: "+msg.getMessageBody());
}
}
Where to put sendSMS method to send SMS after receiving one?
You can call your send sms code statements at the end of onReceive method, because this method executes when you receive a sms.

Android Handheld and Wear Communication is not consistent

We have an Android mobile app, where you can purchase parking tickets for a period. Now, we are planning to integrate it with Android wear.
What we are doing here is:
We want the user to get notified 15 before of the expiry of ticket.
To do this, we create a local notification and schedule it using Alarm Manger.
This scheduled notification is received by Android Broadcast receiver and display this notification on mobile device in Android notification section.
Further, this receiver calls the intent service to send the notification to wear. In this step, we create googleApiClient and onConnected callback, we send the data to wear to show the notification.
On wear, user can check the notification and on tap, user can extend the time of purchased ticket. This flow contains 3-4 views after notification tapping.
We have issue in step 4. Most of the time, on a very first connection (notification), wear does not show the notification and on second connection (notification), wear show both first and second notification and after that it works fine.
We tried to figure out the problem, but no success. Below is the code snippet of Receiver, Intent Service and wear side ListnerServices for understanding.
public class WearNotificationService extends IntentService {
private static final String TAG = "PhoneActivity";
private GoogleApiClient mGoogleApiClient;
public static String title;
public static String desc;
public static String data;
public WearNotificationService() {
super("WearNotificationService");
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, title +"--"+ desc , Toast.LENGTH_SHORT).show();
mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle connectionHint) {
sendNotification(title,desc,data);
Log.d(TAG, "onConnected: " + connectionHint);
}
#Override
public void onConnectionSuspended(int cause) {
Log.d(TAG, "onConnectionSuspended: " + cause);
}
}).addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.d(TAG, "onConnectionFailed: " + result);
}
}).addApi(Wearable.API).build();
mGoogleApiClient.connect();
}
#Override
protected void onHandleIntent(Intent intent) {
}
private void sendNotification(String title,String desc,String data) {
Log.e(TAG, "i am onConnectiond: ");
PutDataMapRequest dataMapRequest = PutDataMapRequest.create(Constants.PATH_NOTIFICATION);
dataMapRequest.getDataMap().putDouble(Constants.NOTIFICATION_TIMESTAMP, System.currentTimeMillis());
dataMapRequest.getDataMap().putString(Constants.KEY_TITLE, title);
dataMapRequest.getDataMap().putString(Constants.KEY_DESC, desc);
dataMapRequest.getDataMap().putString(Constants.KEY_DATA, data);
PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest();
Wearable.DataApi.putDataItem(mGoogleApiClient, putDataRequest);
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (null != intent) {
String action = intent.getAction();
if (Constants.ACTION_DISMISS.equals(action)) {
dismissNotification();
}
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDataChanged(DataEventBuffer dataEvents) {
for (DataEvent dataEvent : dataEvents) {
if (dataEvent.getType() == DataEvent.TYPE_CHANGED) {
if (Constants.PATH_NOTIFICATION.equals(dataEvent.getDataItem().getUri().getPath())) {
DataMapItem dataMapItem = DataMapItem.fromDataItem(dataEvent.getDataItem());
String title = dataMapItem.getDataMap().getString(Constants.KEY_TITLE);
String content = dataMapItem.getDataMap().getString(Constants.KEY_DESC);
String data = dataMapItem.getDataMap().getString(Constants.KEY_DATA);
String id = null;
try {
JSONObject obj = new JSONObject(data);
id = (String) obj.get("id");
} catch (JSONException e) {
e.printStackTrace();
}
sendNotification(title, content, data,id);
}
}
}
}
private void sendNotification(String title, String content, String data,String id) {
Intent notificationIntent = new Intent(this, HoursExtension.class);
Log.e("data1111", data);
HoursExtension.data = data;
HoursExtension.id = id;
PendingIntent notificationPendingIntent = PendingIntent.getActivity(this, 0, notificationIntent,0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.icon)
.setContentTitle(title)
.setContentText(content)
.setContentIntent(notificationPendingIntent)
.extend(new NotificationCompat.WearableExtender().setBackground(BitmapFactory.decodeResource(getResources(), R.drawable.rtabg)))
;
Notification notification = builder.build();
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
notificationManagerCompat.notify(Integer.parseInt(id), notification);
}
I solved it by sending a dummy request on app installation . Which is send once the app is installed and handled in wear by eating that first request this solved my problem . :)

Passing data from BroadCastRecevier to activity

I have an SMS reader application and i am showing the senderno and message body into the Custom Listview. For the incoming messages i have registered a broadcast receiver and populating the listView.
Whenever a new message is coming in the broadcast Receiver i am able to get it but I want to this data to be passed onto the activity.
The code snippets are :
MainActvity.java
public class MainSmsActivity extends Activity{
private ListView smsList;
SmsAdapter smsAdapter;
private SmsDao smsDao;
private List<SmsDao> smsDataList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms_demo);
smsDataList = new ArrayList<SmsDao>();
Intent intent = new Intent();
intent.setAction("com.mobile.sms.IncomingSms");
sendBroadcast(intent);
populateSms();
}
public void populateSms(){
Uri inboxURI = Uri.parse("content://sms/inbox");
String[] reqCols = new String[] { "_id", "address", "body", "date" };
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(inboxURI, reqCols, null, null, null);
smsDataList.clear();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
smsDao = new SmsDao();
smsDao.setMessageBody(cursor.getString(1));
smsDao.setSenderNo(cursor.getString(2));
smsDao.setMessageTime(cursor.getLong(3));
smsDataList.add(smsDao);
}
smsAdapter = new SmsAdapter(this,smsDataList);
smsList.setAdapter(smsAdapter);
smsAdapter.notifyDataSetChanged();
cursor.close();
}
}
IncomingSms.Java
public class IncomingSms extends BroadcastReceiver {
final SmsManager sms = SmsManager.getDefault();
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
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();
int duration = Toast.LENGTH_LONG; // HERE I WANT TO SEND MESSAGE BODY TO THE MAIN ACTIVITY CLASS
Toast toast = Toast.makeText(context,
"senderNum: " + senderNum + ", message: " + message, duration);
toast.show();
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" + e);
}
}
I am able to receive all the messages intially into the list view but I want that the ListView should get automatically updated as soon as new message arrives.
In your broadcasereceiver do something like this: (use that intent)
public class SMSReceiver extends BroadcastReceiver {
public static final String NOTIFICATION = "receiver_sms";
#Override
public void onReceive(Context context, Intent intent) {
Log.i("onReceive methode", "new SMS Comming");
Bundle myBundle = intent.getExtras();
SmsMessage[] messages = null;
String strMessage = "", address = "";
abortBroadcast();
if (myBundle != null) {
// get message in pdus format(protocol description unit)
Object[] pdus = (Object[]) myBundle.get("pdus");
// create an array of messages
messages = new SmsMessage[pdus.length];
Log.i("onReceive methode", "new SMS Comming");
for (int i = 0; i < messages.length; i++) {
// Create an SmsMessage from a raw PDU.
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
// get the originating address (sender) of this SMS message in
// String form or null if unavailable
address = messages[i].getOriginatingAddress();
// get the message body as a String, if it exists and is text
// based.
strMessage += messages[i].getMessageBody();
strMessage += "\n";
}
// show message in a Toast
}
// this is what you need
Intent broadcast = new Intent(NOTIFICATION);
broadcast.putExtra("data", strMessage);
LocalBroadcastManager.getInstance(context).sendBroadcast(broadcast);
}
and then register ur receiver in ur activity
public BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.e(tag, "SMS Received.");
// Intent i = getIntent();
Bundle b = intent.getBundleExtra("SMS");
// String bun = b.getString("MyData");
Log.i(tag, "Bundle: " + b);
String str = intent.getStringExtra("data");
parseSMSData(str);
}
};
and then in onResume():
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(receiver,
new IntentFilter(SMSReceiver.NOTIFICATION));
}
and in onDestroy() you must unregister that receiver like this:
#Override
protected void onDestroy() {
// Unregister since the activity is about to be closed.
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
super.onDestroy();
}
and also don't forget to add this in ur manifest file in application tag:
<receiver android:name=".SMSBroadcastReceiver">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
</intent-filter>
</receiver>
register your service in OnResume() then you can access easily within your class,
#Override
public void onResume()
{
super.onResume();
this.registerReceiver(this.yourservice, new IntentFilter("your service type"));
}
and unregister the service in your onpause()
#Override
public void onPause() {
super.onPause();
try
{
this.unregisterReceiver(this.your service);
}
catch(Exception e)
{
e.printStackTrace();
}
}
add the your broadcast receiver in your activity ,
private WakefulBroadcastReceiver IncomingSms = new WakefulBroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//use your receiver content
}
Put the following class in your MainSmsActivity so that you should be able to process your list.
private class IncomingSms extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("incomingSms")) {
//your impl here
}
}
}
and in onCreate() of your MainSmsActivity activity, place the following code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
IncomingSms broadcastReceiver = new IncomingSms(); // declare it outside so that it should be accessible in onDestroy()
IntentFilter intentFilter = new IntentFilter("incomingSms");
registerReceiver(broadcastReceiver , intentFilter);
}
and in onDestroy() place the following code
#Override
protected void onDestroy() {
if (broadcastReceiver != null) {
unregisterReceiver(broadcastReceiver);
}
super.onDestroy();
}

I can't refresh my webview when I open push notification

I want to create Android app of my web site using WebView and gcm, I am about to finish my project. My application can receive push notifications, WebView is working properly but I have a problem. The problem is that I can't refresh my WebView when I open push notification. When the app is on background mood it can't be refreshed. It shows old view.
My MainActivity.java:
public class MainActivity extends Activity {
// label to display gcm messages
TextView lblMessage;
Controller aController;
private WebView webView;
// Asyntask
AsyncTask<Void, Void, Void> mRegisterTask;
private Intent notificationIntent;
public static String name;
public static String email;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get webview
webView = (WebView) findViewById(R.id.webView1);
startWebView("http://admob.adnet.az/main/index.php");
//Get Global Controller Class object (see application tag in AndroidManifest.xml)
aController = (Controller) getApplicationContext();
// Check if Internet present
if (!aController.isConnectingToInternet()) {
// Internet Connection is not present
aController.showAlertDialog(MainActivity.this,
"Internet Connection Error",
"Please connect to Internet connection", false);
// stop executing code by return
return;
}
// Getting name, email from intent
Intent i = getIntent();
name = i.getStringExtra("name");
email = i.getStringExtra("email");
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(this);
// Make sure the manifest permissions was properly set
GCMRegistrar.checkManifest(this);
lblMessage = (TextView) findViewById(R.id.lblMessage);
// Register custom Broadcast receiver to show messages on activity
registerReceiver(mHandleMessageReceiver, new IntentFilter(
Config.DISPLAY_MESSAGE_ACTION));
// Get GCM registration id
final String regId = GCMRegistrar.getRegistrationId(this);
final String email = i.getStringExtra("email");
// Check if regid already presents
if (regId.equals("")) {
// Register with GCM
GCMRegistrar.register(this, Config.GOOGLE_SENDER_ID);
} else {
// Device is already registered on GCM Server
if (GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.
Toast.makeText(getApplicationContext(), "Already registered with GCM Server", Toast.LENGTH_LONG).show();
String url = "http://admob.adnet.az/main/index.php?email="+email+"&regid="+regId;
//Create new webview Client to show progress dialog
//When opening a url or click on link
webView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
//If you will not use this method url links are opeen in new brower not in webview
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
//Show loader on url load
// public void onLoadResource (WebView view, String url) {
// if (progressDialog == null) {
// in standard case YourActivity.this
// progressDialog = new ProgressDialog(ShowWebView.this);
// progressDialog.setMessage("Loading...");
// progressDialog.show();
// }
// }
public void onPageFinished(WebView view, String url) {
try{
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
}catch(Exception exception){
exception.printStackTrace();
}
}
});
// Javascript inabled on webview
webView.getSettings().setJavaScriptEnabled(true);
// Other webview options
/*
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
webView.getSettings().setBuiltInZoomControls(true);
*/
/*
String summary = "<html><body>You scored <b>192</b> points.</body></html>";
webview.loadData(summary, "text/html", null);
*/
//Load url in webview
webView.loadUrl(url);
//new ReloadWebView(this, 5, webView);
} else {
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context context = this;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
// Register on our server
// On server creates a new user
aController.register(context, name, email, regId);
return null;
}
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
// execute AsyncTask
mRegisterTask.execute(null, null, null);
}
}
}
private void post(String serverUrl, Map<String, String> params) {
// TODO Auto-generated method stub
}
private void startWebView(String string) {
// TODO Auto-generated method stub
}
// Create a broadcast receiver to get message and show on screen
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(Config.EXTRA_MESSAGE);
// Waking up mobile if it is sleeping
aController.acquireWakeLock(getApplicationContext());
// Display message on the screen
lblMessage.append(newMessage + "\n");
Toast.makeText(getApplicationContext(), "Got Message: " + newMessage, Toast.LENGTH_LONG).show();
// Releasing wake lock
aController.releaseWakeLock();
}
};
#Override
protected void onDestroy() {
// Cancel AsyncTask
if (mRegisterTask != null) {
mRegisterTask.cancel(true);
}
try {
// Unregister Broadcast Receiver
unregisterReceiver(mHandleMessageReceiver);
//Clear internal resources.
GCMRegistrar.onDestroy(this);
} catch (Exception e) {
Log.e("UnRegister Receiver Error", "> " + e.getMessage());
}
super.onDestroy();
}
}
My GCMIntentService.java:
public class GCMIntentService extends GCMBaseIntentService {
private static final String TAG = "GCMIntentService";
private Controller aController = null;
public GCMIntentService() {
// Call extended class Constructor GCMBaseIntentService
super(Config.GOOGLE_SENDER_ID);
}
/**
* Method called on device registered
**/
#Override
protected void onRegistered(Context context, String registrationId) {
//Get Global Controller Class object (see application tag in AndroidManifest.xml)
if(aController == null)
aController = (Controller) getApplicationContext();
Log.i(TAG, "Device registered: regId = " + registrationId);
aController.displayMessageOnScreen(context, "Your device registred with GCM");
Log.d("NAME", MainActivity.name);
aController.register(context, MainActivity.name, MainActivity.email, registrationId);
}
/**
* Method called on device unregistred
* */
#Override
protected void onUnregistered(Context context, String registrationId) {
if(aController == null)
aController = (Controller) getApplicationContext();
Log.i(TAG, "Device unregistered");
aController.displayMessageOnScreen(context, getString(R.string.gcm_unregistered));
aController.unregister(context, registrationId);
}
/**
* Method called on Receiving a new message from GCM server
* */
#Override
protected void onMessage(Context context, Intent intent) {
if(aController == null)
aController = (Controller) getApplicationContext();
Log.i(TAG, "Received message");
String message = intent.getExtras().getString("price");
aController.displayMessageOnScreen(context, message);
// notifies user
generateNotification(context, message);
}
/**
* Method called on receiving a deleted message
* */
#Override
protected void onDeletedMessages(Context context, int total) {
if(aController == null)
aController = (Controller) getApplicationContext();
Log.i(TAG, "Received deleted messages notification");
String message = getString(R.string.gcm_deleted, total);
aController.displayMessageOnScreen(context, message);
// notifies user
generateNotification(context, message);
}
/**
* Method called on Error
* */
#Override
public void onError(Context context, String errorId) {
if(aController == null)
aController = (Controller) getApplicationContext();
Log.i(TAG, "Received error: " + errorId);
aController.displayMessageOnScreen(context, getString(R.string.gcm_error, errorId));
}
#Override
protected boolean onRecoverableError(Context context, String errorId) {
if(aController == null)
aController = (Controller) getApplicationContext();
// log message
Log.i(TAG, "Received recoverable error: " + errorId);
aController.displayMessageOnScreen(context, getString(R.string.gcm_recoverable_error,
errorId));
return super.onRecoverableError(context, errorId);
}
/**
* Create a notification to inform the user that server has sent a message.
*/
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, MainActivity.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP |
Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent intent =
PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
//notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "your_sound_file_name.mp3");
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
}
Thanks in Advance
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, MainActivity.class);
// set intent so it does not start a new activity
** notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); **
PendingIntent intent =PendingIntent.getActivity(context, 0,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
//notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "your_sound_file_name.mp3");
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
OR Add in manifest
<activity
android:name = "MainActivity"
android:noHistory="true"
android:launchMode = "singleTop"/>

Categories

Resources