Memory leak in service android - java

I am implementing the bound service for the socket.io implementation in android for single socket maintenance to connect with nodejs server by this Gottox library. When I implementing this the memory of the service is not stable like while on starting of the service it takes around 30MB to 40MB, after some time it also leads to 200MB. So I thought it may be memory leak. But i don't get any single clue to find it.
Codes
DemoActivity.java
import org.json.JSONException;
import org.json.JSONObject;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import com.actionbarsherlock.app.SherlockActivity;
import com.devspark.appmsg.AppMsg;
import com.devspark.appmsg.AppMsg.Style;
import com.nuappz.Demo.DemoService.MyLocalBinder;
import com.nuappz.Demo.handler.ResponseHandler;
import com.nuappz.Demo.helper.MySharedPreferences;
public class DemoActivity extends SherlockActivity {
MySharedPreferences pref;
DemoService socketService;
boolean isBound;
EditText name, mobile_no, email, password;
Button Demo;
Style style_alert, style_success;
JSONObject json_Demo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_Demo);
isBound = false;
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// start the bind service
if (!isBound) {
bindService(new Intent(DemoActivity.this,
DemoService.class), myConnection,
Context.BIND_AUTO_CREATE);
isBound = true;
startService(new Intent(this, DemoService.class));
socketService = DemoService.getInstance();
}
}
public ServiceConnection myConnection = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
isBound = false;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
socketService = ((MyLocalBinder) service).getService();
isBound = true;
}
};
protected void onDestroy() {
if (isBound) {
// Disconnect from an application service. You will no longer
// receive calls as the service is restarted, and the service is
// now allowed to stop at any time.
unbindService(myConnection);
isBound = false;
}
stopService(new Intent(DemoActivity.this, DemoService.class));
super.onDestroy();
}
}
DemoService.java
import io.socket.IOAcknowledge;
import io.socket.IOCallback;
import io.socket.SocketIO;
import io.socket.SocketIOException;
import java.net.MalformedURLException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.SSLContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import com.nuappz.Demo.handler.ResponseHandler;
import com.nuappz.Demo.helper.MySharedPreferences;
/*
* This class is Background service for the Blood Drop application
*/
public class DemoService extends Service {
private static final String serverUrl = "http://nuappzdev.hello.com:8080/";
private static SocketIO socket;
private static DemoService instance;
private static ResponseHandler handler;
public boolean bound;
JSONObject jobj_in = new JSONObject();
#Override
public void onCreate() {
// TODO Auto-generated method stub
Log.d("Service", "Started");
super.onCreate();
// connecting socket
try {
DemoService.initInstance();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
public DemoService() {
}
public static DemoService getInstance() {
return instance;
}
// start the service to handle the functions
public int onStartCommand(Intent intent, int flags, int startId) {
// HandleReceiveRequest();
return START_STICKY;
}
// Stop the services
public void onDestroy() {
Log.d("Service", "Stopped");
getSocket().disconnect();
}
// Binder class initialize
public class MyLocalBinder extends Binder {
DemoService getService() {
return DemoService.this;
}
}
private final IBinder myBinder = new MyLocalBinder();
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
bound = true;
return myBinder;
}
// initiate the socket connection
public static void initInstance() throws MalformedURLException {
if (instance == null) {
instance = new DemoService();
if (DemoService.getSocket() == null) {
DemoService.setSocket(new SocketIO());
}
DemoService.connectIO();
}
}
// Method to get socket
public static SocketIO getSocket() {
return socket;
}
// Method to set socket
public static void setSocket(SocketIO socket) {
DemoService.socket = socket;
}
// Method to ConnectIO to server
public static void connectIO() throws MalformedURLException {
try {
SocketIO.setDefaultSSLSocketFactory(SSLContext.getDefault());
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
DemoService.getSocket().connect(serverUrl, new IOCallback() {
#Override
public void onMessage(JSONObject json, IOAcknowledge ack) {
// TODO Auto-generated method stub
}
#Override
public void onMessage(String data, IOAcknowledge ack) {
}
#Override
public void onError(SocketIOException socketIOException) {
Log.d("Connection:", "Error in Connection");
}
#Override
public void onDisconnect() {
// TODO Auto-generated method stub
Log.d("Connection:", "disConnected");
}
#Override
public void onConnect() {
Log.d("Connection:", "Connected");
}
#Override
// Method to getting response from server
public void on(String event, IOAcknowledge ack, Object... args) {
JSONArray jarr_args = new JSONArray();
JSONObject jobj_in = new JSONObject();
try {
jarr_args.put(args[0]);
jobj_in = jarr_args.getJSONObject(0);
jobj_in.put("event", event);
Log.d("jobject: event", jobj_in.getString("event"));
try {
handler.handleObject(jobj_in);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
}
// Method to send request to server
public static void emit(String event, Object args,
ResponseHandler responseHandler) throws MalformedURLException {
handler = responseHandler;
if (DemoService.getSocket().isConnected() == false) {
DemoService.getSocket().reconnect();
}
DemoService.getSocket().emit(event, args);
}
// Method to send request to server with Acknowledge
public static void emitWithAcknowledge(String event, Object args)
throws MalformedURLException {
if (DemoService.getSocket().isConnected() == false) {
DemoService.getSocket().reconnect();
}
DemoService.getSocket().emit(event, new IOAcknowledge() {
#Override
public void ack(Object... args) {
// TODO Auto-generated method stub
}
}, args);
}
}
}
What are the chances of memory leak in this code.

You needs to unbind service in onStop of your activity and you should never call stopService from your activity. Let Android do the handling of life cycle of your service.

Related

Android Remote Service does not work on Real device

Remote Service
I'm doing a test for Android remote Service.
In the first app module, I make a service, complete as below:
AppService
package com.hqyj.dev.aidltest;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
public class AppService extends Service {
public AppService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return new IAppServiceRemoteBinder.Stub() {
#Override
public void basicTypes(
int anInt, long aLong,
boolean aBoolean, float aFloat,
double aDouble, String aString)
throws RemoteException {
}
#Override
public void setData(String data)
throws RemoteException {
setRealData(data);
}
#Override
public void registerCallback(IRemoteServiceCallback cb)
throws RemoteException {
AppService.this.callback = cb;
}
#Override
public void unregisterCallback(IRemoteServiceCallback cb)
throws RemoteException {
AppService.this.callback = null;
}
};
}
private IRemoteServiceCallback callback;
#Override
public void onCreate() {
super.onCreate();
System.out.println("Service started");
}
#Override
public void onDestroy() {
super.onDestroy();
System.out.println("Service stop");
}
public void setRealData(String data) {
this.data = data;
System.out.println("data = " + data);
try {
Thread.sleep(1000);
if (callback != null) {
callback.vlueChanged(data);
}
} catch (InterruptedException | RemoteException e) {
e.printStackTrace();
}
}
private String data = "default date";
}
And their are two AIDL files:
IAppServiceRemoteBinder.aild
// IAppServiceRemoteBinder.aidl
package com.hqyj.dev.aidltest;
// Declare any non-default types here with import statements
import com.hqyj.dev.aidltest.IRemoteServiceCallback;
interface IAppServiceRemoteBinder {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
void basicTypes(int anInt,
long aLong,
boolean aBoolean, float aFloat,
double aDouble, String aString);
void setData(String data);
void registerCallback(IRemoteServiceCallback cb);
void unregisterCallback(IRemoteServiceCallback cb);
}
IRemoteServiceCallback.aild
// IRemoteServiceCallback.aidl
package com.hqyj.dev.aidltest;
// Declare any non-default types here with import statements
interface IRemoteServiceCallback {
/**
* return from server
*/
void vlueChanged(String value);
}
And in AndroidManifest.xml, this Server decleared as below:
AndroidManifest.xml
<service
android:name="com.hqyj.dev.aidltest.AppService"
android:enabled="true"
android:exported="true"
android:process=":remote">
</service>
And then, the in second module, copies all these aidl files with package name, as below:
And in MainActivity in anotherapp, complete as below:
package com.hqyj.dev.anotherapp;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import com.hqyj.dev.aidltest.IAppServiceRemoteBinder;
import com.hqyj.dev.aidltest.IRemoteServiceCallback;
public class MainActivity extends AppCompatActivity
implements View.OnClickListener, ServiceConnection {
private final String TAG = MainActivity.class.getSimpleName();
private Intent intent;
private IAppServiceRemoteBinder binder;
private int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn_start).setOnClickListener(this);
findViewById(R.id.btn_stop).setOnClickListener(this);
findViewById(R.id.btn_set).setOnClickListener(this);
intent = new Intent();
intent.setComponent(new
ComponentName("com.hqyj.dev.aidltest",
"com.hqyj.dev.aidltest.AppService"));
}
#SuppressLint("DefaultLocale")
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_start:
bindService(intent, this,
Context.BIND_AUTO_CREATE);
break;
case R.id.btn_set:
if (binder != null) {
try {
binder.setData(
String.format("the %d times",
++count));
} catch (RemoteException e) {
e.printStackTrace();
}
}
break;
case R.id.btn_stop:
try {
binder.unregisterCallback(callback);
} catch (RemoteException e) {
e.printStackTrace();
}
unbindService(this);
break;
}
}
#Override
public void onServiceConnected(
ComponentName name, IBinder service) {
binder =
IAppServiceRemoteBinder.Stub.asInterface(service);
Log.d(TAG, "onServiceConnected: " + 1);
try {
binder.registerCallback(callback);
} catch (RemoteException e) {
e.printStackTrace();
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
}
private IRemoteServiceCallback.Stub callback =
new IRemoteServiceCallback.Stub() {
#Override
public void
vlueChanged(String value) throws RemoteException {
Log.e(TAG, "vlueChanged: " + value);
}
};
}
As you see, I called the remote service by using bindService();
It works well, when I push these two apps into an emulator which using Android 7.0 as platform.
But
When I push these app into an real device(using Android 6.0), the flowing mistake happened:
AIDL failed!!
Why??

Single socket.IO connection for all activities in android

I have created Singleton class for SocketIOClient reference by here. Server was connected. I can able to send request from activity to SocketIOClient. But how can I get response from Singleton class in Activity?
Here My Activity:
import java.net.MalformedURLException;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText uname, passwd;
Button login;
JSONObject json;
SocketIOClient socket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
socket = new SocketIOClient();
try {
SocketIOClient.initInstance();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
json = new JSONObject();
uname = (EditText) findViewById(R.id.unameED);
passwd = (EditText) findViewById(R.id.passwdED);
login = (Button) findViewById(R.id.loginButton);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
json.put("username", uname.getText().toString().trim());
json.put("password", passwd.getText().toString().trim());
//request send to server
SocketIOClient.emit("login_request", json);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
Also My Singleton Class have on() method:
#Override
public void on(String event, IOAcknowledge ack, Object... args) {
JSONArray jarr_args = new JSONArray();
JSONObject jobj_in = new JSONObject();
if (event.equals("registration_status")) {
jarr_args.put(args[0]);
try {
jobj_in = jarr_args.getJSONObject(0);
Log.d("Result", jobj_in.getString("result"));
if (jobj_in.getString("result").equals("success")) {
} else {
Log.d("check:", "username and password");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Here Singleton class can get response from server. But I want to know,how to get the response in my activity?
Create an abstract class like this
public abstract class ResponseHandler
{
private Context context;
public abstract void execute (JSONObject jsonObject) throws JSONException;
public ResponseHandler (Context ctx)
{
this.context = ctx;
}
public void handleObject(JSONObject jsonObject) throws Exception
{
execute(jsonObject);
}
}
Inside your activity
While calling socket class, pass the ResponseHadler also as a parameter
Example:
SocketIOClient.initInstance(your parameters, new ResponseHandler(this)
{
//ResponseHandler have an abstract method called execute(). So you are overriding it here
#Override
public void execute(JSONObject jsonObject) throws JSONException
{
// Here you will get your JSONObject passed from socket class
}
}
And inside your socket class
public class YourSocketClass
{
private ResponseHandler handler;
public static void initInstance(your parameter, ResponseHandler responseHandler)
{
this.handler = responseHandler;
// Do your operations here
}
#Override
public void on(String event, IOAcknowledge ack, Object... args)
{
JSONArray jarr_args = new JSONArray();
JSONObject jobj_in = new JSONObject();
if (event.equals("registration_status"))
{
jarr_args.put(args[0]);
try
{
jobj_in = jarr_args.getJSONObject(0);
Log.d("Result", jobj_in.getString("result"));
if (jobj_in.getString("result").equals("success"))
{
//If you want to pass your jsonobject from here to activity
//Do something like this
handler.handleObject(jobj_in);
}
else
{
Log.d("check:", "username and password");
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}
}

sending string in android bluetooth

I have my major project on android based home automation system meaning that I have to control home appliances using android bluetooth. I am using HC-05 bluetooth module which receives the string sent to it through my application, sends it to PIC16f877a and the pic in turn depending upon the string received, controls the appliances. Now my problem is that I have been able to pair and connect the devices through my application but my application is not sending the characters which I want to send when I click the button. Note that PIC and the Bluetooth module are working fine. please help me. I am posting my code below hope you guys won't mind.
package com.chainedcat.splashscreen;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivityActivity extends Activity{
private BluetoothAdapter BA;
private ArrayList<BluetoothDevice> devices;
private ListView lv;
private TextView text;
private BluetoothSocket btSocket=null;
private ArrayAdapter<String> btArrayAdapter;
private static final int REQUEST_ENABLE_BT = 1;
private UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34EB");
private OutputStream outStream=null;
public void Init(){
BA = BluetoothAdapter.getDefaultAdapter();
text =(TextView) findViewById(R.id.text);
lv = (ListView) findViewById(R.id.listView1);
devices = new ArrayList<BluetoothDevice>();
btArrayAdapter= new ArrayAdapter<String>this,android.R.layout.simple_list_item_1);
lv.setAdapter(btArrayAdapter);
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Init();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
BluetoothDevice selectedDevice = devices.get(arg2);
if(selectedDevice.getBondState()== BluetoothDevice.BOND_NONE){
pairDevice(selectedDevice);
}
else if(selectedDevice.getBondState()==BluetoothDevice.BOND_BONDED){
connect(selectedDevice);
}
}
});
}
public void bluetooth(View view){
if(!BA.isEnabled()){
Intent btIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(btIntent, REQUEST_ENABLE_BT);
Toast.makeText(getApplicationContext(), "Bluetooth turned on!!", Toast.LENGTH_LONG).show();
btExtra();
}else{
Toast.makeText(getApplicationContext(), "Bluetooth is already on!!", Toast.LENGTH_LONG).show();
btExtra();
}
}
public void btExtra(){
btArrayAdapter.clear();
BA.startDiscovery();
registerReceiver(btReceiver, new tentFilter(BluetoothDevice.ACTION_FOUND));
}
final BroadcastReceiver btReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
devices.add(device);
String status=null;
if(device.getBondState()==BluetoothDevice.BOND_BONDED){
status="paired";
}else{status="not paired";}
btArrayAdapter.add(device.getName()+" : "+status+"\n"+device.getAddress());
btArrayAdapter.notifyDataSetChanged();
}
}
};
#Override
protected void onActivityResult(int requestCode,int resultCode, Intent data){
if(requestCode==REQUEST_ENABLE_BT){
if(BA.isEnabled()){
text.setText("Bluetooth Status:Enabled");
}else{
text.setText("Bluetooth Status:Disabled");
}
}
}
private void pairDevice(BluetoothDevice device) {
Method m=null;
try {
m = device.getClass().getMethod("createBond", (Class[]) null);
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
m.invoke(device, (Object[]) null);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connect(device);
}
public void connect(BluetoothDevice device){
Toast.makeText(getApplicationContext(), "connecting....", Toast.LENGTH_LONG).show();
try {
btSocket=device.createInsecureRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BA.cancelDiscovery();
try {
Toast.makeText(getApplicationContext(), "entered in run", Toast.LENGTH_LONG).show();
btSocket.connect();
if(btSocket!=null){btSocket.close();}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void send(String s){
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] bytes = s.getBytes();
try {
outStream.write(bytes);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void fan(View v){
send("f");
}
#Override
public void onDestroy(){
super.onDestroy();
BA.disable();
unregisterReceiver(btReceiver);
}
}

Trying to run an Asynctask into a service, eclipse looks good, but app crashes Whats wrong here?

Im trying to make an app witch looks on a JSON encoded php file, there that all right. All runs perfectly, but now im attempting to put that class into a Service beacuse i want to run it on background and repeatedly, but application crushes, (on the phone and simulated)
So can anyone tell me whats wrong here?
Here is the code
First the main activity . java
[...]IMPORTS
public class ServiceMainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service);
}
public void onClickComenzar(View v) {
startService(new Intent(getBaseContext(), MyService.class));
}
public void onClickDetener(View v) {
stopService(new Intent(getBaseContext(), MyService.class));
}
}
And here the Service activity . java , the place where im trying to put my asynctask
package attempt.service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.text.Html;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;
public class MyService extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
try {
new DoBackgroundTask().execute("http://iatek.eu/sys/getsmsx.php");
} catch (Exception ex) {
ex.printStackTrace();
}
return START_STICKY;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(getBaseContext(), "service stoped",
Toast.LENGTH_SHORT).show();
}
private class DoBackgroundTask extends AsyncTask<String, String, JSONObject> {
#Override
protected JSONObject doInBackground(String... urls) {
JSONObject obj = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urls[0]);
// HttpResponse response = httpclient.execute(httppost);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
obj = new JSONObject(jsonResult);
}
catch (JSONException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return obj;
}
protected void onProgressUpdate( ) {
// TODO Auto-generated method stub
}
#Override
protected void onPostExecute(JSONObject obj) {
JSONArray jsonArray;
String dana = null;
try {
jsonArray = obj.getJSONArray("posts");
JSONObject childJSONObject = jsonArray.getJSONObject(1);
String sms = childJSONObject.getString("sms");
Toast.makeText(getBaseContext(), "sms"+sms,
Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stopSelf();
}
public StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
return answer;
}
}
}
My objetive on this code is to show some php data on a toast, but it doesnt... i dont know why, help me pleasee!!
Thanks a lot!
I think using InentService is better suited for what you are trying to accomplish. It runs on a separate Thread, and it stops itself when it is done.

How to create in-app billing in application?

I use example from Android developers, and have created code:
package com.nda.quizapp;
import com.nda.dungeons.BillingService;
import com.nda.dungeons.Consts;
import com.nda.dungeons.ResponseHandler;
import com.nda.dungeons.Consts.PurchaseState;
import com.nda.dungeons.Consts.ResponseCode;
import com.nda.dungeons.PurchaseObserver;
import com.nda.dungeons.Consts.PurchaseState;
import com.nda.dungeons.Consts.ResponseCode;
import com.nda.dungeons.BillingService.RequestPurchase;
import com.nda.dungeons.BillingService.RestoreTransactions;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class QuizappUpgradeActivity extends Activity implements OnClickListener{
private class QuestionsPurchaseObserver extends PurchaseObserver {
public QuestionsPurchaseObserver(Handler handler) {
super(QuizappUpgradeActivity.this, handler);
}
public QuestionsPurchaseObserver(Activity activity, Handler handler) {
super(activity, handler);
// TODO Auto-generated constructor stub
}
#Override
public void onBillingSupported(boolean supported) {
// TODO Auto-generated method stub
Log.e("method", "onBillingSupported");
}
#Override
public void onPurchaseStateChange(PurchaseState purchaseState,
String itemId, int quantity, long purchaseTime,
String developerPayload) {
// TODO Auto-generated method stub
Log.e("method", "onPurchaseStateChange");
}
#Override
public void onRequestPurchaseResponse(RequestPurchase request,
ResponseCode responseCode) {
Log.e("method", "onRequestPurchaseResponse");
// TODO Auto-generated method stub
if (responseCode == ResponseCode.RESULT_OK) {
Log.e("RESULT", "OK");
} else if (responseCode == ResponseCode.RESULT_USER_CANCELED) {
Log.e("RESULT", "CANCEL");
} else {
Log.e("RESULT", "ERROR");
}
}
#Override
public void onRestoreTransactionsResponse(RestoreTransactions request,
ResponseCode responseCode) {
// TODO Auto-generated method stub
Log.e("method", "onRestoreTransactionsResponse");
}
}
private QuestionsPurchaseObserver mObserver;
private Handler mHandler;
private BillingService mBillingService;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upgrade);
initialize();
mHandler = new Handler();
mObserver = new QuestionsPurchaseObserver(mHandler);
mBillingService = new BillingService();
mBillingService.setContext(this);
ResponseHandler.register(mObserver);
if (!mBillingService.checkBillingSupported()) {
Toast.makeText(this, "Paying isn't support", Toast.LENGTH_LONG).show();
}
}
private void initialize() {
Button bronze=(Button)findViewById(R.id.buttonBuyBronze);
Button silver=(Button)findViewById(R.id.buttonBuySilver);
Button gold=(Button)findViewById(R.id.buttonBuyGold);
bronze.setOnClickListener(this);
silver.setOnClickListener(this);
gold.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mBillingService.requestPurchase("bronze_q", null)) {
Log.e("1", "bronze yes");
}
else {
Log.e("1", "bronze no");
}
}
#Override
protected void onStart() {
super.onStart();
ResponseHandler.register(mObserver);
}
#Override
protected void onStop() {
super.onStop();
//ResponseHandler.unregister(mObserver);
}
}
The window for paying is shown sucessfully, but I have problem - if I close this window than I don't get any events in onRequestPurchaseResponse method. Where have I made mistake? Thank you.
You should add this lines to manifest file:
<receiver android:name="BillingReceiver">
<intent-filter>
<action android:name="com.android.vending.billing.IN_APP_NOTIFY" />
<action android:name="com.android.vending.billing.RESPONSE_CODE" />
<action android:name="com.android.vending.billing.PURCHASE_STATE_CHANGED" />
</intent-filter>
</receiver>
You can find it here

Categories

Resources