Sharing one service between two activities without destroying it? - java

I'm working on an application to communicate with a raspberry pi. The app communicates with the server via a socket connection.
I'm currently able to building up the communication and holding it in a service. But my goal is to change from activity A to activity B. The problem is, that my application destroys the service when im switching the activities. Is there a way to avoid this?
Activity A starts the service and when im starting Activity B i bind it to the activity to call the methods in the service class. But it isn't the same instance.
How could i solve this?
Code
ConnectActivity
package com.example.domen.twitchdronev3;
import android.content.Intent;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class ConnectActivity extends AppCompatActivity {
private int port = 3000;
private String ip = "localhost";
private Intent serviceIntent, activityIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connect);
Toast.makeText(getApplicationContext(), "Starte App...", Toast.LENGTH_LONG).show();
activityIntent = new Intent(this, ControllActivity.class);
serviceIntent = new Intent(this, ClientService.class);
serviceIntent.putExtra("ip", ip);
serviceIntent.putExtra("port", port);
Button btnActivity = (Button) findViewById(R.id.changeActivity);
btnActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startService(serviceIntent);
activityIntent.putExtra("Intent", (Parcelable) serviceIntent);
startActivity(activityIntent);
}
});
}
// destroys the Activity
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(getApplicationContext(), "Destroy (ConnectActivity)", Toast.LENGTH_LONG).show();
}
// Activity stopping
#Override
protected void onStop() {
super.onStop();
}
}
ControllActivity
package com.example.domen.twitchdronev3;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class ControllActivity extends AppCompatActivity {
public static final String TAG = "ControllActivity";
private ClientService clientservice;
private Intent serviceIntent;
private boolean isBound;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_controll);
Bundle extras = getIntent().getExtras();
serviceIntent = extras.getParcelable("Intent");
Button btnDisconnect = (Button) findViewById(R.id.btnDisconnect);
btnDisconnect.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
doBindToService();
}
});
}
// destroys the Activity
#Override
public void onDestroy(){
super.onDestroy();
Toast.makeText(getApplicationContext(), "Destroy (ControllActivity)", Toast.LENGTH_LONG).show();
doUnbindToService();
stopService(serviceIntent);
}
// Functions to BIND and UNBIND the SERVICE
// bind to Service
public void doBindToService(){
if(!isBound) {
Toast.makeText(this, "(doBindToService) Binding...", Toast.LENGTH_LONG).show();
isBound = bindService(serviceIntent, myConnection, Context.BIND_AUTO_CREATE);
}
}
// Unbind to Service
public void doUnbindToService(){
Toast.makeText(this, "(doUnbindToService) Unbinding...", Toast.LENGTH_LONG).show();
unbindService(myConnection);
isBound = false;
}
private ServiceConnection myConnection = new ServiceConnection(){
public static final String TAG = "ConnectActivity";
#Override
public void onServiceConnected(ComponentName className, IBinder service){
Log.i(TAG, "BOUND SERVICE CONNECTED");
clientservice = ((ClientService.ClientBinder) service).getService();
isBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name){
Log.i(TAG, "BOUND SERVICE DISCONNECTED");
clientservice = null;
isBound = false;
}
};
}
ClientService
package com.example.domen.twitchdronev3;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
/**
* Created by ViTrex on 12.02.2018.
*/
public class ClientService extends Service {
private static final String TAG = "ClientService";
private final IBinder mBinder = new ClientBinder();
private PrintWriter out;
private Socket socket;
private String ip = "";
private int port = 0;
private Thread backgroundThread;
// the class used for the client binder
public class ClientBinder extends Binder {
ClientService getService() {
// returns the instance of ClientService
// so the client can access the public methods
return ClientService.this;
}
}
//SETTER
public void setIP(String ip) {
this.ip = ip;
}
public void setPort(int port) {
this.port = port;
}
//GETTER
public String getIP() {
return this.ip;
}
public int getPort() {
return this.port;
}
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate...");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "onStartCommand", Toast.LENGTH_LONG).show();
if(intent != null){
setIP(intent.getStringExtra("ip"));
setPort(intent.getIntExtra("port", 3000));
}
return START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "onBind called...");
Toast.makeText(this, getIP() + " " + getPort(), Toast.LENGTH_LONG).show();
backgroundThread = new Thread(new Runnable() {
#Override
public void run() {
buildConnection();
}
});
backgroundThread.start();
return mBinder;
}
private void buildConnection() {
Log.i(TAG, "Try to build up a connection ...");
synchronized (this) {
try {
this.socket = new Socket(getIP(), getPort());
this.out = new PrintWriter(this.socket.getOutputStream(), true);
Log.i(TAG, "Connected");
} catch (IOException ioe) {
Log.i(TAG, ioe.getMessage());
this.socket = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "Close Service");
Thread dummy = backgroundThread;
backgroundThread = null;
if (dummy != null)
dummy.interrupt();
if (this.socket != null) {
try {
this.out.close();
this.socket.close();
Log.i(TAG, "Close Socket");
} catch (IOException ioe) {
Log.i(TAG, "ERROR: Close Socket");
}
}
}
}

