Creating an android service

2019-08-20 17:03发布

I'm trying to create a service which will start by the user request in the application. After the user will choose an update interval, the service will run in the operation system background, and will send a non-relevant message. I've tried to write the service according to the example for Service class API. For some reason, I figured in debug (when running doBindService() method) that mUpdateBoundService is getting null. My second question is whether I can use "Toast" inform message outside an application ? (As kind of a desktop notification). Can anyone help ? Here is my short code:

UpdateService.java

package android.update;

import java.util.Timer;

import java.util.TimerTask;

import android.app.Notification;

import android.app.NotificationManager;

import android.app.PendingIntent;

import android.app.Service;

import android.content.Intent;

import android.os.Binder;

import android.os.IBinder;

import android.widget.Toast;

public class UpdateService extends Service {
    private NotificationManager mNM;

    private final IBinder mBinder = new UpdateBinder();
    private int updateInterval;    

    public class UpdateBinder extends Binder {
        UpdateService getService() {
            return UpdateService.this;
        }
    }

    public void onCreate() {
        mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        Timer timer = new Timer();
        timer.schedule(new UpdateTimeTask(), 100, updateInterval);
    }

    public int onStartCommand(Intent intent, int flags, int startId) {        
        return START_STICKY;
    }

    class UpdateTimeTask extends TimerTask {
           public void run() {
               showNotification();
           }
        }

    public void showNotification() {        
        Toast.makeText(this, "Hi", 10);
    }

    @Override
    public IBinder onBind(Intent intent) {
        updateInterval = intent.getExtras().getInt(getString(R.string.keyUpdateInterval));
        return mBinder;
    }
}

UpdateActivity.java

package android.update;

import android.app.Activity;

import android.content.ComponentName;

import android.content.Context;

import android.content.Intent;

import android.content.ServiceConnection;

import android.os.Bundle;

import android.os.IBinder;

import android.view.View;

import android.widget.EditText;

import android.widget.Toast;

public class UpdateActivity extends Activity {

    private UpdateService mUpdateBoundService;
    private boolean mIsBound = false;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    public void onClickStartUpdateService(View view) {
        switch (view.getId()) {
        case R.id.btnStartUpdateService:
            doBindService();
            //Toast.makeText(this,"Service Started",Toast.LENGTH_LONG).show();
            mUpdateBoundService.showNotification();
            break;
        }
    }    

    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            mUpdateBoundService = ((UpdateService.UpdateBinder)service).getService();
        }

        public void onServiceDisconnected(ComponentName className) {
            mUpdateBoundService = null;
        }
    };

    private void doBindService() {
        Intent updateActivityIntent = new Intent(UpdateActivity.this, 
                UpdateService.class);       
        EditText txtUpdateInterval = (EditText) findViewById(R.id.txtUpdateInterval);
        int interval = Integer.parseInt(txtUpdateInterval.getText().toString());
        updateActivityIntent.putExtra(getString(R.string.keyUpdateInterval), interval);
        bindService(updateActivityIntent, mConnection, Context.BIND_AUTO_CREATE);
        mIsBound = true;
    }

    void doUnbindService() {
        if (mIsBound) {             
            unbindService(mConnection);
            mIsBound = false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        doUnbindService();
    }
}

标签: android
1条回答
beautiful°
2楼-- · 2019-08-20 17:13

Your toast is not showing because you are not telling it to. Try:

public void showNotification() {        
    Toast.makeText(this, "Hi", 10).show();
}

For your service issue, I think that you do not properly understand how services & activities work together. A service can run independently of a service, or you can have a service whose lifecycle matches that of a given activity. From your code, it is not clear which of these models you are following. Your implementation will cause the service to wake periodically, but only while your activity is running. If the user switches to another activity, your service will no longer be woken.

If you want a service to wake periodically independently of the activity, then you need to run your timer event in the service itself. Better still use an Alarm to wake your service: Register an Alarm with AlarmManager which will fire an Intent at a future point (or regular intervals, if you prefer), and extend your service from IntentService, override onHandleIntent() and add the necessary Intent Filter to your Service entry in the manifest.

查看更多
登录 后发表回答