ServiceConnection - Service throws NullPointerException - android

In my application, it was possibly for me to establish a bluetooth connection and sending bytes with an own Service and send some bytes to the receiver.
Now I tried unsuccessfully to connect to my own server for sending a text and get an answer. For any reason, I get a NullPointerException for my Service if I try to call the sendMessage() Method..
Service:
import android.annotation.TargetApi;
import android.app.Service;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
public class ClientService extends Service {
private String LOG_TAG = null;
private final IBinder mBinder = new LocalBinder();
private final String url_string = "";
private int receivedUcCommand = 0;
#Override
public void onCreate() {
super.onCreate();
}
public void sendToServer(final String text){
new Thread(new Runnable() {
#Override
public void run() {
if(internetAvailable()){
try {
String textParam = "text1" + URLEncoder.encode(text,"UTF-8");
URL scriptUrl = new URL(url_string);
HttpURLConnection connection = (HttpURLConnection) scriptUrl.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.setFixedLengthStreamingMode(textParam.getBytes().length);
OutputStreamWriter contextWriter = new OutputStreamWriter(connection.getOutputStream());
contextWriter.write(textParam);
contextWriter.flush();
contextWriter.close();
InputStream answerInputStream = connection.getInputStream();
String answer = read(answerInputStream);
answerInputStream.close();
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
}
private String read(InputStream is){
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String currentLine;
try {
while((currentLine = br.readLine()) != null){
sb.append(currentLine+"\n");
}
}catch (IOException e){
e.printStackTrace();
}
return sb.toString().trim();
}
private boolean internetAvailable(){
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return ni != null && ni.isConnectedOrConnecting();
}
#Override
public IBinder onBind(Intent intent) {
// Wont be called as service is not bound
Log.i(LOG_TAG, "In onBind");
return mBinder;
}
public class LocalBinder extends Binder {
ClientService getService() {
// Return this instance of LocalService so clients can call public methods
return ClientService.this;
}
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Log.i(LOG_TAG, "In onTaskRemoved");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(LOG_TAG, "In onDestroy");
}
}
In Activity I do this:
public class loggedInActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener{
public static final String mBroadcastStringAction = "com.truiton.broadcast.string";
public static final String mBroadcastIntegerAction = "com.truiton.broadcast.integer";
public static final String mBroadcastArrayListAction = "com.truiton.broadcast.arraylist";
private TextView mTextView;
private IntentFilter mIntentFilter;
BluetoothService bService;
ClientService cService;
boolean btBound = false;
boolean clientBound = false;
// private View startButton;
Button testButton;
EditText et;
static final int CAM_REQUEST = 1;
//Button reconnectButton;
TextView recText;
recText = (TextView) findViewById(R.id.receivedText);
//recText.setText("KEIN ALARM");
et = (EditText) findViewById(R.id.editText);
testButton = (Button) findViewById(R.id.testButton);
// This way I start and bind the service for Bluetooth, to my activity
Intent btIntent = new Intent(this, BluetoothService.class);
startService(btIntent);
bindService(btIntent, btServiceConnection, Context.BIND_AUTO_CREATE);
//And this way I unsuccessfully trying to bind and start the ClientService for ServerConnection
Intent clientIntent = new Intent(this, ClientService.class);
startService(clientIntent);
bindService(clientIntent, clientServiceConnection, Context.BIND_AUTO_CREATE);
testButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
//ATTENTION: TRYING TO SENDING TO SERVER HERE, IT THROWS ME A NULLPOINTER
cService.sendToServer(et.getText().toString());
}
});
}
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection btServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
BluetoothService.LocalBinder binder = (BluetoothService.LocalBinder) service;
bService = binder.getService();
btBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
btBound = false;
}
};
//I think it has to be to do something with that code here, but
this is the only place, where cService is defined...
private ServiceConnection clientServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
ClientService.LocalBinder binder = (ClientService.LocalBinder) service;
cService = binder.getService();
clientBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
clientBound = false;
}
};

It was like I said a mistake, which only could produced by a newbie like me. I forget to sign in the tag in the AndroidManifest.xml

Related

wifi p2p file transfer android connected device but not transfering