You say:
Activity A starts the service and when I'm starting Activity B I bind
it to the activity to call the methods in the service class. But it
isn't the same instance.
How do you know it is not the same instance (presumably you mean of the service instance)?
I think your code is o.k. to run on older devices (It runs o.k. on my device. pre-API26, I think permissions changed after then so maybe more code needed. See NOTE at the end of this answer).
Don't you want START_STICKY ?
I would add this code (read the Intent data that was setup by Activity A) to your ClientService.java:
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
String a_ip = intent.getStringExtra("ip");
int a_port = intent.getIntExtra("port",-1);
Log.i(TAG, "onStartCommand called...with " + "ip:" + a_ip + "and port:"+ a_port);
setIP(a_ip);
setPort(a_port);
return START_NOT_STICKY;//don't you want START_STICKY ?
}
Note: If your app targets API level 26 or higher, the system imposes
restrictions on using or creating background services unless the app
itself is in the foreground. If an app needs to create a foreground
service, the app should call StartForegroundService(). That method
creates a background service, but the method signals to the system
that the service will promote itself to the foreground. Once the
service has been created, the service must call its startForeground()
method within five seconds. From here

Related

App keeps crashing cause of broadcastreceiver

Can anyone help me debug which part of my code is the reason why it keeps crashing? I've been trying to figure out which part is wrong, I got the code online and applied it on my own but I had troubles on this part where it keeps saying app is
I created different functions to figure out which part is wrong, thank you.
in my logcat it says:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.intern()' on a null object reference
Mainactivty
import androidx.appcompat.app.AppCompatActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private TextView tv_time;
private TextView tv_amount;
private ImageView iv_status_01;
private ImageView iv_status_02;
private ImageView iv_status_03;
private ImageView iv_status_04;
private ImageView iv_status_05;
private ImageView iv_status_06;
private ImageView iv_complete;
private Intent serviceInent = null;
public static String status1;
public static String status2;
public static String status3;
public static String status4;
public static String status5;
public static String status6;
private IntentFilter intentFilter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intentFilter = new IntentFilter();
intentFilter.addAction(status1);
intentFilter.addAction(status2);
intentFilter.addAction(status3);
intentFilter.addAction(status4);
intentFilter.addAction(status5);
intentFilter.addAction(status6);
init();
}
private void init(){
tv_amount = findViewById(R.id.tv_amount);
tv_time = findViewById(R.id.tv_time);
Date date = new Date();
Locale philippineLocale = new Locale.Builder().setLanguage("en").setRegion("PH").build();
tv_time.setText(getDate(date, philippineLocale));
tv_amount.setText("Total Amount :\n500.00");
serviceInent = new Intent(this, DeliveryService.class);
startService(new Intent(this, DeliveryService.class));
}
private String getDate(Date date, Locale locale) {
DateFormat formatter = new SimpleDateFormat("EEEE \nMMMM dd, yyyy", locale);
return formatter.format(date);
}
#Override
public void onResume() {
super.onResume();
registerReceiver(mReceiver, intentFilter);
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(status1)) {
iv_status_01.setImageResource(R.drawable.box_check);
}
else if (intent.getAction().equals(status2)) {
iv_status_02.setImageResource(R.drawable.box_check);
}
else if (intent.getAction().equals(status3)) {
iv_status_03.setImageResource(R.drawable.box_check);
}
else if (intent.getAction().equals(status4)) {
iv_status_04.setImageResource(R.drawable.box_check);
}
else if (intent.getAction().equals(status5)) {
iv_status_05.setImageResource(R.drawable.box_check);
}
else if (intent.getAction().equals(status5)) {
iv_status_06.setImageResource(R.drawable.box_check);
}
}
};
#Override
protected void onPause() {
unregisterReceiver(mReceiver);
super.onPause();
}
}
Deliveryservice:
import android.annotation.TargetApi;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
public class DeliveryService extends Service {
private String LOG_TAG = null;
#Override
public void onCreate() {
super.onCreate();
LOG_TAG = this.getClass().getSimpleName();
Log.i(LOG_TAG, "In onCreate");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(LOG_TAG, "In onStartCommand");
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(MainActivity.status1);
sendBroadcast(broadcastIntent);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
broadcastIntent.setAction(MainActivity.status2);
sendBroadcast(broadcastIntent);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
broadcastIntent.setAction(MainActivity.status3);
sendBroadcast(broadcastIntent);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
broadcastIntent.setAction(MainActivity.status4);
sendBroadcast(broadcastIntent);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
broadcastIntent.setAction(MainActivity.status5);
sendBroadcast(broadcastIntent);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
broadcastIntent.setAction(MainActivity.status6);
sendBroadcast(broadcastIntent);
}
}).start();
return START_REDELIVER_INTENT;
}
#Override
public IBinder onBind(Intent intent) {
Log.i(LOG_TAG, "In onBind");
return null;
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Log.i(LOG_TAG, "In onTaskRemoved");
}
public void onDestroy() {
super.onDestroy();
Log.i(LOG_TAG, "In onDestroy");
}
}
thank you.
You should initialize strings used as Action (like status1); otherwise, NullProinterException will be thrown.

