开发者

Toast in a self running service

开发者 https://www.devze.com 2023-04-02 12:27 出处:网络
I have an android activity which runs a remote service and then quits. The service itself, polls on a device node, and checks for changes,

I have an android activity which runs a remote service and then quits. The service itself, polls on a device node, and checks for changes, I want to use toast to alert the user, but I didn't mange to get it to work. the Toast is not showing, and after a while, Android shouts that my app is not responding. BTW, I don't want to start the activity again a开发者_如何转开发nd display the toast from there, I just want it to pop on the current screen shown to the user.

Here is the service code:

public class MainService extends Service {

    // Native methods
    public native static int GetWiegandCode();
    public native static void openWiegand();
    public native static void closeWiegand();

    static int code = 0;

    // Other
    private static final String TAG = MainService.class.getSimpleName();
    private Handler handler;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public void run() {
        Handler h;
        while (true) {
            code = GetWiegandCode();
            if (code > 0) {
                h = new Handler(this.getMainLooper());
                h.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getBaseContext(),
                            "ID " + Integer.toString(code) +
                            "Just entered", Toast.LENGTH_LONG).show();
                    }
                });
            }
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        openWiegand();
        Log.i(TAG, "Service Starting");
        this.run();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        closeWiegand();
        Log.i(TAG, "Service destroying");
    }

    static {
        System.loadLibrary("wiegand-toast");
    }
}


You can't call a Toast message from the Service. You can't do anything with the UI except from the UI thread. You're going to need to research one of the many ways to communicate with your UI thread from your service - BroadcastReciever, Messenger, AIDL, etc.

For what you're trying to do, you probably don't need to go as far as the AIDL route. Check out this example the Messenger implementation and then check out the complete example from the sdk-samples:

http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/MessengerService.html

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号