Numair
Numair

Reputation: 1062

Android services, possible or not?

I'm working on an app in which I want to run some services when default Android options are accessed, i.e. when Play Music or Gallery is accessed generate a Toast and so on... Is it possible to do this?? Here is my code.

Here is where I start my service in the Main Activity:

if(autoBrightOn){
  startService(new Intent(this, MyService.class));
}

and my Service.class

public class MyService extends Service {
    private static final String TAG = "MyService";

    @Override
    public IBinder onBind(Intent intent) {
        Log.w(" ibinder ","");
        return null;
    }

    @Override
    public void onCreate() {
//        Toast.makeText(this, "My Service Created",0).show();
        Log.w(TAG, "onCreate");

            }

   @Override
    public void onDestroy() {
//        Toast.makeText(this, "My Service Stopped",0).show();
//        Log.w(TAG, "onDestroy");
//        player.stop();
    }

    @Override
    public void onStart(Intent intent, int startid) {
        Toast.makeText(this, "My Service Started :"+intent+" start id :"+startid,0).show();
//        Log.d(TAG, "onStart");
//        player.start();

        Intent intentBrowseFiles = new Intent(Intent.ACTION_VIEW);
      intentBrowseFiles.setType("image/*");
      intentBrowseFiles.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      startActivity(intentBrowseFiles);                   

    }

Upvotes: 1

Views: 88

Answers (2)

Andy Harris
Andy Harris

Reputation: 938

Yes. Make a class that extends Service and override the onCreate(), onDestroy(), and onBind() methods. In your main manifest, put

<service android:name=".GameServerService"/>

, but replace .GameServerService with the name of your service. Then in your main class, put:

Intent gameServerService = new Intent(this, GameServerService.class);

Use

this.startService(gameServerService);

and

this.stopService(gameServerService);

as needed. Good luck!

Upvotes: 2

starscream_disco_party
starscream_disco_party

Reputation: 2996

You could create a custom BroadcastReceiver and listen for different Intents sent out. There doesn't appear to be a 'catch-all' ACTIVITY_STARTED so you may need to create a pretty detailed list of Intents to listen for. Here's the Android Intent Reference:

http://developer.android.com/reference/android/content/Intent.html

Upvotes: 3

Related Questions