Trying to keep MQTT client connection even when app is closed

I am currently using MQTT protocol in my android app and I am able to receive messages when my app is open or when it is running in the background however when i close my app completely the connection is lost and I am not longer able to receive messages. I need to be able to still recieve messages as I want the message to trigger an activity in my app to launch. Here are the files that I am using to implement MQTT. MQTTHelper class: EDIT. Ive have tried to implement a service but it still doesnt seem to be working.Does Anyone know what I am doing wrong?
package com.example.carcrashdetection.helpers;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
public class MqttHelper extends Service {
public MqttAndroidClient mqttAndroidClient;
BroadcastReceiver m_ScreenOffReceiver;
final String serverUri = "tcp://hairdresser.cloudmqtt.com:15767";
final String clientId = "CarCrashDetection";
final String subscriptionTopic = "Topic/+";
final String username = "username";
final String password = "password";
#Override
public void onCreate() {
super.onCreate();
registerReceiver();
new Thread(new Runnable() {
#Override
public void run() {
MqttHelper.this.connect();
}
}).start();
}
public MqttHelper(Context context){
mqttAndroidClient = new MqttAndroidClient(context, serverUri, clientId);
mqttAndroidClient.setCallback(new MqttCallback() {
public void connectComplete(boolean b, String s) {
}
#Override
public void connectionLost(Throwable throwable) {
}
#Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
Log.w("Mqtt", mqttMessage.toString());
}
#Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
});
connect();
}
public void setCallback(MqttCallback callback) {
mqttAndroidClient.setCallback(callback);
}
private void connect(){
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setAutomaticReconnect(true);
mqttConnectOptions.setCleanSession(false);
mqttConnectOptions.setUserName(username);
mqttConnectOptions.setPassword(password.toCharArray());
try {
mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
disconnectedBufferOptions.setBufferEnabled(true);
disconnectedBufferOptions.setBufferSize(100);
disconnectedBufferOptions.setPersistBuffer(false);
disconnectedBufferOptions.setDeleteOldestMessages(false);
mqttAndroidClient.setBufferOpts(disconnectedBufferOptions);
subscribeToTopic();
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.w("Mqtt", "Failed to connect to: " + serverUri + exception.toString());
}
});
} catch (MqttException ex){
ex.printStackTrace();
}
}
private void subscribeToTopic() {
try {
mqttAndroidClient.subscribe(subscriptionTopic, 0, null, new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.w("Mqtt","Subscribed!");
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.w("Mqtt", "Subscribed fail!");
}
});
} catch (MqttException ex) {
System.err.println("Exception whilst subscribing");
ex.printStackTrace();
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//do something
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void registerReceiver(){
m_ScreenOffReceiver = new BroadcastReceiver(){
#Override
public void onReceive(final Context context, Intent intent){
//Log.d(TAG,"onReceive of Wifi_State_Change called");
if(intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION))
{
int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN);
if(wifiState != WifiManager.WIFI_STATE_ENABLED)
return;
final WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ssid = wifiInfo.getSSID();
Toast.makeText(context, "active wifi:" + ssid, Toast.LENGTH_SHORT).show();
//You can connect to the your mqtt broker again:
connect();
}
}, 10000);
}
}
};
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
registerReceiver(m_ScreenOffReceiver, intentFilter);
}
#Override
public void onDestroy() {
if(mqttAndroidClient!=null) {
/*unregisterResources is needed,otherwise receive this error:
has leaked ServiceConnection org.eclipse.paho.android.service.MqttAndroidClient*/
try {
mqttAndroidClient.unregisterResources();
mqttAndroidClient.close();
mqttAndroidClient.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
unregisterReceiver(m_ScreenOffReceiver);
m_ScreenOffReceiver = null;
super.onDestroy();
}
}
MainActivity
private void startMqtt(){
mqttHelper = new MqttHelper(getApplicationContext());
mqttHelper.setCallback(new MqttCallbackExtended(){
#Override
public void connectComplete(boolean b, String s) {
Toast.makeText(MainActivity.this, "connected ", Toast.LENGTH_SHORT).show();
}
public void connectionLost(Throwable throwable){
Toast.makeText(MainActivity.this,"Disconnected", Toast.LENGTH_SHORT).show();
}
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception{
Log.e("message ", String.valueOf(mqttMessage));
Toast.makeText(MainActivity.this, "Crash Occurred", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, alert.class);
startActivity(intent);
}
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken){
}
});
}
I've been searching for a while now but cant seem to find anything that works. I thought it would be an easy fix but its hasn't been for me. Any help would be much appreciated.
Your options will be to implement a server that will send your device push notifications and then your app can fetch the message once it is open again.
Alternatively you can implement a background service: https://developer.android.com/guide/components/services

