unable to get the notification when the messsage arrives from gcm android - android

Example: In my application I have client,distributors and server.client ask questions to server and server will reply for that question via Gcm push notification.I have implemented this by googling it and push notification tutorials.
And my issue is, if I send a question from client,it gets displayed in server by parsing the link but I'm not getting the push notification. any one help me with this.I don't know where I have done mistake. Any suggestion to implement this functionality via push notification. server side script is write in php
I have posted the server part code...here only i want the push notification
my GCM class
import java.util.Timer;
import java.util.TimerTask;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.RingtoneManager;
import android.os.PowerManager;
import android.util.Log;
import android.widget.Toast;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import com.google.android.gcm.GCMBaseIntentService;
public class GCMIntentService extends GCMBaseIntentService
{
private static final String TAG = "GCM Tutorial::Service";
// Use your PROJECT ID from Google API into SENDER_ID
public static final String SENDER_ID = "projectid";
//SharedPreferences prefs;
//DbHelper db;
String xx = "";
public GCMIntentService() {
super(SENDER_ID);
}
#Override
protected void onRegistered(Context context, String registrationId) {
//prefs = this.getSharedPreferences("", Context.MODE_PRIVATE);
//SharedPreferences.Editor prefsEditor = prefs.edit();
//prefsEditor.putString("registrationid", registrationId);
//prefsEditor.commit();
Log.i(TAG, "onRegistered: registrationId=" + registrationId);
xx = registrationId;
Toast.makeText(getApplicationContext(), xx, Toast.LENGTH_LONG).show();
System.out.println("Register : "+registrationId);
}
#Override
protected void onUnregistered(Context context, String registrationId) {
Log.i(TAG, "onUnregistered: registrationId=" + registrationId);
}
#SuppressLint("NewApi")
#Override
protected void onMessage(Context context, Intent data) {
//db = new DbHelper(context);
//db.openToWrite();
String message;
// Message from PHP server
message = data.getStringExtra("message");
// Open a new activity called GCMMessageView
//db.insertmessage(message);
System.out.println("inside gcm class");
Intent intent = new Intent(this, MainActivity.class);
// Pass data to the new activity
intent.putExtra("message", message);
// Starts the activity on notification click
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
// Create the notification with a notification builder
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setWhen(System.currentTimeMillis())
.setContentTitle("New message")
.setContentText(message).setContentIntent(pIntent)
.getNotification();
// Remove the notification on click
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.sound =
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notification.defaults |= Notification.DEFAULT_VIBRATE;
NotificationManager manager = (NotificationManager)context.getSystemService(NOTIFICATION_SERVICE);
manager.notify(R.string.app_name, notification);
{
// Wake Android Device when notification received
PowerManager pm = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
final PowerManager.WakeLock mWakelock = pm.newWakeLock(
PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP, "GCM_PUSH");
mWakelock.acquire();
// Timer before putting Android Device to sleep mode.
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
mWakelock.release();
}
};
timer.schedule(task, 5000);
}
}
#Override
protected void onError(Context arg0, String errorId) {
Log.e(TAG, "onError: errorId=" + errorId);
}
}
question class
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class prompt extends Activity
{
Button prompt_ok,prompt_cancel;
private static final String url="http://maps.googleapis.com/maps/api/geocode/json?address=";
private static final String url1="&sensor=false";
EditText zip,noofsup;
JSONArray results;
JSONObject geometry,location;
String latt,lngg,ques;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent in=getIntent();
ques=in.getStringExtra("questionfornext");
setContentView(R.layout.prompt);
zip=(EditText)findViewById(R.id.zipcode);
noofsup=(EditText)findViewById(R.id.noofsupplier);
}
public void onClick(View view)
{
String zipcode=zip.getText().toString();
String finalurl=url+zipcode+url1;
new GetData().execute();
new GetRegister().execute();
new GetQuestion().execute();
Intent in=new Intent(getApplicationContext(),MainActivity.class);
startActivity(in);
setContentView(R.layout.activity_main);
}
public void onCancel(View v)
{
Intent in=new Intent(getApplicationContext(),MainActivity.class);
startActivity(in);
setContentView(R.layout.activity_main);
}
private class GetData extends AsyncTask<Void, Void, Void>
{
String status;
String zipcode=zip.getText().toString();
String finalurl=url+zipcode+url1;
#Override
protected void onPreExecute()
{
super.onPreExecute();
// Showing progress dialog
}
#Override
protected Void doInBackground(Void... arg0)
{
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(finalurl, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null)
{
try
{
JSONObject jsonObj = new JSONObject(jsonStr);
status=jsonObj.getString("status");
System.out.println("status"+status);
results=jsonObj.getJSONArray("results");
for(int j=0;j==0;j++)
{
JSONObject c=results.getJSONObject(0);
geometry=c.getJSONObject("geometry");
JSONObject ob=geometry.getJSONObject("location");
latt=ob.getString("lat");
lngg=ob.getString("lng");
// String latt=location.getString("lat");
//String lngg=location.getString("lng");
System.out.println("latt"+latt);
System.out.println("lng"+lngg);
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
else
{
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
if(status.equals("OK"))
{
new GetRegister().execute();
//Toast.makeText(getApplicationContext(), msg1, Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Enter Valid ZIP", Toast.LENGTH_LONG).show();
}
}
}
private class GetRegister extends AsyncTask<Void, Void, Void>
{
//String android_id = Secure.getString(getContentResolver(),Secure.ANDROID_ID);
String weburl="register url ";//if we ask question it will automatically register
String weburl1="&latitude=";
String weburl2="&longtitude=";
String weburl3="&type=Android&author=Jers&Submit=submit";
String code,msg;
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
ServiceHandler sh=new ServiceHandler();
String finalweburl=weburl+MainActivity.androidId+weburl1+latt+weburl2+lngg+weburl3;
System.out.println("new final web url----////"+finalweburl);
String str=sh.makeServiceCall(finalweburl,ServiceHandler.GET);
if(str!=null)
{
try
{
JSONObject obj=new JSONObject(str);
code=obj.getString("code");
msg=obj.getString("msg");
System.out.println("jewellery id-----"+MainActivity.androidId);
System.out.println("code-----"+code);
}
catch(JSONException e)
{
e.printStackTrace();
}
}
else
{
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
if(code.equals("1"))
{
new GetQuestion().execute();
Toast.makeText(getApplicationContext(), "Registered", Toast.LENGTH_SHORT).show();
}
else
{
// Toast.makeText(getApplicationContext(),"NOT a question", Toast.LENGTH_LONG).show();
}
}
}
private class GetQuestion extends AsyncTask<Void, Void, Void>
{
EditText question1=(EditText)findViewById(R.id.question);
String success,msg1;
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
String noofsupplier=noofsup.getText().toString();
ServiceHandler sh=new ServiceHandler();
String android_id = Secure.getString(getContentResolver(),Secure.ANDROID_ID);
String url="request url for distributor ";
String url1="&question=";
String url2="&no_of_suppliers=";
String finalurlq1=url+android_id+url1+ques+url2+noofsupplier;
String finalurlq=new String(finalurlq1.replaceAll(" ","%20"));
System.out.println(finalurlq);
System.out.println("question---->"+ques);
String str1=sh.makeServiceCall(finalurlq,ServiceHandler.GET);
if(str1!=null)
{
try
{
JSONObject ob=new JSONObject(str1);
JSONObject ob1=ob.getJSONObject("response");
success=ob1.getString("success");
msg1=ob1.getString("msg");
System.out.println("success---->"+success);
System.out.println("msg----->"+msg1);
}
catch(JSONException e)
{
e.printStackTrace();
}
}
else
{
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
// Dismiss the progress dialog
// if (pDialog.isShowing())
// pDialog.dismiss();
/* * Updating parsed JSON data into ListView**/
if(success.equals("1"))
{
Toast.makeText(getApplicationContext(), "Question is Registered", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "Question not registered", Toast.LENGTH_SHORT).show();
}
}
}
}

Related

Cordova Android Push Plugin

I am trying to create push notification for my cordova project. I followed the tutorial from this link http://devgirl.org/2012/10/25/tutorial-android-push-notifications-with-phonegap/ and created the plugin and I see the FCM is not sending back the registration id. I have added sender id in my application. Please help me to get this done. Thanks in advance.
GCMIntentService.java
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import com.google.android.gcm.GCMBaseIntentService;
#SuppressLint("NewApi")
public class GCMIntentService extends GCMBaseIntentService {
private static final String TAG = "GCMIntentService";
public GCMIntentService() {
super("GCMIntentService");
}
#Override
public void onRegistered(Context context, String regId) {
Log.v(TAG, "onRegistered: "+ regId);
JSONObject json;
try
{
json = new JSONObject().put("event", "registered");
json.put("regid", regId);
Log.v(TAG, "onRegistered: " + json.toString());
// Send this JSON data to the JavaScript application above EVENT should be set to the msg type
// In this case this is the registration ID
PushPlugin.sendJavascript( json );
}
catch( JSONException e)
{
// No message to the user is sent, JSON failed
Log.e(TAG, "onRegistered: JSON exception");
}
}
#Override
public void onUnregistered(Context context, String regId) {
Log.d(TAG, "onUnregistered - regId: " + regId);
}
#Override
protected void onMessage(Context context, Intent intent) {
Log.d(TAG, "onMessage - context: " + context);
// Extract the payload from the message
Bundle extras = intent.getExtras();
if (extras != null)
{
// if we are in the foreground, just surface the payload, else post it to the statusbar
if (PushPlugin.isInForeground()) {
extras.putBoolean("foreground", true);
createNotification(context, extras);
PushPlugin.sendExtras(extras);
}
else {
extras.putBoolean("foreground", false);
// Send a notification if there is a message
if (extras.getString("message") != null && extras.getString("message").length() != 0) {
createNotification(context, extras);
}
}
}
}
public void createNotification(Context context, Bundle extras)
{
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String appName = getAppName(this);
Intent notificationIntent = new Intent(this, PushHandlerActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
notificationIntent.putExtra("pushBundle", extras);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
int defaults = Notification.DEFAULT_ALL;
if (extras.getString("defaults") != null) {
try {
defaults = Integer.parseInt(extras.getString("defaults"));
} catch (NumberFormatException e) {}
}
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setDefaults(defaults)
.setSmallIcon(context.getApplicationInfo().icon)
.setWhen(System.currentTimeMillis())
.setContentTitle(extras.getString("title"))
.setContentText(extras.getString("title"))
.setTicker(extras.getString("title"))
.setContentIntent(contentIntent)
.setAutoCancel(true);
String message = extras.getString("message");
if (message != null) {
mBuilder.setContentText(message);
} else {
mBuilder.setContentText("<missing message content>");
}
String msgcnt = extras.getString("msgcnt");
if (msgcnt != null) {
mBuilder.setNumber(Integer.parseInt(msgcnt));
}
int notId = 0;
try {
notId = Integer.parseInt(extras.getString("notId"));
}
catch(NumberFormatException e) {
Log.e(TAG, "Number format exception - Error parsing Notification ID: " + e.getMessage());
}
catch(Exception e) {
Log.e(TAG, "Number format exception - Error parsing Notification ID" + e.getMessage());
}
mNotificationManager.notify((String) appName, notId, mBuilder.build());
}
private static String getAppName(Context context)
{
CharSequence appName =
context
.getPackageManager()
.getApplicationLabel(context.getApplicationInfo());
return (String)appName;
}
#Override
public void onError(Context context, String errorId) {
Log.e(TAG, "onError - errorId: " + errorId);
}
}
PushPlugin.Java
import java.util.Iterator;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.android.gcm.GCMRegistrar;
import android.os.Bundle;
import android.util.Log;
public class PushPlugin extends Plugin {
public static final String TAG = "PushPlugin";
public static final String REGISTER = "register";
public static final String UNREGISTER = "unregister";
public static final String EXIT = "exit";
private static CordovaWebView gWebView;
private static String gECB;
private static String gSenderID;
private static Bundle gCachedExtras = null;
private static boolean gForeground = false;
#Override
public PluginResult execute(String action, JSONArray data, String CallbackContext) {
// TODO Auto-generated method stub
boolean result = false;
Log.v(TAG, "execute: action=" + action);
if (REGISTER.equals(action)) {
Log.v(TAG, "execute: data=" + data.toString());
try {
JSONObject jo = data.getJSONObject(0);
gWebView = this.webView;
Log.v(TAG, "execute: jo=" + jo.toString());
gECB = (String) jo.get("ecb");
gSenderID = (String) jo.get("senderID");
Log.v(TAG, "execute: ECB=" + gECB + " senderID=" + gSenderID);
GCMRegistrar.register(this.cordova.getActivity(), gSenderID);
result = true;
// callbackContext.success();
} catch (JSONException e) {
Log.e(TAG, "execute: Got JSON Exception " + e.getMessage());
result = false;
// callbackContext.error(e.getMessage());
}
if ( gCachedExtras != null) {
Log.v(TAG, "sending cached extras");
sendExtras(gCachedExtras);
gCachedExtras = null;
}
}else if (UNREGISTER.equals(action)) {
GCMRegistrar.unregister(this.cordova.getActivity());
Log.v(TAG, "UNREGISTER");
result = true;
// callbackContext.success();
} else {
result = false;
Log.e(TAG, "Invalid action : " + action);
//callbackContext.error("Invalid action : " + action);
}
return new PluginResult(PluginResult.Status.OK);
//return null;
}
public static void sendExtras(Bundle extras)
{
if (extras != null) {
if (gECB != null && gWebView != null) {
sendJavascript(convertBundleToJson(extras));
} else {
Log.v(TAG, "sendExtras: caching extras to send at a later time.");
gCachedExtras = extras;
}
}
}
private static JSONObject convertBundleToJson(Bundle extras)
{
try
{
JSONObject json;
json = new JSONObject().put("event", "message");
JSONObject jsondata = new JSONObject();
Iterator<String> it = extras.keySet().iterator();
while (it.hasNext())
{
String key = it.next();
Object value = extras.get(key);
// System data from Android
if (key.equals("from") || key.equals("collapse_key"))
{
json.put(key, value);
}
else if (key.equals("foreground"))
{
json.put(key, extras.getBoolean("foreground"));
}
else if (key.equals("coldstart"))
{
json.put(key, extras.getBoolean("coldstart"));
}
else
{
// Maintain backwards compatibility
if (key.equals("message") || key.equals("msgcnt") || key.equals("soundname"))
{
json.put(key, value);
}
if ( value instanceof String ) {
// Try to figure out if the value is another JSON object
String strValue = (String)value;
if (strValue.startsWith("{")) {
try {
JSONObject json2 = new JSONObject(strValue);
jsondata.put(key, json2);
}
catch (Exception e) {
jsondata.put(key, value);
}
// Try to figure out if the value is another JSON array
}
else if (strValue.startsWith("["))
{
try
{
JSONArray json2 = new JSONArray(strValue);
jsondata.put(key, json2);
}
catch (Exception e)
{
jsondata.put(key, value);
}
}
else
{
jsondata.put(key, value);
}
}
}
} // while
json.put("payload", jsondata);
Log.v(TAG, "extrasToJSON: " + json.toString());
return json;
}
catch( JSONException e)
{
Log.e(TAG, "extrasToJSON: JSON exception");
}
return null;
}
public static void sendJavascript(JSONObject _json) {
String _d = "javascript:" + gECB + "(" + _json.toString() + ")";
Log.v(TAG, "sendJavascript: " + _d);
if (gECB != null && gWebView != null) {
gWebView.sendJavascript(_d);
}
}
public static boolean isInForeground()
{
return gForeground;
}
public static boolean isActive()
{
return gWebView != null;
}
}
PushHandlerActivity.java
import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
public class PushHandlerActivity extends Activity
{
private static String TAG = "PushHandlerActivity";
/*
* this activity will be started if the user touches a notification that we own.
* We send it's data off to the push plugin for processing.
* If needed, we boot up the main activity to kickstart the application.
* #see android.app.Activity#onCreate(android.os.Bundle)
*/
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Log.v(TAG, "onCreate");
boolean isPushPluginActive = PushPlugin.isActive();
processPushBundle(isPushPluginActive);
finish();
if (!isPushPluginActive) {
forceMainActivityReload();
}
}
/**
* Takes the pushBundle extras from the intent,
* and sends it through to the PushPlugin for processing.
*/
private void processPushBundle(boolean isPushPluginActive)
{
Bundle extras = getIntent().getExtras();
if (extras != null) {
Bundle originalExtras = extras.getBundle("pushBundle");
originalExtras.putBoolean("foreground", false);
originalExtras.putBoolean("coldstart", !isPushPluginActive);
PushPlugin.sendExtras(originalExtras);
}
}
/**
* Forces the main activity to re-launch if it's unloaded.
*/
private void forceMainActivityReload()
{
PackageManager pm = getPackageManager();
Intent launchIntent = pm.getLaunchIntentForPackage(getApplicationContext().getPackageName());
startActivity(launchIntent);
}
#Override
protected void onResume() {
super.onResume();
final NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancelAll();
}
}
Manifeast file
<uses-permission android:name="android.permission.BROADCAST_STICKY" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission
android:name="MyPackageName".push.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<activity android:name="MyPackageName".push.PushHandlerActivity"/>
<receiver android:name="MyPackageName".push.CordovaGCMBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="MyPackageName".push" />
</intent-filter>
</receiver>
<service android:name="MyPackageName".push.GCMIntentService" />

BroadCast Receiver makes slowly works to other services

when I listen push message from BroadcastReceiver I can take message but it makes slow other services for example I am sending "Message is taken" to my web service when I take push message but I can't send to my webservice it works very slowly when I listen to BroadcastReceiver for take message and when I delete BroadcastReceiver I can send message to my webservice very fastly
package jsonparse;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.androidhive.pushnotifications.MapsActivity;
import com.androidhive.pushnotifications.R;
import com.androidhive.pushnotifications.ServerUtilities;
import com.androidhive.pushnotifications.WakeLocker;
import com.daasuu.ahp.AnimateHorizontalProgressBar;
import com.google.android.gcm.GCMRegistrar;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static com.androidhive.pushnotifications.CommonUtilities.DISPLAY_MESSAGE_ACTION;
import static com.androidhive.pushnotifications.CommonUtilities.EXTRA_MESSAGE;
import static com.androidhive.pushnotifications.CommonUtilities.SENDER_ID;
public class ListViewAdapter extends BaseAdapter implements OnClickListener{
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
//ProgressBar mprogressBar;
TextView fulness;
TextView location_info;
TextView descrip;
JSONObject jsonobject;
private Handler mHandler = new Handler();
private int mProgressStatus=0;
String get_enlem,get_boylam;
double dble_get_enlem,dble_get_boylam;
String dest_city_name,dest_state_name,dest_country_name;
NetworkInfo ni;
ConnectivityManager cm;
String get_location;
String device_id;
String sonuc;
SharedPreferences prefs;
String get_groupID, get_customerID;
String get_desc;
String get_toplam;
// Asyntask
AsyncTask<Void, Void, Void> mRegisterTask;
public static String name;
public static String email;
Context con;
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
/*
TextView rank;
TextView country;
TextView population;
ImageView flag;
*/
TextView location;
AnimateHorizontalProgressBar progressBar;
Button cop_toplandi;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
//rank = (TextView) itemView.findViewById(R.id.rank);
//country = (TextView) itemView.findViewById(R.id.country);
//population = (TextView) itemView.findViewById(R.id.population);
//Get Device IMEI number
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
device_id = telephonyManager.getDeviceId();
Log.i("IMEI NUMBER", device_id);
// Getting name, email from intent
Intent i = ((Activity) context).getIntent();
name = i.getStringExtra("get_message_name");
email = i.getStringExtra("email");
Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(context);
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(context);
context.registerReceiver(mHandleMessageReceiver, new IntentFilter(
DISPLAY_MESSAGE_ACTION));
// Get GCM registration id
final String regId = GCMRegistrar.getRegistrationId(context);
// Check if regid already presents
if (regId.equals("")) {
// Registration is not present, register now with GCM
GCMRegistrar.register(context, SENDER_ID);
} else {
// Device is already registered on GCM
if (GCMRegistrar.isRegisteredOnServer(context)) {
// Skips registration.
// Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG).show();
} else {
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context contextm = context;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
// Register on our server
// On server creates a new user
ServerUtilities.register(contextm, name, email, regId);
return null;
}
#Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
}
}
}
};
handler.postDelayed(r, 1000);
prefs = context.getSharedPreferences("login_page", context.MODE_PRIVATE);
get_groupID = prefs.getString("user_groupID", "alınmadı");
get_customerID = prefs.getString("user_customerID", "alınmadı");
if (get_groupID.equals("null")) {
get_groupID = "0";
}
if (get_customerID.equals("null")) {
get_customerID = "0";
}
location = (TextView) itemView.findViewById(R.id.location);
progressBar = (AnimateHorizontalProgressBar) itemView.findViewById(R.id.animate_progress_bar);
fulness = (TextView) itemView.findViewById(R.id.txt_percentage_of_fulness);
descrip = (TextView) itemView.findViewById(R.id.txt_desc);
get_location = resultp.get(MainActivity.COUNTRY);
cop_toplandi = (Button) itemView.findViewById(R.id.secret_button);
cop_toplandi.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context.getApplicationContext(),"Başarıyla Gönderildi",Toast.LENGTH_SHORT).show();
new Send_save_status().execute();
}
});
location_info = (TextView) itemView.findViewById(R.id.location_info);
// Locate the ImageView in listview_item.xml
//flag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
//rank.setText(resultp.get(MainActivity.RANK));
//country.setText(resultp.get(MainActivity.COUNTRY));
//population.setText(resultp.get(MainActivity.POPULATION));
location.setText(resultp.get(MainActivity.COUNTRY));
location_info.setText(resultp.get(MainActivity.Location_info));
String get_descrip = resultp.get(MainActivity.DESCB);
if(get_descrip != "0"){
descrip.setText(resultp.get(MainActivity.DESCB));
cop_toplandi.setVisibility(View.VISIBLE);
}
get_enlem = resultp.get(MainActivity.POPULATION);
get_boylam = resultp.get(MainActivity.FLAG);
get_toplam = resultp.get(MainActivity.Toplam);
//dble_get_enlem = Double.parseDouble(get_enlem);
//dble_get_boylam = Double.parseDouble(get_boylam);
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
//imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), flag);
// Capture ListView item click
String a = resultp.get(MainActivity.RANK);
int b = Integer.parseInt(a);
progressBar.setMax(100);
progressBar.setProgress(b);
//progressBar.setProgressWithAnim(b);
fulness.setText("%"+(b*1));
//mprogressBar = (ProgressBar) itemView.findViewById(R.id.progressBar);
//mprogressBar.setProgress(b);
/*
ObjectAnimator anim = ObjectAnimator.ofInt(mprogressBar, "progress", 0, 80);
anim.setDuration(5000);
anim.setInterpolator(new DecelerateInterpolator());
anim.start();
*/
/*
//Get location name from latitude and longitude
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(dble_get_enlem, dble_get_boylam, 1);
} catch (IOException e) {
e.printStackTrace();
}
dest_city_name = addresses.get(0).getAddressLine(0);
dest_state_name = addresses.get(0).getAddressLine(1);
dest_country_name = addresses.get(0).getAddressLine(2);
location_info.setText(dest_city_name + " " + dest_country_name);
*/
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
ni = cm.getActiveNetworkInfo();
if (ni != null && ni.isConnected()) {
Toast.makeText(context,context.getString(R.string.progressdialog_message), Toast.LENGTH_SHORT).show();
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, MapsActivity.class);
// Pass all data rank
intent.putExtra("level", resultp.get(MainActivity.RANK));
// Pass all data country
intent.putExtra("imei", resultp.get(MainActivity.COUNTRY));
// Pass all data population
intent.putExtra("enlem",resultp.get(MainActivity.POPULATION));
// Pass all data flag
intent.putExtra("boylam", resultp.get(MainActivity.FLAG));
// Start SingleItemView Class
context.startActivity(intent);
}else{
Toast.makeText(context.getApplicationContext(),context.getApplicationContext().getString(R.string.network_connection),Toast.LENGTH_SHORT).show();
}
}
});
return itemView;
}
#Override
public void onClick(View v) {
switch (v.getId()){
}
}
/**
* Receiving push messages
* */
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
// Waking up mobile if it is sleeping
WakeLocker.acquire(context);
//context.sendBroadcast(new Intent("com.google.android.intent.action.GTALK_HEARTBEAT"));
//context.sendBroadcast(new Intent("com.google.android.intent.action.MCS_HEARTBEAT"));
// Showing received message
//lblMessage.append(newMessage + "\n");
//Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();
//descrip.setText(newMessage);
// Intent go = new Intent(context.getApplicationContext(),IsEmri.class);
//context.startActivity(go);
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Acil Durum!!!");
builder.setMessage(newMessage)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// TODO: handle the OK
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
// Releasing wake lock
WakeLocker.release();
}
};
/*
Send GroupID and customerID every five minutes to services
*/
private class Send_save_status extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
}
#Override
protected Void doInBackground(Void... params) {
//Toast.makeText(getApplicationContext(), getApplicationContext().getString(R.string.gprs_adres) + address, Toast.LENGTH_LONG).show();
// make sure you close the gps after using it. Save user's battery power
//mGPSService.closeGPS();
StringBuilder str_url = new StringBuilder();
str_url.append("http://78.186.62.169:8090/TrackBinSvc.svc/saveStatus/");
Log.i("str_url1", "" + str_url);
str_url.append(device_id + "/");
Log.i("strl_url2", "" + str_url);
str_url.append(get_location + "/");
Log.i("strl_url3", "" + str_url);
str_url.append("opened" + "/");
Log.i("strl_url3", "" + str_url);
str_url.append(get_groupID + "/");
Log.i("strl_url3", "" + str_url);
str_url.append(get_customerID);
Log.i("strl_url3", "" + str_url);
String str = str_url.toString();
//"http://192.168.0.39:8090/TrackBinSvc.svc/Get_All_Mobile/admin/1234"
try {
jsonobject = JSONfunctions
.getJSONfromURL(str);
// Locate the array name in JSON
sonuc = jsonobject.getString("SendUpdateCordinatesResult");
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
}
}
}
Problem is: The broadcast receiver that you are registering is implemented on the Main thread. The broadcast receiver handler is ALWAYS EXECUTED ON THE MAIN THREAD, thus, making your entire process slower. To implement receiver's own thread, you can explicitly do so by providing it's own Handler thread.
Register your broadcast receiver like this:
HandlerThread receiverHandlerThread = new HandlerThread("threadName");
receiverHandlerThread.start();
Looper looper = receiverHandlerThread.getLooper();
Handler handler = new Handler(looper);
context.registerReceiver(mHandleMessageReceiver,newIntentFilter(DISPLAY_MESSAGE_ACTION),null,handler);

