onBind() is never called in a service - android

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.

Related

Android: Making Volley HTTP Requests in the background

I am using Volley to make HTTP Calls in my android app. I have a requirement to poll a server every 5 seconds. This should happen even when the app is minimized(or when another app is opened). I am getting timeout errors when the app is minimized and you are on the Home Screen.
here is the code I am using.
AndroidManifest.xml
<application
...
<service android:name=".webviews.services.ScheduledService" android:enabled="true"></service>
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
ScheduledService.java
package com.magic.ultimate_android.webviews.services;
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONObject;
import java.util.Timer;
import java.util.TimerTask;
public class ScheduledService extends Service
{
Timer timer;
private static final String TAG = "ScheduledService";
String valueFromURL = "";
int requestCount = 0;
RequestQueue requestQueue;
#Override
public IBinder onBind(Intent intent)
{
Log.d(TAG, "On Bind called");
return null;
}
#Override
public void onCreate()
{
Log.d(TAG, "On Create called");
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "On Start Command called");
String action = intent.getAction();
if (action.equals("START_TIMER")) {
String urlInput = “https://jsonplaceholder.typicode.com/todos/1”;
String field = “title”;
Log.d(TAG, "Start Timer now******");
startTimer(urlInput, field);
} else if (action.equals("STOP_TIMER")) {
stopTimer();
}
return START_NOT_STICKY;
}
#Override
public void onDestroy()
{
super.onDestroy();
}
private void stopTimer() {
if (timer != null) {
timer.cancel();
}
}
private void startTimer(final String urlInput, final String field) {
timer = new Timer();
requestCount = 0;
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Log.d(TAG, "URL Input: " + urlInput + ", Field: " + field);
makeServiceCall(urlInput, field);
}
}, 0, 5000);
}
private void makeServiceCall(final String urlInput, final String field) {
Log.d(TAG, "Making Service call...");
RequestQueue requestQueue = getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, urlInput, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.d(TAG, "start of response");
if (!response.has(field)) {
return;
}
if ((String) response.get(field).equals(("TARGET_VALUE"))) {
makeServiceCall(urlInput, field);
} else {
if (timer != null) {
timer.cancel();
Log.d(TAG, "Timer is cancelled");
}
// TODO: SEND MESSAGE TO UPDATE THE APP
Intent intent = new Intent(“MESSAGE_TO_MAIN_APP");
// You can also include some extra data.
getApplicationContext().sendBroadcast(intent);
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Log.e(TAG, error.toString());
makeServiceCall(urlInput, field);
}
});
jsonObjectRequest.setShouldCache(false);
requestQueue.add(jsonObjectRequest);
}
private RequestQueue getRequestQueue() {
if (requestQueue == null) {
requestQueue = Volley.newRequestQueue(this);
}
return requestQueue;
}
}
MainActivity.java
Intent intent = new Intent(MainActivity.this, ScheduledService.class);
intent.setAction("START_TIMER");
startService(intent);
When the app is open and running, the code works perfectly fine. I see both the logs
Making Service Calls
start of response
But when the app is minimized, I see only the first one. And a volley error
com.android.volley.TimeoutError
Can you please help?

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>

ServiceConnection - Service throws NullPointerException

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

Android socket.io Service stop