Can i make a background service that always runs a speech recognition

i want to make an application that i can run it over voice like siri or google assistant, so in order to make it i have to implement the code in a background or foreground service which will run speech recognizer
so is this possible,because of the limitation of the working services on android Oreo and higher this make me stuck in the middle of nowhere
and i'm not so professional so i could figure this out myself
i have tried to make a foreground service with IntentService so that it could make the work on the background without freezing the UI
and the Speech recognizer didn't work
package com.example.intentservice;
import android.app.IntentService;
import android.app.Notification;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.SystemClock;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.Nullable;
import java.util.List;
import java.util.Locale;
import static com.example.intentservice.App.CHANNEL_ID;
public class ExampleService extends IntentService {
public static final String TAG = "ExampleService";
private PowerManager.WakeLock wakeLock;
private TextToSpeech textToSpeech;
private SpeechRecognizer recognizer;
#Override
public void onCreate() {
super.onCreate();
Log.e(TAG, "onCreate");
initRec();
startListening();
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ExampleService:wakelock");
wakeLock.acquire();
Log.e(TAG, "wakelock acquired");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Notification notification = new Notification.Builder(this, CHANNEL_ID)
.setContentTitle("noti")
.setContentText("running")
.build();
startForeground(1, notification);
}
}
private void startListening() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,1);
recognizer.startListening(intent);
}
private void initRec() {
if (SpeechRecognizer.isRecognitionAvailable(this)) {
recognizer = SpeechRecognizer.createSpeechRecognizer(this);
recognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
}
#Override
public void onResults(Bundle bundle) {
List<String> res = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
Toast.makeText(ExampleService.this, res.get(0), Toast.LENGTH_SHORT).show();
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
});
}
}
public ExampleService() {
super("ExampleService");
// to create service again
setIntentRedelivery(true);
}
// this just to test the code
#Override
protected void onHandleIntent(#Nullable Intent intent) {
Log.e(TAG, "onHandleIntent");
String string = intent.getStringExtra("key");
for (int i = 0; i < 10; i++) {
Log.e(TAG, string + "-" + i);
// Toast.makeText(this, "i", Toast.LENGTH_SHORT).show();
SystemClock.sleep(1000);
}
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e(TAG, "onDestroy");
wakeLock.release();
Log.e(TAG, "wakelock realised");
}
}

