Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android IntentService not starting

I know this question has been asked many times, but all the other threads didn't solve my issue at all, I can't see anything wrong with my code. Maybe I missed something here, can anyone help me out?

Code for the Intent Service:

package Services;

import android.app.IntentService;
import android.content.Intent;
import android.widget.Toast;

public class WifiSearchService extends IntentService {

  /** 
   * A constructor is required, and must call the super IntentService(String)
   * constructor with a name for the worker thread.
   */
  public WifiSearchService() {
      super("WifiSearchService");
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
      Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
      return super.onStartCommand(intent,flags,startId);
  }

  /**
   * The IntentService calls this method from the default worker thread with
   * the intent that started the service. When this method returns, IntentService
   * stops the service, as appropriate.
   */
  @Override
  protected void onHandleIntent(Intent intent) {
      // Normally we would do some work here, like download a file.
  // For our sample, we just sleep for 5 seconds.
      long endTime = System.currentTimeMillis() + 5*1000;
      while (System.currentTimeMillis() < endTime) {
          synchronized (this) {
              try {
                  wait(endTime - System.currentTimeMillis());
              } catch (Exception e) {
              }
          }
      }
  }

}

Starting the service by flicking a switch:

package com.cdobiz.wifimapper;

import Services.WifiSearchService;
import android.os.Bundle;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Switch;

public class MainActivity extends Activity {

    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        context = this;

        setContentView(R.layout.activity_main);


        Switch serviceSwitch = (Switch) this.findViewById(R.id.switchService);

        serviceSwitch.setChecked(isMyServiceRunning());

        serviceSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener(){

            @Override
            public void onCheckedChanged(CompoundButton view, boolean state) {

                if(state){
                    startService(new Intent(context, WifiSearchService.class));
                }else{
                    stopService(new Intent(context, WifiSearchService.class));
                }
            }

        });

    }

    private boolean isMyServiceRunning() {
        ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            Log.v("debug", service.service.getClassName());
            if ("com.cdobiz.wifimapper.services.WifiSearchService".equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.cdobiz.wifimapper"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.cdobiz.wifimapper.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:enabled="true" android:name=".services.WifiSearchService"></service>
    </application>

</manifest>
like image 914
thedjaney Avatar asked Feb 02 '13 04:02

thedjaney


People also ask

How do I start IntentService?

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. In the above code, we have taken text view, when user gets the data from intent service it will update.

Why is IntentService deprecated?

Provided since Android API 3, the purpose of IntentService was to allow asynchronous tasks to be performed without blocking the main thread. The deprecation is one of a number of steps introduced starting with Android 8.0 (API 26) to limit the actions that can be performed while an app is in the background.

Does IntentService run on background thread?

The IntentService class provides a straightforward structure for running an operation on a single background thread. This allows it to handle long-running operations without affecting your user interface's responsiveness.

How do I trigger a service in Android?

You can start a service from an activity or other application component by passing an Intent to startService() or startForegroundService() . The Android system calls the service's onStartCommand() method and passes it the Intent , which specifies which service to start.


2 Answers

I solved the problem by making sure that the service is registered in the App-Manifest.

like image 197
Philipp Hofmann Avatar answered Oct 16 '22 21:10

Philipp Hofmann


I was able to run your service by changing the package name to com.cdobiz.wifimapper.services and change the package name of the service in the manifest.

like image 20
Samoka Avatar answered Oct 16 '22 21:10

Samoka