English 中文(简体)
1. 建立海底服务
原标题:Creating an android service
  • 时间:2011-10-19 14:48:44
  •  标签:
  • android

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();
    }
}
最佳回答

你的传闻并不是因为你没有告诉你。 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.

如果你想要定期听从活动,那么,你需要亲自管理你的时间。 • 更好地利用阿拉尔来接你的工作: 注册号Alarm with AlarmManager, which will fire an Intent at a future point (or regular between, if You favor),并将您的服务范围从Intentservice上延伸,上列onHandleIntent(),并在明文中添加必要的Intent Filter到您的服务条目中。

问题回答

暂无回答




相关问题
Android - ListView fling gesture triggers context menu

I m relatively new to Android development. I m developing an app with a ListView. I ve followed the info in #1338475 and have my app recognizing the fling gesture, but after the gesture is complete, ...

AsyncTask and error handling on Android

I m converting my code from using Handler to AsyncTask. The latter is great at what it does - asynchronous updates and handling of results in the main UI thread. What s unclear to me is how to handle ...

Android intent filter for a particular file extension?

I want to be able to download a file with a particular extension from the net, and have it passed to my application to deal with it, but I haven t been able to figure out the intent filter. The ...

Android & Web: What is the equivalent style for the web?

I am quite impressed by the workflow I follow when developing Android applications: Define a layout in an xml file and then write all the code in a code-behind style. Is there an equivalent style for ...

TiledLayer equivalent in Android [duplicate]

To draw landscapes, backgrounds with patterns etc, we used TiledLayer in J2ME. Is there an android counterpart for that. Does android provide an option to set such tiled patterns in the layout XML?

Using Repo with Msysgit

When following the Android Open Source Project instructions on installing repo for use with Git, after running the repo init command, I run into this error: /c/Users/Andrew Rabon/bin/repo: line ...

Android "single top" launch mode and onNewIntent method

I read in the Android documentation that by setting my Activity s launchMode property to singleTop OR by adding the FLAG_ACTIVITY_SINGLE_TOP flag to my Intent, that calling startActivity(intent) would ...

From Web Development to Android Development

I have pretty good skills in PHP , Mysql and Javascript for a junior developer. If I wanted to try my hand as Android Development do you think I might find it tough ? Also what new languages would I ...

热门标签