long life service and broadcastreceiver

i write application that send outgoing call number from android to server.
here is my code:
service.java
package info;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class ServiceToSendData extends Service {
// private static final String TAG = "HelloService";
public static boolean isRunning = false;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
isRunning = true;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(new Runnable() {
#Override
public void run() {
}
}).start();
return Service.START_STICKY;
}
#Override
public void onDestroy() {
isRunning = false;
}
}
outgoingCall Reciver
import org.json.JSONException;
import org.json.JSONObject;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.StrictMode;
public class OutgoingCallReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
// Log.i("Outgoing Call", "call to: " + phoneNumber);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("type", "outgoingCall");
}
catch (JSONException e) {
e.printStackTrace();
}
try {
jsonObject.put("number", phoneNumber);
}
catch (JSONException e) {
e.printStackTrace();
}
try {
jsonObject.put("content", "0");
}
catch (JSONException e) {
e.printStackTrace();
}
if (phoneNumber != null) {
sendDataToServer sdts = new sendDataToServer();
sdts.run(jsonObject, context);
}
Intent startServiceIntent = new Intent(context, ServiceToSendData.class);
context.startService(startServiceIntent);
}
}
explain problem
1-this code work good if app was open or app is minimized, but when i close the app code not work , and nullpointerexception problem ?
2-any way to access database with context from service?
thanks in advance.

How to send data from an Android device to pc through serial port over USB