How to make notification appear only in top?

So I have this code
public class notif extends Activity {
private static final int NOTIFY_ME_ID=1337;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final NotificationManager mgr=(NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
Notification note=new Notification(R.drawable.icon,"New Problem ",System.currentTimeMillis());
note.flags|=Notification.FLAG_AUTO_CANCEL;
PendingIntent i=PendingIntent.getActivity(this, 0,new Intent(this,list.class), 0);
note.setLatestEventInfo(this,"Problem Occured","Click to see the problem",i);
mgr.notify(NOTIFY_ME_ID,note);
}
This code is about making notifications but i want it to just appear on my notification on top an not opening any page at first so it's like the notification can appear in the main menu without opening any page at first like.the sms notification that appear on top only without having to see the entire sms until we click the notification so can someone help me with this? :)
Create a class NotificationAlert and paste the code below there:
import android.os.Bundle;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
public class NotificationAlert extends Activity {
private static final int NOTIFY_ME_ID=1337;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notification_alert);
/*********** Create notification ***********/
final NotificationManager mgr=
(NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
Notification note=new Notification(R.drawable.stat_notify_chat,
"Android Example Status message!",
System.currentTimeMillis());
// This pending intent will open after notification click
PendingIntent i=PendingIntent.getActivity(this, 0,
new Intent(this, NotifyMessage.class),
0);
note.setLatestEventInfo(this, "Android Example Notification Title",
"This is the android example notification message", i);
//After uncomment this line you will see number of notification arrived
//note.number=2;
mgr.notify(NOTIFY_ME_ID, note);
}
}
Create a class NotifyMessage and paste the code below there:
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class NotifyMessage extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView txt=new TextView(this);
txt.setText("Activity after click on notification");
setContentView(txt);
}
}
I think I know now that i have to use service and this is the code for making that service hope it helps other
public class servicenotif extends Service {
private static final String TAG = "servicenotif";
private static final int NOTIFY_ME_ID=1337;
private String url="Your URL";
SharedPreferences mPrefs;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
//Untuk bikin alarm yang ngecek ke database setiap 30 detik
Log.d(TAG, "onCreate");
Intent i = new Intent(this, servicenotif.class);
PendingIntent pintent = PendingIntent.getService(this, 0, i,0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 30*1000, pintent);
}
#Override
public void onStart(Intent intent, int startId) {
//buat preference
new LoginAsyncTask().execute();
//Note: You can start a new thread and use it for long background processing from here.
}
class LoginAsyncTask extends AsyncTask<String, Integer, String> {
String response = "";
ProgressDialog dialog;
//step2
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
//publishProgress(190);
mPrefs = getSharedPreferences("Preference", Context.MODE_PRIVATE);
//ngambil data preference
String txtTransID=mPrefs.getString("tid", "");
if(txtTransID.equals("")){
txtTransID="0";
}
int t=Integer.valueOf(txtTransID);
//membuat notifikasi yang muncul apabila ada problem dan hanya muncul lagi apabila ada problem baru
JSONObject json = JSONfunctions.getJSONfromURL("Your URL");
JSONObject js = JSONfunctions.getJSONfromURL("Your URL");
JSONObject j = JSONfunctions.getJSONfromURL("Your URL");
try{
JSONArray makanan = json.getJSONArray("makanan");
for(int i=0;i<makanan.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonobj = makanan.getJSONObject(i);
map.put("id",jsonobj.getString("Status"));
//mengecek status yang berubah dari nol menjadi 1
if(jsonobj.getString("Status").equals("1")){
JSONArray aku=js.getJSONArray("makanan");
for(int a=0;a<aku.length();a++)
{
HashMap<String, String> mp = new HashMap<String, String>();
JSONObject jsb = aku.getJSONObject(a);
mp.put("take", jsb.getString("Taken"));
//mengecek Taken yang belum diambil
if(jsb.getString("Taken").equals("null")){
JSONArray tid=j.getJSONArray("makanan");
for(int Ti=0;Ti<tid.length();Ti++){
HashMap<String,String> trans=new HashMap<String, String>();
JSONObject jo=tid.getJSONObject(Ti);
trans.put("trans", jo.getString("Trans_ID"));
int TID;
//mengecek Trans_ID yang ditambahkan apa ada yang baru atau tidak
if(jo.getString("Trans_ID").equals("")){
TID=0;
}
else{
TID=Integer.valueOf(jo.getString("Trans_ID"));
}
if(t<TID){
Editor editor = mPrefs.edit();
editor.putString("tid", jo.getString("Trans_ID"));
editor.commit();
map.put("nama", jsonobj.getString("Andon_Type"));
map.put("harga", jsonobj.getString("Line"));
String andon=jsonobj.getString("Andon_Type");
String line=jsonobj.getString("Line");
NotificationManager mgr=(NotificationManager)servicenotif.this.getSystemService(Context.NOTIFICATION_SERVICE);
Notification note=new Notification(R.drawable.icon,"New Problem ",System.currentTimeMillis());
note.flags|=Notification.FLAG_AUTO_CANCEL;
PendingIntent b=PendingIntent.getActivity(servicenotif.this, 0,new Intent(servicenotif.this,list2.class),PendingIntent.FLAG_ONE_SHOT);
note.setLatestEventInfo(servicenotif.this,"Problem Occured","Click to see the list of problem",b);
note.defaults=Notification.DEFAULT_ALL;
mgr.notify(NOTIFY_ME_ID,note);
}
//membuat notifikasi muncul lagi apabila data di reset
else if(t>TID){
Editor editor = mPrefs.edit();
editor.putString("tid", "");
editor.commit();
}
}
}
}
}
}
}
catch(JSONException e){
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
publishProgress(190);
return null;
}
//last step
#Override
protected void onPostExecute(String result) {
//dialog.cancel();
}
private void onCreate(Object object) {
// TODO Auto-generated method stub
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
// biasanya untuk progress download
int nilai = values[0];
// didapat dari publish progress
}
//step1
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
// buat bikin dialog loading
/*dialog = ProgressDialog.show(list.this, "Loading",
"Please wait..");*/
super.onPreExecute();
}
public void write(String fileName){
BufferedWriter bw=null;
try{
bw=new BufferedWriter(new OutputStreamWriter(openFileOutput(fileName,Context.MODE_PRIVATE)));
}
catch(Exception e){
}
}
}
private void getRequest(String Url2) {
// TODO Auto-generated method stub
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try {
HttpResponse response = client.execute(request);
} catch (Exception ex) {
Toast.makeText(this, "Penghandelan Gagal !", Toast.LENGTH_SHORT)
.show();
}
}
private String request(HttpResponse response) {
// TODO Auto-generated method stub
String result = "";
try {
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line + "\n");
}
in.close();
result = str.toString();
} catch (Exception ex) {
result = "Error";
}
return result;
}
#Override
//untuk logout mematikan notifikasi dan alarm supaya tidak menjalankan service lagi
public void onDestroy() {
NotificationManager mgr=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
mgr.cancelAll();
Toast.makeText(this, "Log out successfull", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
PendingIntent i=PendingIntent.getService(this, 0,new Intent(this,servicenotif.class), 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.cancel(i);
}
Hope this will help

onBind() is never called in a service

I am writing a service based app with a bound service, and the service's onBind() method never seems to be called (testing it with Toasts and Logs).
The service:
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import com.gmail.zack.yovel.FlickAround.MyActivity;
import com.gmail.zack.yovel.FlickAround.R;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created with IntelliJ IDEA.
* User: Ziky
* Date: 09/04/13
* Time: 19:06
* To change this template use File | Settings | File Templates.
*/
public class UpdateService extends Service implements LocationListener, UpdatePhotosTask.OnHttpResponseListener {
private final static String API_KEY = "5255c7b02750c0fa4b15bd8ad4ec1fb7";
private final static String GET_PHOTOS_FOR_LOCATION_SCHEMA = "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=" + API_KEY + "&lat=%d&lon=%d&format=json&nojsoncallback=1";
private static final String KEY_PHOTOS = "photos";
private static final String KEY_PHOTO = "photo";
private int NOTIFICATION = R.string.update_service_started;
private NotificationManager mNManager;
private LocationManager mLManager;
private String mProvider;
private Location mLocation;
private IBinder mBinder = new LocalBinder();
private UpdatePhotosTask task;
#Override
public IBinder onBind(Intent intent) {
Toast.makeText(this, "UpdateService.onBind()", Toast.LENGTH_LONG).show();
Log.i("test", "UpdateService.onBind()");
mLManager.requestLocationUpdates(mProvider, 0, 1000, this);
return mBinder;
}
#Override
public void onCreate() {
mNManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
showNotification();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
mLManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
mProvider = mLManager.getBestProvider(criteria, false);
mLocation = mLManager.getLastKnownLocation(mProvider);
return START_STICKY;
}
#Override
public void onDestroy() {
mNManager.cancel(NOTIFICATION);
Toast.makeText(this, R.string.update_service_stoped, Toast.LENGTH_SHORT).show();
}
private void showNotification() {
CharSequence text = getText(R.string.update_service_active);
Notification notification = new Notification(R.drawable.refresh, text, System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MyActivity.class), 0);
notification.setLatestEventInfo(this, getText(R.string.update_service_label), text, contentIntent);
mNManager.notify(NOTIFICATION, notification);
}
#Override
public void onLocationChanged(Location location) {
beginUpdate(location);
}
private void beginUpdate(Location location) {
Toast.makeText(this, "beginning update", Toast.LENGTH_LONG).show();
String url = buildUrl(location);
task = new UpdatePhotosTask(this);
task.execute(url);
}
private String buildUrl(Location location) {
return String.format(GET_PHOTOS_FOR_LOCATION_SCHEMA, location.getLatitude(), location.getLongitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onHttpResponse(ArrayList<String> responses) {
if (responses.size() > 0) {
String response = responses.get(0);
try {
JSONObject jsonObject = new JSONObject(response);
jsonObject = jsonObject.getJSONObject(KEY_PHOTOS);
JSONArray jsonArray = jsonObject.getJSONArray(KEY_PHOTO);
ArrayList<String> photos = new ArrayList<String>();
for (int i = 0, length = jsonArray.length(); i < length; i++) {
jsonObject = jsonArray.getJSONObject(i);
Log.i("photo info", jsonObject.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class LocalBinder extends Binder {
public UpdateService getService() {
return UpdateService.this;
}
}
}
The AsyncTask:
import android.os.AsyncTask;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
/**
* Created with IntelliJ IDEA.
* User: Ziky
* Date: 09/04/13
* Time: 07:38
* To change this template use File | Settings | File Templates.
*/
public class UpdatePhotosTask extends AsyncTask<String, Void, ArrayList<String>> {
private OnHttpResponseListener listener;
public UpdatePhotosTask(OnHttpResponseListener listener) {
this.listener = listener;
}
#Override
protected ArrayList<String> doInBackground(String... urls) {
ArrayList<String> responses = new ArrayList<String>();
for (String url : urls) {
StringBuilder response = new StringBuilder();
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
StatusLine statusLine = execute.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response.append(s);
}
responses.add(response.toString());
} else {
Log.e(this.getClass().toString(), "Failed to download photo list");
}
} catch (IOException e) {
e.printStackTrace();
}
}
return responses;
}
#Override
protected void onPostExecute(ArrayList<String> responses) {
listener.onHttpResponse(responses);
}
public interface OnHttpResponseListener {
public void onHttpResponse(ArrayList<String> responses);
}
}
The activity:
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.StrictMode;
import android.widget.Toast;
import com.gmail.zack.yovel.FlickAround.background.UpdateService;
public class MyActivity extends Activity {
private UpdateService mUpdateService;
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
mUpdateService = ((UpdateService.LocalBinder) service).getService();
Toast.makeText(MyActivity.this, R.string.update_service_connected, Toast.LENGTH_SHORT).show();
}
#Override
public void onServiceDisconnected(ComponentName name) {
mUpdateService = null;
Toast.makeText(MyActivity.this, R.string.local_service_disconnected, Toast.LENGTH_SHORT).show();
}
};
private boolean mIsBound;
void doBindService() {
Toast.makeText(this, "MyActivity.doBindService()", Toast.LENGTH_LONG).show();
bindService(new Intent(this, UpdateService.class), mConnection, BIND_AUTO_CREATE);
mIsBound = true;
}
void doUnbindService() {
if (mIsBound) {
unbindService(mConnection);
mIsBound = false;
}
}
#Override
protected void onDestroy() {
super.onDestroy();
doUnbindService();
}
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Activate StrictMode
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll().penaltyLog().penaltyDeath().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll()
.penaltyLog().penaltyDeath().build());
}
#Override
protected void onStart() {
super.onStart();
doBindService();
}
}
Why isn't it working?
Probably the most common source of binding silently failing is not having the service listed in the manifest. This does not raise an exception, so your app does not crash, but there should be a message (warning, IIRC) in LogCat pointing out your issue.

Android: How can post my link with image title and some description on Facebook wall

I am parsing rss feed using xml parsing in my app. I integrated facebook in my app. My requirement is when I click on share button it shares my content with image title and single description.
My main activity in which I store parse data.
SplashActivity.java
package com.example.shareslab;
import java.util.ArrayList;
import java.util.List;
import com.example.shareslab.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.text.Html.ImageGetter;
import android.util.Log;
import android.view.Gravity;
import android.view.ViewGroup.LayoutParams;
import android.widget.Toast;
public class SplashActivity extends Activity {
/** Called when the activity is first created. */
ProgressDialog progress;
private List<com.example.shareslab.Message> messages;
public static String singleDescription;
public static String title;
static List<String>imageURLAmit;
static List<String> titles;
static List<String> description,link;
public static String[][] arrays;
public static ArrayList<String> galleryImages;
public static int position=0;
//Handle user current location
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_activity);
// Register the listener with the Location Manager to receive location updates
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
Log.d("net status ", "show "+info);
if (info != null && info.isAvailable()) {
Log.d("net connected", "show "+info);
System.out.println("Connection OKK");
new DownloadCities().execute();
}
else{
Log.d("net not connected", "show "+info);
Toast.makeText(SplashActivity.this, "Check Internet connection. And try again.", Toast.LENGTH_LONG).show();
}
}
private class DownloadCities extends AsyncTask<String, Void, String> {
private String ResultString = "";
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
if(progress.isShowing()){
System.out.println("IN POST EXE");
progress.dismiss();
startActivity(new Intent(SplashActivity.this,MessageList.class));
}
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progress = ProgressDialog.show(SplashActivity.this, "","Loading....");
progress.setIndeterminate(true);
progress.getWindow().setGravity(Gravity.BOTTOM);;
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
System.out.println("Going to call getCitiesFromServer()");
loadFeed();
}
catch (Exception e) { // <-- Use the correct exception type
ResultString = "Some error message";
}
return null;
}
}
private void loadFeed(){
position=0;
try{
BaseFeedParser parser = new BaseFeedParser();
messages = parser.parse();
titles = new ArrayList<String>(messages.size());
description = new ArrayList<String>(messages.size());
link = new ArrayList<String>(messages.size());
arrays=new String[messages.size()][];
final List<String> imageURL=new ArrayList<String>(1);
imageURLAmit=new ArrayList<String>(messages.size());
for (com.example.shareslab.Message msg : messages){
Spanned title=Html.fromHtml(msg.getTitle());
titles.add(title.toString());
link.add(msg.getLink().toString());
Spanned data=Html.fromHtml(msg.getDescription(),new ImageGetter() {
public Drawable getDrawable(String source) {
// TODO Auto-generated method stub
imageURL.add(source);
return null;
}
},null);
if(imageURL.size()!=0){
imageURLAmit.add(imageURL.get(0));
}else{
imageURLAmit.add("http://blog.kevinlearynet.netdna-cdn.com/files/applausemeter-300x200.jpg");
}
System.out.println("Position b4 loop : "+position);
int j;
arrays[position]=imageURL.toArray(new String[imageURL.size()]);
System.out.println("2D array colomn length : "+arrays[position].length);
position++;
System.out.println("Position afeter loop : "+position);
imageURL.clear();
description.add( data.toString());
System.out.println("End addition");
}
System.out.println("Final Image URL lenght : "+imageURL.size());
} catch (Throwable t){
Log.e("AndroidNews",t.getMessage(),t);
}
}
}`
here my Facebookc.java class for Facebook share.
Facebookc.java
package com.example.shareslab;
import com.example.shareslabfb.DialogError;
import com.example.shareslabfb.Facebook;
import com.example.shareslabfb.Facebook.DialogListener;
import com.example.shareslabfb.FacebookError;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Toast;
public class Facebookc extends Activity{
private static final String APP_ID = "392939617444978";
private static final String[] PERMISSIONS = new String[] {"publish_stream"};
private static final String TOKEN = "access_token";
private static final String EXPIRES = "expires_in";
private static final String KEY = "facebook-credentials";
private Facebook facebook;
private String messageToPost;
public boolean saveCredentials(Facebook facebook) {
Editor editor = getApplicationContext().getSharedPreferences(KEY, Context.MODE_PRIVATE).edit();
editor.putString(TOKEN, facebook.getAccessToken());
editor.putLong(EXPIRES, facebook.getAccessExpires());
return editor.commit();
}
public boolean restoreCredentials(Facebook facebook) {
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(KEY, Context.MODE_PRIVATE);
facebook.setAccessToken(sharedPreferences.getString(TOKEN, null));
facebook.setAccessExpires(sharedPreferences.getLong(EXPIRES, 0));
return facebook.isSessionValid();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
facebook = new Facebook(APP_ID);
restoreCredentials(facebook);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.facebook_dialog);
String facebookMessage = getIntent().getStringExtra("facebookMessage");
if (facebookMessage == null){
facebookMessage = "";
}
messageToPost = facebookMessage;
}
public void doNotShare(View button){
finish();
}
public void share(View button){
if (! facebook.isSessionValid()) {
loginAndPostToWall();
}
else {
postToWall(messageToPost);
}
}
public void loginAndPostToWall(){
facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH, new LoginDialogListener());
}
public void postToWall(String message){
Bundle parameters = new Bundle();
parameters.putString("message", message);
parameters.putString("name", "titles.get(position)");
parameters.putString("caption","shareslab.com");
parameters.putString("link", "http://www.shareslab.com");
parameters.putString("picture", "imageURLAmit.get(position)");
parameters.putString("description","description.get(position)");
try {
facebook.request("me");
String response = facebook.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") ||
response.equals("false")) {
showToast("Blank response.");
}
else {
showToast("Message posted to your facebook wall!");
}
finish();
} catch (Exception e) {
showToast("Failed to post to wall!");
e.printStackTrace();
finish();
}
}
class LoginDialogListener implements DialogListener {
public void onComplete(Bundle values) {
saveCredentials(facebook);
if (messageToPost != null){
postToWall(messageToPost);
}
}
public void onFacebookError(FacebookError error) {
showToast("Authentication with Facebook failed!");
finish();
}
public void onError(DialogError error) {
showToast("Authentication with Facebook failed!");
finish();
}
public void onCancel() {
showToast("Authentication with Facebook cancelled!");
finish();
}
}
private void showToast(String message){
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
}
If your image is saved in SDCard, then you can use the below code after getting the uri of image :-
Here in code, uri of image is declared as imageUri.
public void performPostToWall(Uri imageUri){
byte[] data = null;
ContentResolver cr = context.getContentResolver();
InputStream in = null;
try {
in = cr.openInputStream(imageUri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap thumb = BitmapFactory.decodeStream(in, null, options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumb.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
Toast.makeText(context, "Unable to upload image", Toast.LENGTH_LONG).show();
}
Bundle params = new Bundle();
params.putByteArray("picture", data);
if (!(captionText == null || captionText.equals("")))
params.putString("caption", captionText);
Request req = new Request(session, "me/photos", params, HttpMethod.POST, new Request.Callback() {
#Override
public void onCompleted(Response response) {
context.onPostToMyWallWithImageResponse(response);
}
});
req.executeAsync();
}
tyr this code
public void postToWall(String message){
try {
String response=facebook.request("me");
Bundle parameters = new Bundle();
parameters.putString("message", _id);
parameters.putString("caption", " message.");
parameters.putString("description", "A secret message is waiting for you.");
parameters.putString("name", "A Secret Message For You");
parameters.putString("picture", "http://sheokhanda.files.wordpress.com/2010/06/spring-colors.jpg");
parameters.putString("link", "http://www.google.com" );
response = facebook.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") || response.equals("false")) {
Log.i(TAG, "Blank Response...");
}
else {
Log.i(TAG, "Message posted to your facebook wall!..");
}
} catch (Exception e) {
e.printStackTrace();
}
}
it requires this permissions publish_stream

Categories

Resources