创建服务机器人 [英] Creating an android service

查看:187
本文介绍了创建服务机器人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建将通过应用程序的用户请求启动服务。
用户会选择更新间隔后,该服务将在操作系统后台运行,并会发送一个不相关的消息。
我试图根据对服务类的API的例子写的服务。
出于某种原因,我在调试想通(运行doBindService()方法时),该mUpdateBoundService越来越空。
我的第二个问题是,我是否可以使用面包的应用程序之外的通知消息? (作为一种桌面通知)。
任何人都可以帮忙吗?这里是我的短code:

UpdateService.java

 包android.update;进口java.util.Timer中;进口java.util.TimerTask中;进口android.app.Notification;进口android.app.NotificationManager;进口android.app.PendingIntent;进口android.app.Service;进口android.content.Intent;进口android.os.Binder;进口android.os.IBinder;进口android.widget.Toast;公共类UpdateService延伸服务{
    私人NotificationManager MNM;    私人最终的IBinder mBinder =新UpdateBinder();
    私人诠释updateInterval;    公共类UpdateBinder扩展粘结剂{
        UpdateService的getService(){
            返回UpdateService.this;
        }
    }    公共无效的onCreate(){
        MNM =(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        定时器定时器=新的Timer();
        timer.schedule(新UpdateTimeTask(),100,updateInterval);
    }    公众诠释onStartCommand(意向意图,诠释标志诠释startId){
        返回START_STICKY;
    }    类UpdateTimeTask扩展的TimerTask {
           公共无效的run(){
               showNotification();
           }
        }    公共无效showNotification(){
        Toast.makeText(这一点,你好,10);
    }    @覆盖
    公众的IBinder onBind(意向意图){
        updateInterval = intent.getExtras()调用getInt(的getString(R.string.keyUpdateInterval));
        返回mBinder;
    }
}

UpdateActivity.java

 包android.update;进口android.app.Activity;进口android.content.ComponentName;进口android.content.Context;进口android.content.Intent;进口android.content.ServiceConnection;进口android.os.Bundle;进口android.os.IBinder;进口android.view.View;进口android.widget.EditText;进口android.widget.Toast;公共类UpdateActivity延伸活动{    私人UpdateService mUpdateBoundService;
    私人布尔mIsBound = FALSE;    / **当第一次创建活动调用。 * /
    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.main);
    }    公共无效onClickStartUpdateService(查看视图){
        开关(view.getId()){
        案例R.id.btnStartUpdateService:
            doBindService();
            //Toast.makeText(this,\"Service开始,Toast.LENGTH_LONG).show();
            mUpdateBoundService.showNotification();
            打破;
        }
    }    私人ServiceConnection mConnection =新ServiceConnection(){
        公共无效onServiceConnected(组件名的className,服务的IBinder){
            mUpdateBoundService =((UpdateService.UpdateBinder)服务).getService();
        }        公共无效onServiceDisconnected(组件名的className){
            mUpdateBoundService = NULL;
        }
    };    私人无效doBindService(){
        意图updateActivityIntent =新意图(UpdateActivity.this,
                UpdateService.class);
        的EditText txtUpdateInterval =(EditText上)findViewById(R.id.txtUpdateInterval);
        INT间隔=的Integer.parseInt(txtUpdateInterval.getText()的toString());
        updateActivityIntent.putExtra(的getString(R.string.keyUpdateInterval),间隔);
        bindService(updateActivityIntent,mConnection,Context.BIND_AUTO_CREATE);
        mIsBound = TRUE;
    }    无效doUnbindService(){
        如果(mIsBound){
            unbindService(mConnection);
            mIsBound = FALSE;
        }
    }    @覆盖
    保护无效的onDestroy(){
        super.onDestroy();
        doUnbindService();
    }
}


解决方案

您敬酒不显示,因为你不告诉它来。尝试:

 公共无效showNotification(){
    Toast.makeText(这一点,你好,10).show();
}

为您服务的问题,我认为你没有正确理解如何服务和放大器;活动一起工作。服务可以服务的独立运行,也可以拥有的生命周期相匹配的特定活动的服务。从code,目前尚不清楚你是以下这些车型。您的实施将导致服务定期唤醒,但,而你的活动正在运行。如果用户切换到另一个活动,您的服务将不再被唤醒。

如果你想有一个服务定期独立活动的清醒,那么你就需要在服务本身运行计时器事件。更妙的是使用闹钟唤醒你的服务:注册与AlarmManager报警,这将在未来的某个时刻触发一个Intent(或定期,如果你preFER),并从 IntentService <延长服务/ code>,覆盖 onHandleIntent()和必要的意图过滤器添加到清单您的服务项目。

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();
    }
}

解决方案

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.

这篇关于创建服务机器人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