Search in sources :

Example 51 with ServiceConnection

use of android.content.ServiceConnection in project Small by wequick.

the class MainFragment method onCreateView.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_main, container, false);
    // 启动一个带自定义转场动画的Activity
    // 需要用户在宿主提前占坑的地方:
    //  1. 转场动画相关anim资源
    Button button = (Button) rootView.findViewById(R.id.start_transition_activity_button);
    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainFragment.this.getContext(), TransitionActivity.class);
            startActivity(intent);
        }
    });
    /**
         * 以下代码测试:
         * 1. 成功发送通知, 在通知栏显示通知图标与信息
         * 2. 点击通知, 成功跳转指定Activity
         * 3. 在该Activity返回, 成功返回上一个界面
         * @see https://developer.android.com/training/notify-user/navigation.html#ExtendedNotification
         */
    // 方案一: 使用PendingIntent.getActivity构造PendingIntent, 发起一个通知。
    // 额外操作:
    //  1. 在 `stub` 模块放置 `smallIcon` 图片资源
    //  2. 使用 `Small.wrapIntent(intent)` 暗度插件意图
    button = (Button) rootView.findViewById(R.id.send_notification_special_button);
    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Context context = getContext();
            Intent onclickIntent = new Intent(context, NotifyResultActivity.class);
            onclickIntent.putExtra("notification_id", MY_NOTIFICATION_ID);
            //!< 增加这行代码
            Small.wrapIntent(onclickIntent);
            PendingIntent pi = PendingIntent.getActivity(context, 0, onclickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            Bitmap largeIcon = BitmapFactory.decodeResource(getContext().getResources(), // large icon的资源可以在插件里
            R.drawable.ic_large_notification);
            NotificationCompat.Builder nb = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.ic_notification).setLargeIcon(largeIcon).setContentTitle("Small").setContentText("Click to start pending intent with PendingIntent.getActivity").setContentIntent(pi);
            NotificationManagerCompat nm = NotificationManagerCompat.from(context);
            nm.notify(MY_NOTIFICATION_ID, nb.build());
        }
    });
    // 方案二: 使用TaskStackBuilder构造PendingIntent, 发起一个通知
    // 额外操作:
    //   1. 在 `stub` 模块放置 `smallIcon` 图片资源
    //
    // 这里不需要手动修改意图, 因为 `Small` 对 `TaskStackBuilder` 进行了Hook, 自动完成wrapIntent
    button = (Button) rootView.findViewById(R.id.send_notification_taskstack_button);
    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Context context = getContext();
            Intent onclickIntent = new Intent(context, NotifyResultActivity.class);
            onclickIntent.putExtra("notification_id", MY_NOTIFICATION_ID);
            PendingIntent pi = TaskStackBuilder.create(context).addNextIntent(getActivity().getIntent()).addNextIntent(onclickIntent).getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
            Bitmap largeIcon = BitmapFactory.decodeResource(getContext().getResources(), // large icon的资源可以在插件里
            R.drawable.ic_large_notification);
            NotificationCompat.Builder nb = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.ic_notification).setLargeIcon(largeIcon).setContentTitle("Small").setContentText("Click to start pending intent with TaskStackBuilder").setContentIntent(pi);
            NotificationManagerCompat nm = NotificationManagerCompat.from(context);
            nm.notify(MY_NOTIFICATION_ID, nb.build());
        }
    });
    // 本地服务
    button = (Button) rootView.findViewById(R.id.start_service_button);
    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getContext(), MyLocalService.class);
            getContext().startService(intent);
        }
    });
    button = (Button) rootView.findViewById(R.id.stop_service_button);
    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getContext(), MyLocalService.class);
            getContext().stopService(intent);
        }
    });
    // 远程服务
    mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };
    button = (Button) rootView.findViewById(R.id.bind_remote_service_button);
    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getContext(), MyRemoteService.class);
            getContext().bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
        }
    });
    button = (Button) rootView.findViewById(R.id.unbind_remote_service_button);
    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            getContext().unbindService(mServiceConnection);
        }
    });
    // 广播
    button = (Button) rootView.findViewById(R.id.send_broadcast_button);
    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setAction("net.wequick.example.small.MyAction");
            getContext().sendBroadcast(intent);
        }
    });
    button = (Button) rootView.findViewById(R.id.get_content_button);
    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            ContentResolver resolver = getContext().getContentResolver();
            Uri uri = Uri.parse("content://net.wequick.example.small/test");
            // Insert
            ContentValues values = new ContentValues();
            values.put("name", "T" + System.currentTimeMillis());
            resolver.insert(uri, values);
            // Query
            Cursor cursor = resolver.query(uri, null, null, null, "id desc");
            if (cursor == null) {
                return;
            }
            if (cursor.moveToFirst()) {
                String msg = "name in top record is: " + cursor.getString(1);
                Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
            }
        }
    });
    button = (Button) rootView.findViewById(R.id.start_remote_activity_button);
    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getContext(), MyRemoteActivity.class);
            startActivity(intent);
        }
    });
    return rootView;
}
Also used : Context(android.content.Context) ContentValues(android.content.ContentValues) ServiceConnection(android.content.ServiceConnection) TaskStackBuilder(android.support.v4.app.TaskStackBuilder) NotificationManagerCompat(android.support.v4.app.NotificationManagerCompat) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) Cursor(android.database.Cursor) View(android.view.View) Uri(android.net.Uri) ContentResolver(android.content.ContentResolver) Bitmap(android.graphics.Bitmap) IBinder(android.os.IBinder) Button(android.widget.Button) ComponentName(android.content.ComponentName) PendingIntent(android.app.PendingIntent)