Hello iam stuck in problem since yesterday searched everything anywhere i create application which show device which arre connected to same router wifi , then iam able to connect both device using this exmple
https://developer.android.com/guide/topics/connectivity/wifip2p.html#creating-app
everything is okay both devices are connected but when transfer file serviceintent is not starting so thats why i cant transfer anything , there is not log error but happend nothing when i choose image to send
MainActivity Class
package com.b.wifip2p;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pGroup;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MainActivity extends AppCompatActivity implements WifiP2pManager.PeerListListener, WifiP2pManager.ConnectionInfoListener {
Button button;
private boolean isWifiP2pEnabled = false;
private boolean retryChannel = false;
private final IntentFilter intentFilter = new IntentFilter();
private WifiP2pManager.Channel channel;
WifiP2pManager.Channel mChannel = null;
WifiP2pManager mManager;
private WifiP2pInfo info;
BroadCast broadCast;
private BroadcastReceiver receiver = null;
static List peers = new ArrayList();
ListView lv;
static Adapater myadapter;
ArrayList<DeviceInfo_Bean>list=new ArrayList<>();
private WifiP2pDevice device;
String hostaddd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=findViewById(R.id.lv);
myadapter=new Adapater(this,list);
button=findViewById(R.id.button);
lv.setAdapter(myadapter);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
connect();
}
});
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
System.out.println("---sucess discover");
}
#Override
public void onFailure(int reasonCode) {
System.out.println("---fail");
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 007);
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
System.out.println("---ip"+ipAddress);
}
});
}
#Override
public void onResume() {
super.onResume();
broadCast = new BroadCast(mManager, mChannel, MainActivity.this);
registerReceiver(broadCast, intentFilter);
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(broadCast);
}
private static WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
#Override
public void
onPeersAvailable(WifiP2pDeviceList peerList) {
List<WifiP2pDevice> refreshedPeers = (List<WifiP2pDevice>) peerList.getDeviceList();
if (!refreshedPeers.equals(peers)) {
peers.clear();
peers.addAll(refreshedPeers);
System.out.println("---ref"+refreshedPeers);
}
if (peers.size() == 0) {
Log.d("-----deviceno", "No devices found");
return;
}
}
};
#Override
public void onPeersAvailable(WifiP2pDeviceList peers) {
for (WifiP2pDevice device : peers.getDeviceList())
{
list.clear();
String address=device.deviceAddress;
String name=device.deviceName;
System.out.println("---name"+name+address);
list.add(new DeviceInfo_Bean(name,address));
}
myadapter.notifyDataSetChanged();
Log.i("----", "Found some peers!!! " + peers.getDeviceList());
}
public void connect() {
DeviceInfo_Bean device = list.get(0);
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.address;
config.wps.setup = WpsInfo.PBC;
System.out.println("device in"+device.address);
mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(MainActivity.this, "Connected.",
Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(int reason) {
Toast.makeText(MainActivity.this, "Connect failed. Retry.",
Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// User has picked an image. Transfer it to group owner i.e peer using
// FileTransferService.
Uri uri = data.getData();
// TextView statusText = (TextView) mContentView.findViewById(R.id.status_text);
// statusText.setText("Sending: " + uri);
// Log.d(WiFiDirectActivity.TAG, "Intent----------- " + uri);
Intent serviceIntent = new Intent(MainActivity.this, FileTransferService.class);
serviceIntent.setAction(FileTransferService.ACTION_SEND_FILE);
serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, uri.toString());
serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_ADDRESS,
info.groupOwnerAddress.getHostAddress());
serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_PORT, 8988);
startService(serviceIntent);
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
public static class FileServerAsyncTask extends AsyncTask<Void, Void, String> {
private Context context;
//private TextView statusText;
/**
* #param context
*
*/
public FileServerAsyncTask(Context context) {
this.context = context;
//this.statusText = (TextView) statusText;
}
#Override
protected String doInBackground(Void... params) {
try {
ServerSocket serverSocket = new ServerSocket(8988);
System.out.println("---socket");
Socket client = serverSocket.accept();
///Log.d(WiFiDirectActivity.TAG, "Server: connection done");
final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ context.getPackageName() + "/wifip2pshared-" + System.currentTimeMillis()
+ ".jpg");
File dirs = new File(f.getParent());
if (!dirs.exists())
dirs.mkdirs();
f.createNewFile();
//Log.d(WiFiDirectActivity.TAG, "server: copying files " + f.toString());
OutputStream stream = client.getOutputStream();
String s="---mymsg";
stream.write(s.getBytes());
Log.e("hello","context value "+context);
InputStream inputstream = client.getInputStream();
copyFile(inputstream, new FileOutputStream(f));
serverSocket.close();
return f.getAbsolutePath();
} catch (IOException e) {
// Log.e(WiFiDirectActivity.TAG, e.getMessage());
return null;
}
}
/*
* (non-Javadoc)
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(String result) {
if (result != null) {
// statusText.setText("File copied - " + result);
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + result), "image/*");
context.startActivity(intent);
}
}
/*
* (non-Javadoc)
* #see android.os.AsyncTask#onPreExecute()
*/
#Override
protected void onPreExecute() {
// statusText.setText("Opening a server socket");
}
}
public static boolean copyFile(InputStream inputStream, OutputStream out) {
byte buf[] = new byte[1024];
int len;
long startTime=System.currentTimeMillis();
try {
while ((len = inputStream.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
inputStream.close();
long endTime=System.currentTimeMillis()-startTime;
Log.v("","Time taken to transfer all bytes is : "+endTime);
} catch (IOException e) {
// Log.d(WiFiDirectActivity.TAG, e.toString());
return false;
}
return true;
}
public void onConnectionInfoAvailable(final WifiP2pInfo info) {
System.out.println("---info");
this.info=info;
// view.setText("Group Owner IP - " + info.groupOwnerAddress.getHostAddress());
InetAddress groupOwnerAddress = info.groupOwnerAddress;
System.out.println("--g"+groupOwnerAddress);
System.out.println("--info"+info.groupOwnerAddress.getHostAddress());
if (info.groupFormed && info.isGroupOwner) {
new FileServerAsyncTask(getApplication())
.execute();
} else if (info.groupFormed) {
// The other device acts as the client. In this case, we enable the
// get file button.
}
// hide the connect button
// mContentView.findViewById(R.id.btn_connect).setVisibility(View.GONE);
}
public void showDetails(WifiP2pDevice device) {
this.device = device;
// this.getView().setVisibility(View.VISIBLE);
// TextView view = (TextView) mContentView.findViewById(R.id.device_address);
// view.setText(device.deviceAddress);
//view = (TextView) mContentView.findViewById(R.id.device_info);
//view.setText(device.toString());
System.out.println("---device"+device.deviceAddress);
}
}'
Broadcast
package com.b.wifip2p;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pManager;
import android.util.Log;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import java.nio.channels.Channel;
/**
* Created by BHM on 3/3/2018.
*/
public class BroadCast extends BroadcastReceiver {
private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel;
private MainActivity activity;
PeerListListener peerListListener=null;
public BroadCast(WifiP2pManager manager, WifiP2pManager.Channel channel,
MainActivity activity) {
super();
this.mManager = manager;
this.mChannel = channel;
this.activity = (MainActivity) activity;
}
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("-----broadcast");
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
// UI update to indicate wifi p2p status.
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
// Wifi Direct mode is enabled
// activity.setIsWifiP2pEnabled(true);
} else {
//activity.setIsWifiP2pEnabled(false);
// activity.resetData();
}
// Log.d(WiFiDirectActivity.TAG, "P2P state changed - " + state);
} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
// request available peers from the wifi p2p manager. This is an
// asynchronous call and the calling activity is notified with a
// callback on PeerListListener.onPeersAvailable()
if (mManager != null) {
// mManager.requestPeers(mChannel, (PeerListListener) mChannel);
}
// Log.d(WiFiDirectActivity.TAG, "P2P peers changed");
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
if (mManager == null) {
return;
}
NetworkInfo networkInfo = (NetworkInfo) intent
.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
if (networkInfo.isConnected()) {
// we are connected with the other device, request connection
// info to find group owner IP
mManager.requestConnectionInfo(mChannel, activity);
} else {
// It's a disconnect
// activity.resetData();
}
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
// DeviceListFragment fragment = (DeviceListFragment) activity.getFragmentManager()
// .findFragmentById(R.id.frag_list);
// fragment.updateThisDevice((WifiP2pDevice) intent.getParcelableExtra(
// WifiP2pManager.EXTRA_WIFI_P2P_DEVICE));
intent.getParcelableExtra(
WifiP2pManager.EXTRA_WIFI_P2P_DEVICE);
}
}
}
FileTransferService here intent is not coming
package com.b.wifip2p;
import android.app.IntentService;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
/**
* Created by BHM on 3/4/2018.
*/
class FileTransferService extends IntentService {
private static final int SOCKET_TIMEOUT = 5000;
public static final String ACTION_SEND_FILE = "com.example.android.wifidirect.SEND_FILE";
public static final String EXTRAS_FILE_PATH = "file_url";
public static final String EXTRAS_GROUP_OWNER_ADDRESS = "go_host";
public static final String EXTRAS_GROUP_OWNER_PORT = "go_port";
public FileTransferService(String name) {
super(name);
}
#Override
protected void onHandleIntent(Intent intent) {
System.out.println("--intent");
Context context = getApplicationContext();
if (intent.getAction().equals(ACTION_SEND_FILE)) {
String fileUri = intent.getExtras().getString(EXTRAS_FILE_PATH);
String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);
Socket socket = new Socket();
int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
try {
// Log.d(WiFiDirectActivity.TAG, "Opening client socket - ");
socket.bind(null);
socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
// Log.d(WiFiDirectActivity.TAG, "Client socket - " + socket.isConnected());
OutputStream stream = socket.getOutputStream();
ContentResolver cr = context.getContentResolver();
InputStream is = null;
try {
is = cr.openInputStream(Uri.parse(fileUri));
} catch (FileNotFoundException e) {
// Log.d(WiFiDirectActivity.TAG, e.toString());
}
MainActivity.copyFile(is, stream);
// Log.d(WiFiDirectActivity.TAG, "Client: Data written");
} catch (IOException e) {
// Log.e(WiFiDirectActivity.TAG, e.getMessage());
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
// Give up
e.printStackTrace();
}
}
}
}
}
}
}
I know this is a slightly old question by now, but for those looking for answers:
I would recommend checking that you have the intent filters properly in your AndroidManifest.xml file.
It should look something like:
<activity android:name="ShareActivity">
<intent-filter>
<action android:name="android.intent.action.ACTION_SEND_FILE"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>