I have found this Serial Port example:
MainActivity.java
package com.felhr.serialportexample;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.lang.ref.WeakReference;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
/*
* Notifications from UsbService will be received here.
*/
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case UsbService.ACTION_USB_PERMISSION_GRANTED: // USB PERMISSION GRANTED
Toast.makeText(context, "USB Ready", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_PERMISSION_NOT_GRANTED: // USB PERMISSION NOT GRANTED
Toast.makeText(context, "USB Permission not granted", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_NO_USB: // NO USB CONNECTED
Toast.makeText(context, "No USB connected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_DISCONNECTED: // USB DISCONNECTED
Toast.makeText(context, "USB disconnected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_NOT_SUPPORTED: // USB NOT SUPPORTED
Toast.makeText(context, "USB device not supported", Toast.LENGTH_SHORT).show();
break;
}
}
};
private UsbService usbService;
private TextView display;
private EditText editText;
private MyHandler mHandler;
private final ServiceConnection usbConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
usbService = ((UsbService.UsbBinder) arg1).getService();
usbService.setHandler(mHandler);
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
usbService = null;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler = new MyHandler(this);
display = (TextView) findViewById(R.id.textView1);
editText = (EditText) findViewById(R.id.editText1);
Button sendButton = (Button) findViewById(R.id.buttonSend);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!editText.getText().toString().equals("")) {
String data = editText.getText().toString();
if (usbService != null) { // if UsbService was correctly binded, Send data
display.append(data);
usbService.write(data.getBytes());
}
}
}
});
}
#Override
public void onResume() {
super.onResume();
setFilters(); // Start listening notifications from UsbService
startService(UsbService.class, usbConnection, null); // Start UsbService(if it was not started before) and Bind it
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(mUsbReceiver);
unbindService(usbConnection);
}
private void startService(Class<?> service, ServiceConnection serviceConnection, Bundle extras) {
if (!UsbService.SERVICE_CONNECTED) {
Intent startService = new Intent(this, service);
if (extras != null && !extras.isEmpty()) {
Set<String> keys = extras.keySet();
for (String key : keys) {
String extra = extras.getString(key);
startService.putExtra(key, extra);
}
}
startService(startService);
}
Intent bindingIntent = new Intent(this, service);
bindService(bindingIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
private void setFilters() {
IntentFilter filter = new IntentFilter();
filter.addAction(UsbService.ACTION_USB_PERMISSION_GRANTED);
filter.addAction(UsbService.ACTION_NO_USB);
filter.addAction(UsbService.ACTION_USB_DISCONNECTED);
filter.addAction(UsbService.ACTION_USB_NOT_SUPPORTED);
filter.addAction(UsbService.ACTION_USB_PERMISSION_NOT_GRANTED);
registerReceiver(mUsbReceiver, filter);
}
/*
* This handler will be passed to UsbService. Data received from serial port is displayed through this handler
*/
private static class MyHandler extends Handler {
private final WeakReference<MainActivity> mActivity;
public MyHandler(MainActivity activity) {
mActivity = new WeakReference<>(activity);
}
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UsbService.MESSAGE_FROM_SERIAL_PORT:
String data = (String) msg.obj;
mActivity.get().display.append(data);
break;
}
}
}
}
and UsbService.java
package com.felhr.serialportexample;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import com.felhr.usbserial.CDCSerialDevice;
import com.felhr.usbserial.UsbSerialDevice;
import com.felhr.usbserial.UsbSerialInterface;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
public class UsbService extends Service {
public static final String ACTION_USB_READY = "com.felhr.connectivityservices.USB_READY";
public static final String ACTION_USB_ATTACHED = "android.hardware.usb.action.USB_DEVICE_ATTACHED";
public static final String ACTION_USB_DETACHED = "android.hardware.usb.action.USB_DEVICE_DETACHED";
public static final String ACTION_USB_NOT_SUPPORTED = "com.felhr.usbservice.USB_NOT_SUPPORTED";
public static final String ACTION_NO_USB = "com.felhr.usbservice.NO_USB";
public static final String ACTION_USB_PERMISSION_GRANTED = "com.felhr.usbservice.USB_PERMISSION_GRANTED";
public static final String ACTION_USB_PERMISSION_NOT_GRANTED = "com.felhr.usbservice.USB_PERMISSION_NOT_GRANTED";
public static final String ACTION_USB_DISCONNECTED = "com.felhr.usbservice.USB_DISCONNECTED";
public static final String ACTION_CDC_DRIVER_NOT_WORKING = "com.felhr.connectivityservices.ACTION_CDC_DRIVER_NOT_WORKING";
public static final String ACTION_USB_DEVICE_NOT_WORKING = "com.felhr.connectivityservices.ACTION_USB_DEVICE_NOT_WORKING";
public static final int MESSAGE_FROM_SERIAL_PORT = 0;
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
private static final int BAUD_RATE = 9600; // BaudRate. Change this value if you need
public static boolean SERVICE_CONNECTED = false;
private IBinder binder = new UsbBinder();
private Context context;
private Handler mHandler;
private UsbManager usbManager;
private UsbDevice device;
private UsbDeviceConnection connection;
private UsbSerialDevice serialPort;
private boolean serialPortConnected;
/*
* Data received from serial port will be received here. Just populate onReceivedData with your code
* In this particular example. byte stream is converted to String and send to UI thread to
* be treated there.
*/
private UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() {
#Override
public void onReceivedData(byte[] arg0) {
try {
String data = new String(arg0, "UTF-8");
if (mHandler != null)
mHandler.obtainMessage(MESSAGE_FROM_SERIAL_PORT, data).sendToTarget();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
};
/*
* Different notifications from OS will be received here (USB attached, detached, permission responses...)
* About BroadcastReceiver: http://developer.android.com/reference/android/content/BroadcastReceiver.html
*/
private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
if (arg1.getAction().equals(ACTION_USB_PERMISSION)) {
boolean granted = arg1.getExtras().getBoolean(UsbManager.EXTRA_PERMISSION_GRANTED);
if (granted) // User accepted our USB connection. Try to open the device as a serial port
{
Intent intent = new Intent(ACTION_USB_PERMISSION_GRANTED);
arg0.sendBroadcast(intent);
connection = usbManager.openDevice(device);
serialPortConnected = true;
new ConnectionThread().run();
} else // User not accepted our USB connection. Send an Intent to the Main Activity
{
Intent intent = new Intent(ACTION_USB_PERMISSION_NOT_GRANTED);
arg0.sendBroadcast(intent);
}
} else if (arg1.getAction().equals(ACTION_USB_ATTACHED)) {
if (!serialPortConnected)
findSerialPortDevice(); // A USB device has been attached. Try to open it as a Serial port
} else if (arg1.getAction().equals(ACTION_USB_DETACHED)) {
// Usb device was disconnected. send an intent to the Main Activity
Intent intent = new Intent(ACTION_USB_DISCONNECTED);
arg0.sendBroadcast(intent);
serialPortConnected = false;
serialPort.close();
}
}
};
/*
* onCreate will be executed when service is started. It configures an IntentFilter to listen for
* incoming Intents (USB ATTACHED, USB DETACHED...) and it tries to open a serial port.
*/
#Override
public void onCreate() {
this.context = this;
serialPortConnected = false;
UsbService.SERVICE_CONNECTED = true;
setFilter();
usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
findSerialPortDevice();
}
/* MUST READ about services
* http://developer.android.com/guide/components/services.html
* http://developer.android.com/guide/components/bound-services.html
*/
#Override
public IBinder onBind(Intent intent) {
return binder;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
UsbService.SERVICE_CONNECTED = false;
}
/*
* This function will be called from MainActivity to write data through Serial Port
*/
public void write(byte[] data) {
if (serialPort != null)
serialPort.write(data);
}
public void setHandler(Handler mHandler) {
this.mHandler = mHandler;
}
private void findSerialPortDevice() {
// This snippet will try to open the first encountered usb device connected, excluding usb root hubs
HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
if (!usbDevices.isEmpty()) {
boolean keep = true;
for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
device = entry.getValue();
int deviceVID = device.getVendorId();
int devicePID = device.getProductId();
if (deviceVID != 0x1d6b && (devicePID != 0x0001 || devicePID != 0x0002 || devicePID != 0x0003)) {
// There is a device connected to our Android device. Try to open it as a Serial Port.
requestUserPermission();
keep = false;
} else {
connection = null;
device = null;
}
if (!keep)
break;
}
if (!keep) {
// There is no USB devices connected (but usb host were listed). Send an intent to MainActivity.
Intent intent = new Intent(ACTION_NO_USB);
sendBroadcast(intent);
}
} else {
// There is no USB devices connected. Send an intent to MainActivity
Intent intent = new Intent(ACTION_NO_USB);
sendBroadcast(intent);
}
}
private void setFilter() {
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_USB_PERMISSION);
filter.addAction(ACTION_USB_DETACHED);
filter.addAction(ACTION_USB_ATTACHED);
registerReceiver(usbReceiver, filter);
}
/*
* Request user permission. The response will be received in the BroadcastReceiver
*/
private void requestUserPermission() {
PendingIntent mPendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
usbManager.requestPermission(device, mPendingIntent);
}
public class UsbBinder extends Binder {
public UsbService getService() {
return UsbService.this;
}
}
/*
* A simple thread to open a serial port.
* Although it should be a fast operation. moving usb operations away from UI thread is a good thing.
*/
private class ConnectionThread extends Thread {
#Override
public void run() {
serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection);
if (serialPort != null) {
if (serialPort.open()) {
serialPort.setBaudRate(BAUD_RATE);
serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8);
serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1);
serialPort.setParity(UsbSerialInterface.PARITY_NONE);
serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
serialPort.read(mCallback);
// Everything went as expected. Send an intent to MainActivity
Intent intent = new Intent(ACTION_USB_READY);
context.sendBroadcast(intent);
} else {
// Serial port could not be opened, maybe an I/O error or if CDC driver was chosen, it does not really fit
// Send an Intent to Main Activity
if (serialPort instanceof CDCSerialDevice) {
Intent intent = new Intent(ACTION_CDC_DRIVER_NOT_WORKING);
context.sendBroadcast(intent);
} else {
Intent intent = new Intent(ACTION_USB_DEVICE_NOT_WORKING);
context.sendBroadcast(intent);
}
}
} else {
// No driver for given device, even generic CDC driver could not be loaded
Intent intent = new Intent(ACTION_USB_NOT_SUPPORTED);
context.sendBroadcast(intent);
}
}
}
}
In this app you can type a string, send it and it will print it. What I want to do is send that input through an FTDI to a pc where it is visible in PuTTy. I'm new to this so I have no idea where in the code this has to be changed.
It seeems very old but I solved that by adding in Handle message handler case UsbService.SYNC_READ:
and actually i found that data coming from the serial.

Categories

Resources