Example 52 with ServiceConnection

use of android.content.ServiceConnection in project android_frameworks_base by crdroidandroid.

the class MediaBrowser method connect.

/**
     * Connects to the media browse service.
     * <p>
     * The connection callback specified in the constructor will be invoked
     * when the connection completes or fails.
     * </p>
     */
public void connect() {
    if (mState != CONNECT_STATE_DISCONNECTED) {
        throw new IllegalStateException("connect() called while not disconnected (state=" + getStateLabel(mState) + ")");
    }
    // TODO: remove this extra check.
    if (DBG) {
        if (mServiceConnection != null) {
            throw new RuntimeException("mServiceConnection should be null. Instead it is " + mServiceConnection);
        }
    }
    if (mServiceBinder != null) {
        throw new RuntimeException("mServiceBinder should be null. Instead it is " + mServiceBinder);
    }
    if (mServiceCallbacks != null) {
        throw new RuntimeException("mServiceCallbacks should be null. Instead it is " + mServiceCallbacks);
    }
    mState = CONNECT_STATE_CONNECTING;
    final Intent intent = new Intent(MediaBrowserService.SERVICE_INTERFACE);
    intent.setComponent(mServiceComponent);
    final ServiceConnection thisConnection = mServiceConnection = new MediaServiceConnection();
    boolean bound = false;
    try {
        bound = mContext.bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
    } catch (Exception ex) {
        Log.e(TAG, "Failed binding to service " + mServiceComponent);
    }
    if (!bound) {
        // Tell them that it didn't work. We are already on the main thread,
        // but we don't want to do callbacks inside of connect(). So post it,
        // and then check that we are on the same ServiceConnection. We know
        // we won't also get an onServiceConnected or onServiceDisconnected,
        // so we won't be doing double callbacks.
        mHandler.post(new Runnable() {

            @Override
            public void run() {
                // Ensure that nobody else came in or tried to connect again.
                if (thisConnection == mServiceConnection) {
                    forceCloseConnection();
                    mCallback.onConnectionFailed();
                }
            }
        });
    }
    if (DBG) {
        Log.d(TAG, "connect...");
        dump();
    }
}
Also used : ServiceConnection(android.content.ServiceConnection) Intent(android.content.Intent) RemoteException(android.os.RemoteException)

Example 53 with ServiceConnection

use of android.content.ServiceConnection in project android_frameworks_base by crdroidandroid.

the class LoadedApk method forgetServiceDispatcher.

public final IServiceConnection forgetServiceDispatcher(Context context, ServiceConnection c) {
    synchronized (mServices) {
        ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher> map = mServices.get(context);
        LoadedApk.ServiceDispatcher sd = null;
        if (map != null) {
            sd = map.get(c);
            if (sd != null) {
                map.remove(c);
                sd.doForget();
                if (map.size() == 0) {
                    mServices.remove(context);
                }
                if ((sd.getFlags() & Context.BIND_DEBUG_UNBIND) != 0) {
                    ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher> holder = mUnboundServices.get(context);
                    if (holder == null) {
                        holder = new ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher>();
                        mUnboundServices.put(context, holder);
                    }
                    RuntimeException ex = new IllegalArgumentException("Originally unbound here:");
                    ex.fillInStackTrace();
                    sd.setUnbindLocation(ex);
                    holder.put(c, sd);
                }
                return sd.getIServiceConnection();
            }
        }
        ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher> holder = mUnboundServices.get(context);
        if (holder != null) {
            sd = holder.get(c);
            if (sd != null) {
                RuntimeException ex = sd.getUnbindLocation();
                throw new IllegalArgumentException("Unbinding Service " + c + " that was already unbound", ex);
            }
        }
        if (context == null) {
            throw new IllegalStateException("Unbinding Service " + c + " from Context that is no longer in use: " + context);
        } else {
            throw new IllegalArgumentException("Service not registered: " + c);
        }
    }
}
Also used : ServiceConnection(android.content.ServiceConnection) AndroidRuntimeException(android.util.AndroidRuntimeException)

Example 54 with ServiceConnection

use of android.content.ServiceConnection in project android_frameworks_base by crdroidandroid.

the class KeyChain method bindAsUser.

