Why the code in schedule Task Execution fixed Rate not working? - java

I am trying to add feature of Sheduled Task in android to do something after a time like I want to know whenever user loss his internet connection then I want to make a alert dialog. So I am doing it using Sheduled Task Execution but whenever I putted my run code in Runnable, Task didnot work.
Important is I am doing this in service class
CODE IS
package com.example.sid.marwadishaadi.LoginHistory;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.widget.Toast;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import static com.bumptech.glide.gifdecoder.GifHeaderParser.TAG;
public class OnClearFromRecentService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("ClearFromRecentService-", "-----------------------------------------Service Started");
SharedPreferences sharedPreferences=getSharedPreferences("userinfo",MODE_PRIVATE);
SharedPreferences.Editor edtr=sharedPreferences.edit();
String id=sharedPreferences.getString("customer_id","");
Log.e(TAG, "onStartCommand: .........................."+id);
if(isOnline()) {
Toast.makeText(this, "You are online", Toast.LENGTH_SHORT).show();
}
ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
Log.i(TAG, "run: ----I'm running after 15 seconds");
if(isOnline()) {
//Dummy TODO, you can do something if you want,
Toast.makeText(OnClearFromRecentService.this, "You are not online", Toast.LENGTH_SHORT).show();
}
else{
Log.i(TAG, "run: --- exited from here or not :::: yes ");
AlertDialog.Builder network =new AlertDialog.Builder(OnClearFromRecentService.this);
network.setTitle("No Internet");
network.setMessage("Please check your internet connection or go to the internet option by clicking #settings");
network.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
getApplicationContext().startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
});
network.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
network.setCancelable(false);
AlertDialog alertDialog = network.create();
alertDialog.show();
}
}
}, 0, 15, TimeUnit.SECONDS);
return START_NOT_STICKY;
}
public boolean isOnline() {
ConnectivityManager conMgr = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if(netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()){
Toast.makeText(getApplicationContext(), "No Internet connection!", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e("ClearFromRecentService-", "-----------------------------------Service Destroyed");
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Log.e("Clearvi--------------", "---------------------------------END");
//Code here
stopSelf();
}
}
when I did not doing something in sheduled task and printing single line then work fine like
log.e("","I'm running after 15 sec") -->> print line in log
but when I put my code then it not work,like code did not run.
Can Anyone suggest something,it will be really helpful for noob.

Wrap your run method in try-catch block.
Just a guess: An exception is being thrown. A ScheduledExecutorService halts silently if it encounters an Exception.
The run method’s code should always be surrounded by a try-catch to handle and absorb any thrown Exception.
If you try to make a Looper before try catch and make that open then it will work fine because You cannot handle an UI thread from a working thread.

Related

How to navigate to specific activity/fragment after tapping on one signal push notification?

can someone provide me the proper documentation or code to navigate to specific activity by tapping on one signal push notification, i want to open the specific fragment
here is my code where i extened application class and initialize one signal :
package com.example.nasapp;
import android.app.Application;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Parcelable;
import android.util.Log;
import com.example.nasapp.ui.home.HomeFragment;
import com.example.nasapp.ui.information.InformationFragment;
import com.onesignal.OSMutableNotification;
import com.onesignal.OSNotification;
import com.onesignal.OSNotificationAction;
import com.onesignal.OSNotificationOpenedResult;
import com.onesignal.OSNotificationReceivedEvent;
import com.onesignal.OneSignal;
import org.json.JSONException;
import org.json.JSONObject;
public class OneSignalApplication extends Application {
private static final String ONESIGNAL_APP_ID = "e855e254-9b4e-4e6f-a64a-e48db6f35d07";
#Override
public void onCreate() {
super.onCreate();
// Enable verbose OneSignal logging to debug issues if needed.
//OneSignal.setLogLevel(OneSignal.LOG_LEVEL.VERBOSE, OneSignal.LOG_LEVEL.NONE);
// OneSignal Initialization
OneSignal.initWithContext(this);
OneSignal.setAppId(ONESIGNAL_APP_ID);
// promptForPushNotifications will show the native Android notification permission prompt.
// We recommend removing the following code and instead using an In-App Message to prompt for notification permission (See step 7)
OneSignal.promptForPushNotifications();
OneSignal.setNotificationOpenedHandler(new OneSignal.OSNotificationOpenedHandler() {
#Override
public void notificationOpened(OSNotificationOpenedResult result) {
JSONObject data = result.getNotification().getAdditionalData();
Log.i("OneSignalExample", "Notification Data: " + data);
String notification_topic;
if (data != null) {
try {
System.out.println(data.getString("job_id"));
} catch (JSONException e) {
e.printStackTrace();
}
notification_topic = data.optString("notification_topic", "hii");
if (notification_topic != null) {
OneSignal.addTrigger("level", notification_topic);
}
}
}
});
}
}
here is my NotificationServiceExtensionClass:
public class NotificationServiceExtension extends Service implements OneSignal.OSRemoteNotificationReceivedHandler {
#Override
public void remoteNotificationReceived(Context context, OSNotificationReceivedEvent notificationReceivedEvent) {
OSNotification notification = notificationReceivedEvent.getNotification();
// Example of modifying the notification's accent color
OSMutableNotification mutableNotification = notification.mutableCopy();
mutableNotification.setExtender(builder -> {
//... do stuff
builder.setTimeoutAfter(30000);
Intent intent = new Intent();
JSONObject data = notification.getAdditionalData();
// check the data and create intent
intent = new Intent(context, InformationFragment.class);
// or any other depends on data value
intent.putExtra("data", (Parcelable) data);
PendingIntent pendIntent = PendingIntent.getActivity(context,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
builder = builder.setContentIntent(pendIntent);
return builder;
});
JSONObject data = notification.getAdditionalData();
Log.i("OneSignalExample", "Received Notification Data: " + data);
// If complete isn't call within a time period of 25 seconds, OneSignal internal logic will show the original notification
// To omit displaying a notification, pass `null` to complete()
notificationReceivedEvent.complete(mutableNotification);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
In manifest i declare this service class:
<service
android:name=".service.NotificationServiceExtension"
android:permission="android.permission.BIND_JOB_SERVICE"
android:exported="false">
am i missing some code or what am i doing wrong in code ,can please someone help?

Wi-fi Scan Broadcast Receiver not Working

I am currently working on a simple Wi-fi scanner android application
with min API level 26 and target API level 28.
I want real time update in scan results so i have created a broadcast receiver but it is not working as intended.
Note: I have already tried
Wifi scan results broadcast receiver not working, Broadcast receiver with wifi scan not working
PLEASE NOTE THAT I WANT EXPLICIT BROADCAST RECEIVER NOT VIA MANIFEST FILE
I will be grateful to you.
Below is my java code:
package com.example.quickshare;
import androidx.appcompat.app.AppCompatActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class ActivitySend extends AppCompatActivity {
WifiManager wifiManager;
ListView ScanList;
List<ScanResult> results;
ListAdapter listAdapter;
WifiReceiver wifiReceiver;
IntentFilter intentFilter;
TextView msg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send);
wifiManager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
CheckWifiStatus();
msg = findViewById(R.id.wifiStatus);
intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
intentFilter.addAction(WifiManager.EXTRA_RESULTS_UPDATED);
try {
getApplicationContext().registerReceiver(wifiReceiver, intentFilter);
}
catch(Exception e){
System.out.println(e);
}
boolean success = wifiManager.startScan();
if(success)
Toast.makeText(ActivitySend.this, "Scanning", Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
super.onResume();
CheckWifiStatus();
registerReceiver(wifiReceiver, intentFilter);
wifiManager.startScan();
results = wifiManager.getScanResults();
if (results.size() > 0)
Toast.makeText(ActivitySend.this, "Scan Successful", Toast.LENGTH_LONG).show();
else
Toast.makeText(ActivitySend.this, "No Device Available", Toast.LENGTH_LONG).show();
ScanList = findViewById(R.id.ScanList);
listAdapter = new ListAdapter(getApplicationContext(), results);
ScanList.setAdapter(listAdapter);
ScanList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(ActivitySend.this, "Selected" + results.get(position).SSID, Toast.LENGTH_LONG).show();
//TODO: Establish Connection with selected SSID
}
});
}
class WifiReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(ActivitySend.this,"Available Device list changed",Toast.LENGTH_LONG).show();
//TODO: Append SSID of new Available APs in ListView and arrange a callback to onResume().
}
}
public void CheckWifiStatus(){
if (!wifiManager.isWifiEnabled()){
wifiManager.setWifiEnabled(true);
Toast.makeText(ActivitySend.this, "Wifi turned 'On' Successfully", Toast.LENGTH_SHORT).show();
msg.setText("Wifi Status : ON");
}
}
#Override
protected void onPause() {
unregisterReceiver(wifiReceiver);
super.onPause();
}
}
Using Above java code i can scan available APs if they are available before launching the activity.
After Launching this activity nothing changes in scan result and it keep showing previously fetched results even if i turn off that AP.
In order to detect your AP being disconnected, your intentFilter is lacking the ConnectivityManager.CONNECTIVITY_ACTION.
You can listen
to these action with the following line:
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
Also, you need to add brackets to your else code blocks, i.e.
if {
// ...
} else {
Toast.makeText(ActivitySend.this, "No Device Available", Toast.LENGTH_LONG).show();
ScanList = findViewById(R.id.ScanList);
// ...
}