how can i keep the socket active on the service, when i close the app it disconnected, from node, i call it from the main activity, with startService(new Intent(this, sys_service.class)); the socket its fine while the app its active
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
import com.github.nkzawa.emitter.Emitter;
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URISyntaxException;
public class sys_service extends Service {
Socket mSocket;
TelephonyManager manager;
JSONObject chat_response;
private Handler mHandler = new Handler();
String msg_over;
{
try {
mSocket = IO.socket("http://xxxx:8001");
} catch (URISyntaxException e) {
Toast.makeText(this, "refused", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
Toast.makeText(this,"Service Active :)", Toast.LENGTH_LONG ).show();
run_app();
return START_STICKY;
}
#Override
public void onDestroy() {
Toast.makeText(this,"Service stop :)", Toast.LENGTH_LONG ).show();
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent){
run_app();
return null;
}
public Socket getSocket() {
return mSocket;
}
public void run_app() {
mSocket.connect();
manager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
final JSONObject uidJson = new JSONObject();
String real = manager.getDeviceId();
try {
uidJson.put("uid", real);
} catch (JSONException e) {
e.printStackTrace();
}
mSocket.on("connect", new Emitter.Listener() {
public void call(Object... args) {
mSocket.emit("uid", uidJson);
}
});
mSocket.on("chat", new Emitter.Listener() {
public void call(Object... args) {
String chat_msg = args[0].toString();
try {
chat_response = new JSONObject(chat_msg);
} catch (JSONException e) {
e.printStackTrace();
}
msg_over = chat_response.optString("msg");
final JSONObject chat = new JSONObject();
try {
chat.put("msg", "all fine");
} catch (JSONException e) {
e.printStackTrace();
}
mSocket.emit("test", msg_over);
//Toast.makeText(StartActivity.this, msg, Toast.LENGTH_SHORT).show(); Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
Log.d("chat", msg_over);
}
});
}
}

Getting value in Service class from another class

I am creating a project in which I am getting data from a server and displaying it through table view. Here is the code for Main activity class
package com.example.e_quates;
import java.net.URL;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
//import com.websmithing.broadcasttest.BroadcastService;
//import com.websmithing.broadcasttest.BroadcastService;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup.LayoutParams;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
//import java.sql.SQLException;
public class MainActivity extends Activity {
List<String> strs = new ArrayList<String>();
ResultSet rs=null;
TableLayout tl;
TableRow[] tr;
TextView[] tv;
private Intent intent;
private static final String TAG = "E-Quates";
int count=1;
public static DB db = new DB(<connection string>);
String query = "select top(10) SymbolName,LTP,Net_change,Bid_vol,Ask,Ask_vol,High_Index from NCDX_LiveData_new";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
strs=db.sqlexec(query);
db.closeConnection();
Log.e("connected ","success");
System.out.println("connection sucess");
tl=(TableLayout)findViewById(R.id.table);
Log.e("first row","created");
tr=new TableRow[strs.size()/7];
tv=new TextView[strs.size()];
//int i=0;
for(int i=0,j=-1;i<strs.size();i++)
{
Log.e("index "+i,"value is "+strs.get(i));
if(i%7==0)
{
j++;
Log.e("inside if","value "+i);
tr[j]=new TableRow(this);
tr[j].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
}
tv[i] = new TextView(this);
tv[i].setText(strs.get(i));
tv[i].setId(i);
tv[i].setBackgroundResource(R.drawable.row_shape);
tr[j].addView(tv[i]);
}
for(int i=0,j=-1;i<strs.size()/7;i++)
{
tl.addView(tr[i]);
Log.e("adding row",""+i);
}
//Thread.sleep(5000);
}
catch(Exception E)
{
System.out.println(E.toString());
}
intent = new Intent(this, BroadcastService.class);
}
public void onResume() {
super.onResume();
startService(intent);
Log.e("service","called");
registerReceiver(broadcastReceiver, new IntentFilter(BroadcastService.BROADCAST_ACTION));
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
stopService(intent);
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.e("in the","receiver");
updateUI(intent);
}
};
private void updateUI(Intent intent) {
strs.clear();
//String dummy = null;
Log.e("inside ","UI update");
//db.sqlexec(query);
try
{
strs = intent.getStringArrayListExtra("TAG");
//application_main apm=((application_main) getApplicationContext());
for(int i=0;i<strs.size();i++)
{
Log.e("inside for","loo[");
tv[i].setText(strs.get(i));
}
}
catch(Exception e)
{
Log.e("exception occured in intent value",e.toString());
}
//Log.e("value is ",dummy.toString());
//Thread.sleep(5000);
}
}
Here is my DB class
package com.example.e_quates;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
//import android.widget.*;
class DB extends Activity
{
List<String> strs = new ArrayList<String>();
ResultSet rs=null;
Connection conn=null;
private Intent intent;
#SuppressLint("NewApi")
String query = "select top(10) SymbolName,LTP,Net_change,Bid_vol,Ask,Ask_vol,High_Index from NCDX_LiveData_new";
public DB(String db_connect_string,String db_userid,String db_password) {
System.out.println("inside DB");
Log.e("inside DB","");
try
{
StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Log.e("Inside first","try block");
Class.forName("net.sourceforge.jtds.jdbc.Driver");
conn = DriverManager.getConnection(db_connect_string, db_userid, db_password);
Log.e("Connection sucessfull","");
}catch (Exception e)
{
e.printStackTrace();
}
}
public List<String> sqlexec(String sql)
{
try
{
Statement stmt = null;
strs.clear();
try {
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
Log.e("##########################################################################3","result in rs");
while (rs.next()) {
strs.add(rs.getString("SymbolName"));
strs.add(rs.getString("LTP"));
strs.add(rs.getString("Net_change"));
strs.add(rs.getString("Bid_vol"));
strs.add(rs.getString("Ask"));
strs.add(rs.getString("Ask_vol"));
strs.add(rs.getString("High_Index"));
Log.e("symbolname",rs.getString("SymbolName"));
}
}catch (Exception e)
{
e.printStackTrace();
}
}
catch(Exception e)
{
Log.e("error:",e.toString());
}
Log.e("return ","to main");
int size=strs.size();
Log.e("array size in DB",""+size);
//Log.e("set string",String.valueOf(apm.getState()));
Log.e("application ","initialized");
return strs;
}
public void closeConnection()
{
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
And here is the service class
package com.example.e_quates;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
public class BroadcastService extends Service {
List<String> strs_array1 = new ArrayList<String>();
private static final String TAG = "E-Quates";
public static final String BROADCAST_ACTION = "com.example.e_quates";
private final Handler handler = new Handler();
Intent intent;
String query = "select top(10) SymbolName,LTP,Net_change,Bid_vol,Ask,Ask_vol,High_Index from NCDX_LiveData_new";
int counter = 0;
DB db1=new DB(<connection string>);
//String dummy;
#Override
public void onCreate() {
super.onCreate();
//db1.forService();
intent = new Intent(BROADCAST_ACTION);
}
#Override
public void onStart(Intent intent, int startId) {
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 3000); // 3 second
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
DisplayLoggingInfo();
handler.postDelayed(this, 3000); // 3 seconds
}
};
private void DisplayLoggingInfo() {
Log.d(TAG, "entered DisplayLoggingInfo");
strs_array1=db1.sqlexec(query);
intent.putStringArrayListExtra(TAG, (ArrayList<String>)strs_array1);
sendBroadcast(intent);
Log.e("Broadcast","done");
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
handler.removeCallbacks(sendUpdatesToUI);
super.onDestroy();
}
}
The problem is that when I am calling the DB class's sqlexec() function from main activity class it is return correct value but while is I am calling it service class it is not returning the SQL output. I have tried every possible combination of calling the sqlexec() function inside the service class,but same problem is occurring.
the function db.sqlexec(query) is not returning any value..
I have referred the link for help:
Don't do any initialization in the Service constructor. Android constructs Android components (Activity, Service, BroadcastReceiver, ContentProvider) using its own mechanisms. Move all your initialization code from the constructor to the onCreate() method.
EDIT: Clarify my instructions
I am referring to this code:
List<String> strs_array1 = new ArrayList<String>();
private static final String TAG = "E-Quates";
public static final String BROADCAST_ACTION = "com.example.e_quates";
private final Handler handler = new Handler();
Intent intent;
String query = "select top(10) SymbolName,LTP,Net_change,Bid_vol,Ask,Ask_vol,High_Index from NCDX_LiveData_new";
int counter = 0;
DB db1=new DB(<connection string>);
These variables will be initialized in the constructor (even though you haven't explicitly created a constructor, one will be created for you). The constants aren't a problem, but these may cause you a problem:
private final Handler handler = new Handler();
DB db1=new DB(<connection string>);
You will want to be creating the Handler in onCreate(). I don't know what your DB class is doing, but you probably want to be creating that instance also in onCreate().
EDIT 2
I now see the code for your DB class. You can't do this like this! Your DB class extends Activity. You cannot create an instance of this class like this:
DB db1=new DB(<connection string>);
Android components (Activity, Service, BroadcastReceiver, ContentProvider) are created by the Android framework using its own mechanisms.
Why does your DB class extend Activity? It doesn't need to.

Categories

Resources