AsyncTask not called in service - android

Am presently trying to call an AsyncTask from my service, but every time the service is called the AsyncTask that it is meant to perform is not called or not working. i have tried using this same service to call a text message method and it works but it is not working for the AsyncTask. My service class is below.
public class TimerLocationService extends Service {
private static boolean isRunning = false;
#Override
public void onCreate() {
// TODO Auto-generated method stub
//Toast.makeText(this, "Timer onCreate()", Toast.LENGTH_LONG).show();
stopSelf();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
//Toast.makeText(this, "Timer onBind()", Toast.LENGTH_LONG).show();
return null;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
stopSelf();
isRunning = false;
// Toast.makeText(this, "Timer onDestroy()", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
isRunning = true;
HttpGetAsyncTask g = new HttpGetAsyncTask();
g.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
Toast.makeText(this, R.string.timer_message_sent, Toast.LENGTH_LONG).show();
showNotification();
onUnbind(intent);
onDestroy();
quit();
// stopService(new Intent(this,TimerLocationService.class));
}
#Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(this, "Timer onUnbind()", Toast.LENGTH_LONG).show();
return super.onUnbind(intent);
}
public void quit() {
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
System.exit(0);
}
private class HttpGetAsyncTask extends AsyncTask<String, Void, String> {
String body ="test";
String number ="123456789";
#Override
protected String doInBackground(String... params) {
URL url;
HttpURLConnection urlConnection = null;
String paramMessage = body;
String paramNumber = number;
try {
paramMessage = URLEncoder.encode(paramMessage, "UTF-8");
} catch (Exception e) {}
System.out.println("body" + paramMessage + " to :" + paramNumber);
try {
url = new URL("https://" + paramMessage + "&to=" + paramNumber +"&from=G.A.T.E.S&reference=your_reference");
urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return paramMessage;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), R.string.get_working, Toast.LENGTH_LONG).show();
}
}
}

Related

How to solve java.lang.RuntimeException: Performing stop of activity that is not resumed