Sending text from service to server using TCP socket

Below is main activity code where I got text from service throug broadcast and I'd like to forward this text to server using wifi.
I was thinking that I can just register this app as client and send text to another phone where server app is installed.
But I'm not sure how to do that.
It should be done automatically without pushing any buttons.
Any ideas???
This code is put together from different examples, so sorry if it looks very rough but at least it works;)
I separated lines I added for TCP client:
//for socket client start
//for socket client end
Thanks!
Code
import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.SystemClock;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainActivity extends Activity {
public ResponseReceiver receiver;
public CountDownTimer countDownTimer;
//for socket client start
private Socket socket;
private static final int SERVERPORT = 6000;
private static final String SERVER_IP = "192.168.0.106";
//for socket client end
final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
//Do something if connected
Toast.makeText(getApplicationContext(), "SINIHAMMAS OLEMAS", Toast.LENGTH_SHORT).show();
SystemClock.sleep(3000);
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
countDownTimer.cancel();
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
Toast.makeText(getApplicationContext(), "SINIHAMMAS LAHTI", Toast.LENGTH_SHORT).show();
countDownTimer.start();
}//else if...
}//onReceive
};//BroadcastReceiver
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
long startTime = 30000;
long interval = 1000;
countDownTimer = new MyCountDownTimer(startTime, interval);
IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
IntentFilter filter3 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
this.registerReceiver(mReceiver, filter1);
this.registerReceiver(mReceiver, filter2);
this.registerReceiver(mReceiver, filter3);
final AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
//for socket client start
new Thread(new ClientThread()).start();
//for socket client end
registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1);
Log.d("sinihammas", "Audio SCO state: " + state);
if (AudioManager.SCO_AUDIO_STATE_CONNECTED == state) {
unregisterReceiver(this);
}//if
}//onRecieve
}, new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED));//registerReciever
Log.d("sinihammas", "starting bluetooth");
am.startBluetoothSco();
SystemClock.sleep(2000);
Intent msgIntent = new Intent(MainActivity.this, SimpleIntentService.class);
startService(msgIntent);
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
am.setBluetoothScoOn(false);
am.stopBluetoothSco();
System.exit(0);
}
});
IntentFilter filter = new IntentFilter(ResponseReceiver.ACTION_RESP);
filter.addCategory(Intent.CATEGORY_DEFAULT);
receiver = new ResponseReceiver();
registerReceiver(receiver, filter);
}//onCreate
public class ResponseReceiver extends BroadcastReceiver {
public static final String ACTION_RESP = "alar.alar.com.rahelividinakes2.MESSAGE_PROCESSED";
#Override
public void onReceive(Context context, Intent intent) {
TextView result = (TextView) findViewById(R.id.textView);
String text = intent.getStringExtra(SimpleIntentService.PARAM_OUT_MSG);
result.setText(Html.fromHtml(text + "<br>" + result.getText()));
**I THINK I SHOULD SEND TEXT HERE, BUT I DONT KNOW HOW**
}//onReceive
}//BroadcastReceiver
public class MyCountDownTimer extends CountDownTimer {
MediaPlayer mediaPlayer = MediaPlayer.create(alar.alar.com.rahelividinakes2.MainActivity.this, R.raw.haire);
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
mediaPlayer.start();
SystemClock.sleep(7000);
mediaPlayer.release();
}
#Override
public void onTick(long millisUntilFinished) {
}
}
//for socket client start
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1){
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
//for socket client end
}//Activity
server code EDITED
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class MainActivity extends Activity {
private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
private TextView text;
public static final int SERVERPORT = 6000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text2);
updateConversationHandler = new Handler();
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private String msg;
public updateUIThread(String str) {
this.msg = str;
}
#Override
public void run() {
text.setText(text.getText().toString()+"Client Says: "+ msg + "\n");
}
}
}
First of all, SystemClock.sleep() in MainActivity.onCreate() is a really bad idea due to possible ANR.
Your question actually contains 2 subquestions:
How to send our data to the client thread?
Add a queue member to the activity class. We'll use it in our client thread.
//for socket client start
private Socket socket;
private static final int SERVERPORT = 6000;
private static final String SERVER_IP = "192.168.0.106";
private ConcurrentLinkedQueue<String> mSendQueue = new ConcurrentLinkedQueue<String>();
//for socket client end
And make ResponseReceiver to add data to a queue.
public class ResponseReceiver extends BroadcastReceiver {
public static final String ACTION_RESP = "alar.alar.com.rahelividinakes2.MESSAGE_PROCESSED";
#Override
public void onReceive(Context context, Intent intent) {
TextView result = (TextView) findViewById(R.id.textView);
String text = intent.getStringExtra(SimpleIntentService.PARAM_OUT_MSG);
result.setText(Html.fromHtml(text + "<br>" + result.getText()));
MainActivity.this.mSendQueue.add(text);
}//onReceive
}//BroadcastReceiver
How to send our data via the socket?
Use a queue in ClientThread
class ClientThread implements Runnable {
private final ConcurrentLinkedQueue<String> mQueue;
public ClientThread(ConcurrentLinkedQueue<String> queue) {
mQueue = queue;
}
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
OutputStream stream = socket.getOutputStream();
while(true) {
String data = mQueue.poll();
if(data == null) {
//queue is empty, waiting...
SystemClock.sleep(100);
continue;
}
byte[] bytes = data.getBytes();
stream.write(bytes, 0, bytes.length);
stream.flush();
}
} catch (UnknownHostException e1){
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
//free resources
}
}
}
//for socket client end