/**
     * @hide
     */
@WorkerThread
public static KeyChainConnection bindAsUser(@NonNull Context context, UserHandle user) throws InterruptedException {
    if (context == null) {
        throw new NullPointerException("context == null");
    }
    ensureNotOnMainThread(context);
    final BlockingQueue<IKeyChainService> q = new LinkedBlockingQueue<IKeyChainService>(1);
    ServiceConnection keyChainServiceConnection = new ServiceConnection() {

        volatile boolean mConnectedAtLeastOnce = false;

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            if (!mConnectedAtLeastOnce) {
                mConnectedAtLeastOnce = true;
                try {
                    q.put(IKeyChainService.Stub.asInterface(service));
                } catch (InterruptedException e) {
                // will never happen, since the queue starts with one available slot
                }
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };
    Intent intent = new Intent(IKeyChainService.class.getName());
    ComponentName comp = intent.resolveSystemService(context.getPackageManager(), 0);
    intent.setComponent(comp);
    if (comp == null || !context.bindServiceAsUser(intent, keyChainServiceConnection, Context.BIND_AUTO_CREATE, user)) {
        throw new AssertionError("could not bind to KeyChainService");
    }
    return new KeyChainConnection(context, keyChainServiceConnection, q.take());
}
Also used : ServiceConnection(android.content.ServiceConnection) IBinder(android.os.IBinder) ComponentName(android.content.ComponentName) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) WorkerThread(android.annotation.WorkerThread)

Example 55 with ServiceConnection

use of android.content.ServiceConnection in project android_frameworks_base by crdroidandroid.

the class AppWidgetServiceImpl method handleNotifyAppWidgetViewDataChanged.

private void handleNotifyAppWidgetViewDataChanged(Host host, IAppWidgetHost callbacks, int appWidgetId, int viewId, long requestId) {
    try {
        callbacks.viewDataChanged(appWidgetId, viewId);
        host.lastWidgetUpdateRequestId = requestId;
    } catch (RemoteException re) {
        // It failed; remove the callback. No need to prune because
        // we know that this host is still referenced by this instance.
        callbacks = null;
    }
    // RemoteViewsFactory.onDataSetChanged() directly
    synchronized (mLock) {
        if (callbacks == null) {
            host.callbacks = null;
            Set<Pair<Integer, FilterComparison>> keys = mRemoteViewsServicesAppWidgets.keySet();
            for (Pair<Integer, FilterComparison> key : keys) {
                if (mRemoteViewsServicesAppWidgets.get(key).contains(appWidgetId)) {
                    final ServiceConnection connection = new ServiceConnection() {

                        @Override
                        public void onServiceConnected(ComponentName name, IBinder service) {
                            IRemoteViewsFactory cb = IRemoteViewsFactory.Stub.asInterface(service);
                            try {
                                cb.onDataSetChangedAsync();
                            } catch (RemoteException e) {
                                Slog.e(TAG, "Error calling onDataSetChangedAsync()", e);
                            }
                            mContext.unbindService(this);
                        }

                        @Override
                        public void onServiceDisconnected(android.content.ComponentName name) {
                        // Do nothing
                        }
                    };
                    final int userId = UserHandle.getUserId(key.first);
                    Intent intent = key.second.getIntent();
                    // Bind to the service and call onDataSetChanged()
                    bindService(intent, connection, new UserHandle(userId));
                }
            }
        }
    }
}
Also used : ServiceConnection(android.content.ServiceConnection) PendingIntent(android.app.PendingIntent) Intent(android.content.Intent) Point(android.graphics.Point) IBinder(android.os.IBinder) UserHandle(android.os.UserHandle) IRemoteViewsFactory(com.android.internal.widget.IRemoteViewsFactory) FilterComparison(android.content.Intent.FilterComparison) ComponentName(android.content.ComponentName) RemoteException(android.os.RemoteException) Pair(android.util.Pair)

Aggregations

ServiceConnection (android.content.ServiceConnection)122 ComponentName (android.content.ComponentName)95 Intent (android.content.Intent)95 IBinder (android.os.IBinder)94 RemoteException (android.os.RemoteException)75 PendingIntent (android.app.PendingIntent)46 UserHandle (android.os.UserHandle)23 Handler (android.os.Handler)20 Message (android.os.Message)19 Messenger (android.os.Messenger)19 IRemoteViewsFactory (com.android.internal.widget.IRemoteViewsFactory)12 IInterface (android.os.IInterface)9 ResolveInfo (android.content.pm.ResolveInfo)8 IntentFilter (android.content.IntentFilter)7 Point (android.graphics.Point)7 AndroidRuntimeException (android.util.AndroidRuntimeException)7 LinkedBlockingQueue (java.util.concurrent.LinkedBlockingQueue)7 Test (org.junit.Test)7 FilterComparison (android.content.Intent.FilterComparison)6 ReceiverCallNotAllowedException (android.content.ReceiverCallNotAllowedException)6