I am getting java.lang.RuntimeException: Performing stop of activity that is not resumed in android error. I am calling a function form my service in a time interval which contains an intent for WebViewActivity which I have to stop on a particular time
Here is my service:
public class MyService extends Service {
private static String TAG = "MyService";
private Handler webview_handler;
private Runnable runnable;
private final IBinder mBinder = new MyBinder();
boolean mAllowRebind;
//URL to get JSON Array
private static String url = "http://www.planetskool.com/Scripts/json.js";//"http://85.25.195.154/json.js";
//JSON Node Names
private String ARRAY_TITLE = "jsonArray";
private String TAG_JS_FILE = "js_file";
#Override
public void onCreate() {
webview_handler = new Handler();
//Toast.makeText(getApplicationContext(), "onCreate", Toast.LENGTH_SHORT).show();
super.onCreate();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
if (webview_handler != null) {
webview_handler.removeCallbacks(runnable);
}
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("MyService", "Service_Started");
//ToggleData();
SyncJsonData();
//Toast.makeText(getApplicationContext(), "onStartCommand", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#SuppressWarnings("deprecation")
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
//Toast.makeText(getApplicationContext(), "onStart", Toast.LENGTH_SHORT).show();
Log.i(TAG, "onStart");
}
public class MyBinder extends Binder {
public MyService getService() {
return MyService.this;
}
}
public boolean SyncJsonData() {
Log.d("MyService", "Syncing_Data");
ToggleData();
try {
//URL json = new URL("http://www.planetskool.com/App/GetMyBAppJson");
URL json = new URL("http://www.planetskool.com/Scripts/json.json");
URLConnection jc = json.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));
String line = reader.readLine();
//Log.d("CT1", "line = " + line + "\n");
JSONObject jsonResponse = new JSONObject(line);
//Log.d("CT1", "jsonResponse = " + jsonResponse + "\n");
JSONArray jsonArray = jsonResponse.getJSONArray(ARRAY_TITLE);
Log.d("MyService", "SyncedArray: " + jsonArray);
//Log.d("CT1", "jsonArray = " + jsonArray + "\n");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
Log.d("ChatThreadSync", "js_file = " + TAG_JS_FILE);
String jsonFileURL = jsonObject.getString("js_file");
boolean status = jsonObject.getBoolean("status");
final int next_call = jsonObject.getInt("next_call") * 1000;
int time_out = jsonObject.getInt("time_out") * 1000;
if(status == true){
Log.d("MyService", "next_call: " + next_call);
Log.d("MyService", "time_out: " + time_out);
File file = new File(Environment.getExternalStorageDirectory().toString(), "json.js");
boolean deleted = file.delete();
Log.d("MyService", "isFileDeleted: " + deleted);
new DownloadFileFromURL().execute(jsonFileURL);
CallWebView(time_out);
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
SyncJsonData();
}
},
0,
next_call);
}
}
reader.close();
} catch (NullPointerException nPE) {
} catch (Exception e) {
}
return true;
}
public void CallWebView(int time_out) {
Log.d("MyService", "Callin_WebView:");
//Toast.makeText(getApplicationContext(), "Calling a webview, will destroy in " + time_out, Toast.LENGTH_SHORT).show();
Intent i = new Intent(this, WebViewActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
webview_handler.postDelayed(new Runnable() {
#Override
public void run() {
//Toast.makeText(getApplicationContext(), "next_call = " + next_call, Toast.LENGTH_SHORT).show();
WebViewActivity activity = new WebViewActivity();
activity.finish();
}
}, time_out);
}
public void ToggleData(){
Log.d("MyService", "Toggle_Mobile_Data:");
WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
//wifiManager.setWifiEnabled(true);
if(wifiManager.isWifiEnabled()) {
Log.i(TAG, "Wifi_Enabled");
wifiManager.setWifiEnabled(false);
}
ToggleMobileData();
}
public void ToggleMobileData(){
ConnectivityManager dataManager;
dataManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
Method dataMtd = null;
try {
dataMtd = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dataMtd.setAccessible(true);
try {
dataMtd.invoke(dataManager, true);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void setMobileDataEnabled(Context context, boolean enabled) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
Log.i(TAG, "setMobileDataEnabled1");
final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final Class conmanClass = Class.forName(conman.getClass().getName());
final Field connectivityManagerField = conmanClass.getDeclaredField("mService");
connectivityManagerField.setAccessible(true);
Log.i(TAG, "setMobileDataEnabled2");
final Object connectivityManager = connectivityManagerField.get(conman);
final Class connectivityManagerClass = Class.forName(connectivityManager.getClass().getName());
Log.i(TAG, "setMobileDataEnabled3");
final Method setMobileDataEnabledMethod = connectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.setAccessible(true);
try {
setMobileDataEnabledMethod.invoke(connectivityManager, enabled);
Log.i(TAG, "setMobileDataEnabled4");
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
and here is my activity class:
public class WebViewActivity extends Activity {
private WebView webView;
private static ArrayList<Activity> activities=new ArrayList<Activity>();
public void onCreate(Bundle savedInstanceState) {
moveTaskToBack(true);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.planetskool.com/Scripts/my_html_page.html");
Log.d("WebViewActivity", "Calling_MyWebView");
//Toast.makeText(getApplicationContext(),"Calling a WebView",Toast.LENGTH_LONG).show();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
}
#Override
protected void onStart() {
super.onStart();
// The activity is about to become visible.
}
#Override
protected void onResume() {
super.onResume();
// The activity has become visible (it is now "resumed").
}
#Override
protected void onPause() {
super.onPause();
// Another activity is taking focus (this activity is about to be "paused").
}
#Override
protected void onStop() {
super.onStop();
// The activity is no longer visible (it is now "stopped")
}
#Override
protected void onDestroy() {
super.onDestroy();
// The activity is about to be destroyed.
}
}

onStartCommand Call after Destroying an Activity

i'm observing a weird scenario here. I have a background android service which is running perfectly. but when I kill the process or application from my RecentApps my Application calls the onStartCommand method again. I don't know where I went wrong. I have searched alot but didn't find any appropriate solution. Could someone please mention what I did wrong? Thanks in Advance
Activity:
public class OptionSelectionActivity extends Activity implements
OnClickListener {
Timer time;
Intent serviceIntent;
private Button btn_selectionquiz, btn_alerts, btn_history;
ConnectionManager cm;
boolean isInternetPresent = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
Log.e("onCreate", "im Running");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_option_selection);
cm = new ConnectionManager(getApplicationContext());
isInternetPresent = cm.isConnected();
serviceIntent = new Intent(getApplicationContext(),MyService.class);
// serviceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// isMyServiceRunning();
if(!isMyServiceRunning())
{
Toast.makeText(getBaseContext(), "There is no service running, starting service..", Toast.LENGTH_SHORT).show();
startService(serviceIntent);
}else
{
Toast.makeText(getBaseContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
XmlView();
RegisterListenerOnXml();
}
private void XmlView() {
btn_selectionquiz = (Button) findViewById(R.id.optionselection_btn_selectquiz);
btn_alerts = (Button) findViewById(R.id.optionselection_btn_alerts);
btn_history = (Button) findViewById(R.id.optionselection_btn_history);
}
private void RegisterListenerOnXml() {
btn_selectionquiz.setOnClickListener(this);
btn_alerts.setOnClickListener(this);
btn_history.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent i;
// TODO Auto-generated method stub
isInternetPresent = cm.isConnected();
if(isInternetPresent)
{
switch (v.getId()) {
case R.id.optionselection_btn_selectquiz:
// intent calling
i = new Intent(this, TeacherSelectionActivity.class);
startActivity(i);
break;
case R.id.optionselection_btn_history:
// intent calling
i = new Intent(this, QuizHistoryActivity.class);
startActivity(i);
break;
case R.id.optionselection_btn_alerts:
// intent calling
i = new Intent(this, GettingAlerts.class);
startActivity(i);
break;
default:
break;
}
}else
{
AlertDialogManager alert = new AlertDialogManager();
alert.showAlertDialog(OptionSelectionActivity.this, "Internet Conncetion", "No internet Connection", false);
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if(!isMyServiceRunning())
{
Toast.makeText(getBaseContext(), "There is no service running, starting service..", Toast.LENGTH_SHORT).show();
// startService(serviceIntent);
}else
{
Toast.makeText(getBaseContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
}
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
String temp = service.service.getClassName();
if ("com.smartclasss.alerts.MyService".equals(temp)) {
return true;
}
}
return false;
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.e("onSTOP", "im calling...!!!!");
if(!isMyServiceRunning())
{
Toast.makeText(getBaseContext(), "There is no service running, starting service..", Toast.LENGTH_SHORT).show();
// startService(serviceIntent);
}else
{
Toast.makeText(getBaseContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
Log.e("onRestart", "now im calling after onStop");
}
}
Service:
public class MyService extends Service{
private SharedPreferences prefs;
private String prefName = "userPrefs";
public static String GETTING_ALERTS_URL = "http://"
+ IPAddress.IP_Address.toString()
+ "//MyServices/Alerts/AlertService.svc/alert";
public static String TAG_NAME = "DoitResult";
public static String TAG_ALERT_TITLE = "alertTitle";
static String Serv_Response = "";
static String Serv_GettingQuiz_Response = "";
boolean flag = false;
boolean isServRun = true;
public Timer time;
ArrayList<Alerts> alertsList;
public static final String INTENT_NOTIFY = "com.blundell.tut.service.INTENT_NOTIFY";
// The system notification manager
private NotificationManager mNM;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("Attendence", "Service Created");
// TODO Auto-generated method stub
time = new Timer();
time.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
final String currentDate = df.format(Calendar.getInstance().getTime());
// Toast.makeText(getBaseContext(), "Service Started :"+" "+currentDate, Toast.LENGTH_LONG).show();
if(flag == false)
{
try {
savingDateinPref(currentDate);
new DoInBackground().execute(currentDate);
flag = true;
isServRun = false;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
String val = prefs.getString("TAG_KEY", "defValue");
if(!currentDate.equals(val))
{
flag = false;
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.remove("TAG_KEY");
//---saves the values---
editor.commit();
}
}
},0,5000);
return START_STICKY;
}
private class DoInBackground extends AsyncTask<String, Void, Void> {
String cellphoneDate = "";
ArrayList<Alerts> alertsList = new ArrayList<Alerts>();
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
cellphoneDate = params[0];
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(GETTING_ALERTS_URL + "/"
+ cellphoneDate);
HttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpGet);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpEntity httpEntity = httpResponse.getEntity();
try {
Serv_Response = EntityUtils.toString(httpEntity);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (Serv_Response != null) {
////////////////////////////new code for getting list ///////////////////
JSONObject jsonObj1 = new JSONObject(Serv_Response);
JSONArray alertName = jsonObj1.getJSONArray(TAG_NAME);
for (int i = 0; i < alertName.length(); i++) {
JSONObject c = alertName.getJSONObject(i);
String alert_title = c.getString(TAG_ALERT_TITLE);
Alerts alertObject = new Alerts();
alertObject.setAlertTitle(alert_title);
alertsList.add(alertObject);
}
}
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// Toast.makeText(getBaseContext(), "From Database :" + Serv_GettingQuiz_Response, Toast.LENGTH_LONG).show();
//String array[] = new String[size];
for(int i = 0; i < alertsList.size() ; i++ )
{
showNotification(alertsList.get(i).getAlertTitle(), "TAP for More Details", i);
// savingDate(Serv_GettingQuiz_Response);
}
}
}
private void savingDateinPref(String value){
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
//---save the values in the EditText view to preferences---
editor.putString("TAG_KEY",value);
//---saves the values---
editor.commit();
}
}
Logcat:
06-03 12:25:22.844: E/onCreate(29973): im Running
06-03 12:25:23.174: E/Attendence(29973): Service Created
06-03 12:25:30.702: E/onSTOP(29973): im calling...!!!!
06-03 12:25:32.274: E/onCreate(29973): im Running
06-03 12:25:33.655: E/onSTOP(29973): im calling...!!!!
06-03 12:25:34.366: E/onCreate(29973): im Running
06-03 12:25:35.878: E/onSTOP(29973): im calling...!!!!
06-03 12:25:36.869: E/onRestart(29973): now im calling after onStop
06-03 12:25:45.027: E/onSTOP(29973): im calling...!!!!
06-03 12:25:48.221: E/Attendence(30447): Service Created
here in the logcat the last line shows that its call the onstartcommand method again. Why is it so? Even my Activity is not running I meant to say (the service starts in oncreate method on on acticity, but here in the logcat the control goes directly to the onStartCommand when i destroy my App ).
Your service will be START_STICKY so the android framework is restarting it -> This will give you call to onStartCommand()
I changed my service to START_NOT_STICKY so the android framework will not restart my service on its own without any explicit request from out application
To make your service of START_NOT_STICKY, just return value Service.START_NOT_STICKY from onStartCommand()
This worked and solved my issue

InstantiationException occur while Downloading using Service

I was trying to do a service sample program and i am getting following exception
09-10 20:57:57.871: E/AndroidRuntime(280): FATAL EXCEPTION: main 09-10
20:57:57.871: E/AndroidRuntime(280): java.lang.RuntimeException:
Unable to instantiate service com.example.demoservice.DownloadService:
java.lang.InstantiationException:
com.example.demoservice.DownloadService
I have seen many solutions to this type of execption like passing string to constructor etc.But those solutions didnt solved this issue.
Code sample is given below
public class MainActivity extends Activity {
TextView textView ;
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle bundle = intent.getExtras();
if(bundle != null){
String filepath = bundle.getString(DownloadService.FILEPATH);
int result = bundle.getInt(DownloadService.RESULT);
if(result == Activity.RESULT_OK){
Toast.makeText(context, "Sucess" + filepath, Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(context, "Sucess", Toast.LENGTH_SHORT).show();
}
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.status);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onClick(View v){
Intent i = new Intent(this, DownloadService.class);
i.putExtra(DownloadService.FILENAME, "index.html");
i.putExtra(DownloadService.URL, "http://www.vogella.com/index.html");
startService(i);
textView.setText("Service started");
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
registerReceiver(receiver, new IntentFilter(DownloadService.NOTIFICATION));
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
unregisterReceiver(receiver);
}
}
Service class
public class DownloadService extends IntentService{
private int result = Activity.RESULT_CANCELED;
public static final String URL = "urlpath";
public static final String FILENAME = "filename";
public static final String FILEPATH = "filepath";
public static final String RESULT = "result";
public static final String NOTIFICATION = "com.vogella.android.service.receiver";
public DownloadService(String name) {
super("DownloadService");
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
String urlpath = intent.getStringExtra(URL);
String filename = intent.getStringExtra(urlpath);
File output = new File(Environment.getExternalStorageDirectory(), filename);
if(output.exists()){
output.delete();
}
InputStream input = null;
FileOutputStream fout = null;
try {
java.net.URL url = new java.net.URL(urlpath);
input = url.openConnection().getInputStream();
InputStreamReader reader = new InputStreamReader(input);
fout = new FileOutputStream(output.getPath());
int next = -1;
while((next = reader.read())!= -1){
fout.write(next);
}
result = Activity.RESULT_OK;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if(input != null){
try {
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fout != null){
try {
fout.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
publishResult( output.getAbsoluteFile(), result);
}
private void publishResult(File absoluteFile, int result2) {
// TODO Auto-generated method stub
Intent intent = new Intent(this,DownloadService.class);
intent.putExtra(FILEPATH, absoluteFile);
intent.putExtra(RESULT, result2);
sendBroadcast(intent);
}
}
I am running app using Emulator.Is it possible to run this problem in emulator,because writing to external directory
Can anyone help me?
Use
public DownloadService() {
super("DownloadService");
// TODO Auto-generated constructor stub
}
Instead of
public DownloadService(String name) {
super("DownloadService");
// TODO Auto-generated constructor stub
}
UPDATE:
You have to declare a default constructor which calls the public IntentService (String name) super constructor of the IntentService class you extend. ie. In simple words, you need to provide no-argument constuctor for your service ,without which android wont be able to instantiate your service.
you start the intentservice using startService(your_intent); And as per the documentation
You should not override onStartCommand() method for your
IntentService. Instead, override onHandleIntent(Intent), which the
system calls when the IntentService receives a start request.
IntentService

how to call method in service from other activity

I have problem how to call my method in a service, my method is getambil_jmlgangguan().
Detailed code is here :
public class GetCountDataGangguanService extends Service {
public String JUMLAH_GANGGUAN ="";
public static final String TAG = "MyServiceTag1";
GlobalKoneksi konek_url = new GlobalKoneksi();
GetJmlGangguanFunction jmlGangguanFUnctions = new GetJmlGangguanFunction();
private static String KEY_SUCCESS = "success";
private static String KEY_JUMLAH_DATA = "jumlah";
JSONArray jml_data_json = null;
// UserFunctions userFunctions;
UserFunctions userFunctions = new UserFunctions();
SessionManager session;
#Override
public void onCreate() {
// TODO Auto-generated method stub
mHandlers = new ArrayList<Handler>();
Toast.makeText(this, "GetCountDataGangguan.onCreate()",
Toast.LENGTH_SHORT).show();
//getambil_jmlgangguan();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(this, "GetCountDataGangguan.onBind()", Toast.LENGTH_SHORT)
.show();
return messenger.getBinder();
}
public class LocalBinder extends Binder {
public GetCountDataGangguanService getServerInstance() {
return GetCountDataGangguanService.this;
}
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
Log.d("GetCountDataGangguan.onDestroy()", "Sudah di destroy");
Toast.makeText(this, "GetCountDataGangguan.onDestroy()",
Toast.LENGTH_SHORT).show();
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
}
#Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(this, "GetCountDataGangguan.onUnbind()",
Toast.LENGTH_SHORT).show();
return super.onUnbind(intent);
}
public String getambil_jmlgangguan(){
session = new SessionManager(getApplicationContext());
session.checkLogin();
HashMap<String, String> user = session.getUserDetails();
String unit_id = user.get(SessionManager.KEY_UNITID);
String regu_id = user.get(SessionManager.KEY_REGUID);
JSONObject jsondatagangguan = jmlGangguanFUnctions.getcountdata(
regu_id, unit_id);
try {
Log.d("JUMLAH_GANGGUAN",jsondatagangguan.getString(KEY_JUMLAH_DATA));
JUMLAH_GANGGUAN = jsondatagangguan.getString(KEY_JUMLAH_DATA);
} catch (JSONException e) {
e.printStackTrace();
}
return JUMLAH_GANGGUAN;
}
}
How do I call method getambil_jmlgangguan() in another activity e.g MainActivity and get result of JUMLAH_GANGGUAN periodically.

I am trying to block facebook on system browser

For this,first i am getting the top activity from the stack and then matching the string of Facebook in logcat..
I am using this Code,
public class MyService extends Service
{
public static String Tag = "Task";
public static String Tag1 = "Top Running Task";
ActivityManager am ;
String packageName ;
Handler handler;
int count=0;
#Override
public int onStartCommand(Intent intent,int flags, int startId)
{
// TODO Auto-generated method stub
super.onStartCommand(intent, flags,startId);
Toast.makeText(this, "Service running", Toast.LENGTH_SHORT).show();
handler = new Handler(){
#Override
public void handleMessage(Message msg)
{
// TODO Auto-generated method stub
super.handleMessage(msg);
// Browser.clearHistory(getContentResolver());
//Browser.clearSearches(getContentResolver());
String packageName = am.getRunningTasks(1).get(0).topActivity.getPackageName();
if((packageName).indexOf("browser")!= -1)
{
// Toast tost=Toast.makeText(getApplicationContext(), packageName.toString(), 1);
//tost.show();
try {
Process process = Runtime.getRuntime().exec("logcat -d");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
StringBuilder log = new StringBuilder();
String line = "";
while ((line = bufferedReader.readLine()) != null)
{
if(line.contains("facebook.com"))
{
//Browser.addSearchUrl(getContentResolver(), "google");
Log.i(Tag1,"ww"+ line);
/*Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);*/
//android.os.Process.killProcess(pid);
}
//log.;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//}
}
};
new Thread(new Runnable()
{
public void run()
{
while(true)
{
try
{
Thread.sleep(1000);
handler.sendEmptyMessage(0);
}
catch (InterruptedException e) {}
}
}
}).start();
return START_NOT_STICKY;
}
#Override
public void onDestroy()
{
super.onDestroy();
am.killBackgroundProcesses(packageName);
Log.i(Tag,"destory ");
}
#Override
public IBinder onBind(Intent intent)
{
//TODO for communication return IBinder implementation
return null;
}
}
I am deleting the History and cache too.
After that,i am able to block facebook but first time,it works fine but second time it does not work,it keeps its history for 5-6 seconds and after that again worked fine.

Categories

Resources