Accessing functions inside a thread withing a service from an activity (socket communication)

i'm trying to get the communication between activities and a service to work.
i am pretty new to android and java, learned it my self through youtube :D, but cant find or solve this one.
at first i made an activity with a class thread which handles an ethernet socket. but i discovered when i leave the activity and switch to another the thread is destroyed. to preserve the thread i included the thread inside an service. but now i cant use the functions inside the thread (like sending/getting status). how can i get the instance of my ethernet class back to all of my activities. below i clipped my code.
the code works and run. but when i want to call my send() function or getConStatus() it crashed.
working on a client server communication for home domotics.
// my main activity
import java.io.IOException;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends Activity {
//UI declerations
Button button1, button2;
EditText text1,text2;
ProgressBar waiter;
Ethernets eth;
house house;
Toast message;
ProgressTask Task;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button)findViewById(R.id.button1);
button2 = (Button)findViewById(R.id.button2);
text1 = (EditText)findViewById(R.id.editText1);
text2 = (EditText)findViewById(R.id.editText2);
waiter = (ProgressBar)findViewById(R.id.Waiter);
}
protected void onStop()
{
Intent intent = new Intent(this, Ethernet_Service.class);
stopService(intent);
}
public void start(View view)
{
eth.send("Turn ON"); // i cant USE this !!
}
public void connect(View view) throws UnknownHostException, IOException
{
String ip = null;
int port = 0;
ip = text1.getText().toString();
port = Integer.parseInt(text2.getText().toString());
Intent intent = new Intent(this, Ethernet_Service.class);
startService(intent);
}
}
// my service
package com.example.homeapp;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class Ethernet_Service extends Service{
public Ethernet_Service() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startid)
{
Ethernets eth = new Ethernets("I9001", "192.168.1.101", 4000);
eth.start();
return startid;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
// my ethernet thread class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import android.util.Log;
public class Ethernets extends Thread {
Thread ethernetThread, recieveThread;
Socket ethernetSocket;
PrintStream PW;
String IP;
int PORT;
boolean connect_status = false;
String Client_Name;
public Ethernets(String name, String ip, int port)
{
Client_Name = name;
PORT = port;
IP = ip;
}
public void run()
{
try
{
ethernetSocket = new Socket(IP,PORT);
if(ethernetSocket.isConnected() == true)
{
connect_status = true;
}
else{connect_status = false;}
PW = new PrintStream(ethernetSocket.getOutputStream(),true);
}catch(Exception ex){}
recieveThread = new Thread(new Runnable() {
#Override
public void run() {
String message;
try
{
BufferedReader BR = new BufferedReader(new InputStreamReader(ethernetSocket.getInputStream()));
while((message = BR.readLine()) != null)
{
System.out.println("message: "+message);
}
} catch (IOException e) {e.printStackTrace();}
}
});
recieveThread.start();
}
public void send(String msg)
{
//protocol description
byte[] buffer = {(byte) 0x02, (byte) 0x04, (byte) 'B', (byte) 0x02, 0x00, 0x00, (byte) 0x46 };
try
{
Log.i("hi","hi");
PW.write(buffer);
PW.flush();
} catch (IOException e) {e.printStackTrace();}
}
public boolean getconStatus()
{
return connect_status;
}
}

android:video is not playing

I am trying to run video which is stored in assets/pages/id(id may be rice or sugar or meat ect)/id.mp4 . In this app if i touch on a video of any item (rice or sugar or meat) it will play respective mp4 video. But video is not playing properly.
Trying to find out but fail.
Below is my code
package com.app.teachmesushi;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.AssetManager;
import android.graphics.PixelFormat;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.widget.MediaController;
import android.widget.VideoView;
import com.flurry.android.FlurryAgent;
public class VideoActivity extends Activity implements OnPreparedListener {
private VideoView video;
private MediaController ctlr;
private String id;
private File file;
private ProgressDialog pd = null;
private Integer msec = -1;
private int start = 1;
Messenger mService = null;
boolean mIsBound;
final Messenger mMessenger = new Messenger(new IncomingHandler());
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFormat(PixelFormat.TRANSLUCENT);
setContentView(R.layout.activity_video);
final String id = getIntent().getExtras().getString("id");
this.id = id;
if (savedInstanceState != null) {
msec = savedInstanceState.getInt("pos");
}
video = (VideoView) findViewById(R.id.video);
ctlr = new MediaController(this, false);
ctlr.setMediaPlayer(video);
video.setMediaController(ctlr);
video.setOnPreparedListener(this);
}
#Override
protected void onStart() {
super.onStart();
FlurryAgent.onStartSession(this, MainActivity.FLURRY_KEY);
Map<String, String> articleParams = new HashMap<String, String>();
articleParams.put("ID", id); // Capture user status
FlurryAgent.logEvent("Video", articleParams);
Log.e("sushi", "msec: " + msec);
Log.e("sushi", "start: " + start);
CheckIfServiceIsRunning();
String fileName = id + ".mp4";
file = new File(getExternalFilesDir(null), fileName);
if (file.exists()) {
video.setVideoPath(file.getPath());
} else {
// Show the ProgressDialog on this thread
pd = ProgressDialog.show(VideoActivity.this, "Launching video",
"Accessing...", true, false);
pd.dismiss();
// Start a new thread that will download all the data
new DownloadTask().execute(fileName);
}
if (msec != -1) {
video.seekTo(msec);
} else if (start == 1) {
start = 0;
video.start();
} else if (msec == video.getDuration()) {
video.seekTo(0);
}
}
#Override
public void onPause() {
super.onPause();
video.pause();
msec = video.getCurrentPosition();
pd.dismiss();
}
#Override
public void onStop() {
super.onStop();
video.pause();
msec = video.getCurrentPosition();
doUnbindService();
}
#Override
public void onDestroy() {
super.onDestroy();
video = null;
ctlr = null;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("pos", video.getCurrentPosition());
}
public void onPrepared(MediaPlayer mp) {
try {
video.requestFocus();
ctlr.show();
} catch (Exception e) {
}
}
class DownloadTask extends AsyncTask<String, Void, Object> {
protected Object doInBackground(String... args) {
AssetManager am = getAssets();
String fileName = args[0];
File file = new File(getExternalFilesDir(null), fileName);
Log.i("sushi", "Background thread starting");
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
try {
InputStream in = am.open("pages/" + id + "/" + id + ".mp4");
//InputStream in = am.open("http://176.9.35.93/tmc/videos/old/equipments.mp4");
FileOutputStream f = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
in.close();
} catch (Exception e) {
Log.d("sushi", e.getMessage());
}
if (VideoActivity.this.pd != null) {
VideoActivity.this.pd.dismiss();
VideoActivity.this.pd = null;
}
}
return null;
}
protected void onPostExecute(Object result) {
Intent intent = new Intent(VideoActivity.this, VideoActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Bundle b = new Bundle();
b.putString("id", id);
intent.putExtras(b);
startActivity(intent);
finish();
}
}
#Override
public void onBackPressed() {
try {
Log.d("sushi", "Deleting file");
file.delete();
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e("sushi", "File delete failed");
}
finish();
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mService = new Messenger(service);
try {
Message msg = Message.obtain(null,
TimerService.MSG_REGISTER_CLIENT);
msg.replyTo = mMessenger;
mService.send(msg);
} catch (RemoteException e) {
// In this case the service has crashed before we could even do
// anything with it
}
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected - process crashed.
mService = null;
}
};
private void CheckIfServiceIsRunning() {
// If the service is running when the activity starts, we want to
// automatically bind to it.
if (TimerService.isRunning()) {
doBindService();
} else {
Log.e("sushi", "Service not running");
}
}
void doBindService() {
bindService(new Intent(this, TimerService.class), mConnection,
Context.BIND_AUTO_CREATE);
mIsBound = true;
Log.e("sushi", "Bound to service");
}
void doUnbindService() {
if (mIsBound) {
// If we have received the service, and hence registered with it,
// then now is the time to unregister.
if (mService != null) {
try {
Message msg = Message.obtain(null,
TimerService.MSG_UNREGISTER_CLIENT);
msg.replyTo = mMessenger;
mService.send(msg);
} catch (RemoteException e) {
// There is nothing special we need to do if the service has
// crashed.
}
}
// Detach our existing connection.
unbindService(mConnection);
mIsBound = false;
}
}
class IncomingHandler extends Handler {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case TimerService.MSG_SET_INT_VALUE:
Log.e("sushi", String.valueOf(msg.arg1));
if (msg.arg1 <= 1) {
video.pause();
}
break;
default:
super.handleMessage(msg);
}
}
}
}
My Logcat error is
04-25 21:15:57.371: E/sushi(273): msec: -1
04-25 21:15:57.371: E/sushi(273): start: 1
04-25 21:15:57.381: E/sushi(273): Service not running
04-25 21:15:58.121: E/sushi(273): msec: -1
04-25 21:15:58.121: E/sushi(273): start: 1
04-25 21:15:58.121: E/sushi(273): Service not running
Pls help
Everything is ok. The problem is that i run this service in emulator not in real device. When i test in real device it is running properly. But problem in emulator.

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.

Categories

Resources