来自其他应用

时间:2016-04-20 08:19:02

标签: android android-service aidl android-binder

在app中,提供服务我有两个AIDL文件:

interface ICountTest {
    oneway void count(in INotifierTest test);
}

interface INotifierTest {
   oneway void notify(int count);
}

基本上我想在Integer.MAX_VALUE循环中计算到for,然后将此值提供给通知程序,以便他可以在其他应用程序中以可视方式显示它

为此,我有一项服务

的xml:

<service android:name=".service.TestService"
    android:process=".remote"
    android:exported="true">
    <intent-filter>
        <action android:name="TestService.START_SERVICE" />
    </intent-filter>
</service>

我添加了意图过滤器,尝试从不同的方法启动它

的java:

public class TestService extends Service{

   private ICountTest.Stub mBinder;

   @Override
   public void onCreate() {
       super.onCreate();

       mBinder = new ICountTest.Stub() {
           @Override
           public void count(INotifierTest notifier) throws   RemoteException {
               int k = 0;
               for(int i = 0; i < Integer.MAX_VALUE; i++) {
                   k = i;
               }
               notifier.notify(k);
           }
       };
   }

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

在我的MainActivity课程中,我已覆盖notify方法:

private INotifierTest.Stub mINotifierTest = new INotifierTest.Stub() {
    @Override
    public void notify(int count) throws RemoteException {
       final String result = String.valueOf(count);
       Log.d("aidl_test", result);
       MainActivity.this.runOnUiThread(new Runnable() {
           @Override
           public void run() {
               Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
           }
       });
    }
};

我在count中调用onServiceConnected方法:

 private ServiceConnection mServiceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        mCountTest = ICountTest.Stub.asInterface(iBinder);
        try {
            Log.d("aidl_test", Thread.currentThread().getName());
            mCountTest.count(mINotifierTest);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {

    }
};

但是当我需要从另一个应用程序运行它时,例如,像这样:

Intent i = new Intent();
i.setComponent(new ComponentName("com.xxx.xxx", "com.xxx.xxxx.service.TestService"));
getActivity().bindService(i, mServiceConntection, Context.BIND_AUTO_CREATE);

我需要提供我自己的ServiceConnection类,它将覆盖所需的功能,我在其中获得了绑定,但基本上我只有所需接口的类名,因此,我无法做任何事情它。 我也尝试过startService,但从逻辑上讲,它不起作用。

我认为我做错了什么,请帮助我理解。

我的目标是:在另一个应用中使用count个关键字运行TestService方法,并查看ToastLog的结果。

编辑:我已经开始使用与第一个应用程序相同的包和代码创建相同的AIDL文件,并使用它们,但它不起作用。

编辑:哇,这是我的错,我只是覆盖了INotifierTest.Stub,而只是INotifierTest感谢大家的帮助

0 个答案:

没有答案
相关问题