How to get available wifi list from backend android service?

I am developing an android app which needs to check available wifi list periodically even when the app is killed from background. So I am thinking about using a service to check it from back end. In this case I am facing some problem to get the available wifi list from service. I search over internet and found most of the solution for activity only. Though I tried them but not working.
Please note that. THIS SAME CODE WORKS WHEN I USE THEM IN DIRECT ACTIVITY. BUT IT DOESN'T WORK IN SERVICE CLASS.
Code of my service is.....
package com.example.sodrulaminshaon.ringmodecontroller;
import android.Manifest;
import android.app.AlarmManager;
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.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import java.util.List;
import java.util.Set;
/**
* Created by Sodrul Amin Shaon on 22-Jun-18.
*/
public class MyService extends Service {
WifiManager wifiManager;
WifiReceiver receiverWifi;
private static final String LIST_TESTING = "ListTest";
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
SharedPreferences preferences = getSharedPreferences(Constants.PREFERENCE_NAME,MODE_PRIVATE);
boolean auto = preferences.getBoolean(Constants.AUTO_CONTROL_STR,false);
//if(MainActivity.getAutoControl())
if(auto)
{
wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
if (!wifiManager.isWifiEnabled())
{
wifiManager.setWifiEnabled(true);
}
Log.i(LIST_TESTING,"Wifi is enabled. Now going to check the available list.");
receiverWifi = new WifiReceiver();
registerReceiver(receiverWifi,
new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
wifiManager.startScan();
}
stopSelf();
return START_STICKY;
}
class WifiReceiver extends BroadcastReceiver {
// This method call when number of wifi connections changed
public void onReceive(Context c, Intent intent) {
StringBuilder sb = new StringBuilder();
List<ScanResult> wifiList = wifiManager.getScanResults();
Log.i(LIST_TESTING,"Inside scan result receiver. Scan result size: "+wifiList.size());
sb.append("\n Number Of Wifi connections :"+wifiList.size()+"\n\n");
for(int i = 0; i < wifiList.size(); i++){
sb.append(new Integer(i+1).toString() + ". ");
sb.append(wifiList.get(i).SSID).toString();
sb.append("\n\n");
}
Log.i(LIST_TESTING,sb.toString());
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
// I want to restart this service again in one hour
SharedPreferences preferences = getSharedPreferences(Constants.PREFERENCE_NAME,MODE_PRIVATE);
boolean auto = preferences.getBoolean(Constants.AUTO_CONTROL_STR,false);
if(auto)
{
if(wifiManager.isWifiEnabled())unregisterReceiver(receiverWifi);
AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
alarm.set(
alarm.RTC_WAKEUP,
System.currentTimeMillis() + (1000 * 10),
PendingIntent.getService(this, 0, new Intent(this, MyService.class), 0)
);
}
}
}
No need to worry about permission. I have taken necessary permissions at the start of the app. Still I am sharing the permission taken part.
private void getPermission(){
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
&&
ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
askForLocationPermissions();
}
}
private void askForLocationPermissions() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
new android.support.v7.app.AlertDialog.Builder(this)
.setTitle("Location permessions needed")
.setMessage("you need to allow this permission!")
.setPositiveButton("Sure", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
LOCATION_PERMISSION_REQUEST_CODE);
}
})
.setNegativeButton("Not now", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.show();
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
LOCATION_PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
switch (requestCode) {
case LOCATION_PERMISSION_REQUEST_CODE:
if (isPermissionGranted(permissions, grantResults, Manifest.permission.ACCESS_FINE_LOCATION)) {
} else {
Toast.makeText(this, "Can not proceed! i need permission" , Toast.LENGTH_SHORT).show();
}
break;
}
}
public static boolean isPermissionGranted(#NonNull String[] grantPermissions, #NonNull int[] grantResults,
#NonNull String permission) {
for (int i = 0; i < grantPermissions.length; i++) {
if (permission.equals(grantPermissions[i])) {
return grantResults[i] == PackageManager.PERMISSION_GRANTED;
}
}
return false;
}
I can assure that my service is running well. It tries to check available wifi list each 10 seconds interval.
What I want to know is that. This code can not print the available wifi list. Just for the information in MyService class
Log.i(LIST_TESTING,"Wifi is enabled. Now going to check the available list.");
this line is printing continuously. But the other two lines
Log.i(LIST_TESTING,"Inside scan result receiver. Scan result size: "+wifiList.size());
Log.i(LIST_TESTING,sb.toString());
are not being executed. Can anyone please help me....
As nobody is answering. I tried further and found the problem of my code. In my code I called
stopSelf();
inside
public int onStartCommand(Intent intent, int flags, int startId) method. Which was causing my service to stop just after it was started. Which means my registered broadCastReceiver was also being discarded. As a result wifi list was not being printed. I was dumb to write this code and finding the error.
You should create a broadcast receivers to get the list of available wifi networks.
private final BroadcastReceiver mWifiScanReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context c, Intent intent) {
if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
List<ScanResult> mScanResults = mWifiManager.getScanResults();
}
}
}
also add these lines in the manifest.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
and in oncreate() method register the listners
mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
registerReceiver(mWifiScanReceiver,
new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
mWifiManager.startScan();
For more details this question related to this POST.

Android how to run a task when app is in background of phone

I'm trying to create a service for the first time that runs a method from the activity every 15 seconds once a toggle button is checked when app is the background of a phone and so far the tutorials havent been helpful; this is my code so far. Forgive me if I look stupid here, its my first time using a service.
Service Code
package com.example.adrian.trucktracker;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import java.util.Timer;
import java.util.TimerTask;
public class AutoUpdateService extends Service {
Locator locator = new Locator();
Timer myTimer = new Timer();
private class MyTimerTask extends TimerTask
{
#Override
public void run() {
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
locator.TemperatureCatch();
}
}, 1000 );
}
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
MyTimerTask myTimerTask = new MyTimerTask();
myTimer.scheduleAtFixedRate(myTimerTask, 0, 15000);
}
#Override
public void onDestroy() {
super.onDestroy();
myTimer.cancel();
stopSelf();
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
My toggle button code
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
{
startService(new Intent(this,AutoUpdateService.class));
}
else
{
stopService(new Intent(this,AutoUpdateService.class));
}
You got it right to use Service. Do not use Timer, since it is extra thread you do not need. What you can do is to use AlarmManager to schedule your service intent to be launched every 15 seconds (interval). This will trigger interval time your service by calling onStartCommand in your service where you can do whatever you need by reading (if need) intent from parameters of onStartCommand.

intentService : why my onHandleIntent is never called?

I'm working with android xml rpc to mount a server. For that I'm using and intentService. The only problem is that when the server class is launched, my onHandleIntent which contains the server is never called.
I've made some research and I found someone who had the same problem, he managed solving it by using super class but I'm new in programming and didn't manage to do what he did ==> link
Here is my code:
package tfe.rma.ciss.be;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlrpc.android.MethodCall;
import org.xmlrpc.android.XMLRPCServer;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class Server extends IntentService {
public String myData="";
public String streamTitle = "",path="";
public void onCreate() {
Log.d("Server", ">>>onCreate()");
}
public Server() {
super("Server");
}
public void onStart (Intent intent, int startId) {
Log.d("Server", ">>>Started()"); }
#Override
protected void onHandleIntent(Intent intent) {
Log.d("Server", ">>>handlingIntent()");
try {
ServerSocket socket = new ServerSocket(8214);
XMLRPCServer server = new XMLRPCServer();
Log.d("Server", ">>>opening on port" + socket);
while (true) {
Socket client = socket.accept();
MethodCall call = server.readMethodCall(client);
String name = call.getMethodName();
if (name.equals("newImage")) {
ArrayList<Object> params = call.getParams();
// assume "add" method has two Integer params, so no checks done
myData = (String)( params.get(0));
//int i1 = (Integer) params.get(1);
server.respond(client, new Object[] {200});
/*intent = new Intent (this, ParseFunction.class);
startService (intent); */
Toast.makeText(this, myData, Toast.LENGTH_SHORT).show();
Log.d("ParseFunction", ">>>Started()");
Intent i = new Intent( this, B.class );
i.putExtra( "Azo", myData);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity( i );
} else {
server.respond(client, null);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
}
If you got here and nothing worked, check your manifest looks like this:
<service android:name=".subpackage.ServiceClassName" >
</service>
And not like this:
<service android:name=".subpackage.ServiceClassName" />
There's a problem with xml closing tags. The first one works. The second is legal but doesn't work.
In case someone else wants the result here is what I should have done. Adding superclass to onCreate super.onCreate() and change onStart by onStartCommand (plus its superclass super.onStartCommand()), now it works as a charm
package tfe.rma.ciss.be;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlrpc.android.MethodCall;
import org.xmlrpc.android.XMLRPCServer;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class Server extends IntentService {
public String myData="";
public String streamTitle = "",path="";
public void onCreate() {
super.onCreate();
Log.d("Server", ">>>onCreate()");
}
public Server() {
super("Server");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, startId, startId);
Log.i("LocalService", "Received start id " + startId + ": " + intent);
return START_STICKY;
}
#Override
protected void onHandleIntent(Intent intent) {
Log.d("Server", ">>>handlingIntent()");
try {
ServerSocket socket = new ServerSocket(8214);
XMLRPCServer server = new XMLRPCServer();
Log.d("Server", ">>>opening on port" + socket);
while (true) {
Socket client = socket.accept();
MethodCall call = server.readMethodCall(client);
String name = call.getMethodName();
if (name.equals("newImage")) {
ArrayList<Object> params = call.getParams();
// assume "add" method has two Integer params, so no checks done
myData = (String)( params.get(0));
//int i1 = (Integer) params.get(1);
server.respond(client, new Object[] {200});
/*intent = new Intent (this, ParseFunction.class);
startService (intent); */
Toast.makeText(this, myData, Toast.LENGTH_SHORT).show();
Log.d("ParseFunction", ">>>Started()");
Intent i = new Intent( this, B.class );
i.putExtra( "Azo", myData);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity( i );
} else {
server.respond(client, null);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
}
Get rid of onStart(). First, it is obsolete. Second, you are not chaining to the superclass, thereby preventing IntentService from doing its work.
I had the same issue, it turned out the service definition was missing in the App manifest.
Adding:
<service
android:name=".MyIntentServiceName"
android:exported="false" />
solved the problem.
Just to sum up: In case you override onStartCommand, do not forget to call super:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
If not, check your manifest, see answer by Mister Smith.
I was having this problem but only on some devices, more specifically on a Motorola Moto G 1st Gen (4.5" & 4G-less) and the solution was to include the FULL PACKAGE NAME in the Service description in the Manifest.
So changing 'mypackage.MyService' to 'com.android.myapp.mypackage.MyService' solved the onHandleIntent never being called.
Some of you might get to this page because your onHandleIntent() method never gets called, despite you implemented everything just fine.
If it's your first service you try to test, you might not be awared of the importance of permissions. In that case check your permissions.
I hope this helps someone.
I had the same problem. I removed the OnCreate method and it works like a charm now. LMK if it worked for you :)

Categories

Resources