您的位置:首页 > 移动开发

在一个Android application 调用另一个 application 里的 Activity 和 Service

2011-11-15 19:16 429 查看
Android application 和普通的应用程序有些差别,他是由四大组件(compoment)组成的,即Activity,Service,ContentProvider ,和BroadcastReceiver。 本文介绍从一个application 调用其它application 里的 Activity 和 Service。

要启动别的app里的 Activity 和 Service,主要生成两个 intent 实例,分别把实例的action 设置成和另一个 application 里 AndroidManifest.xml定义的 intent-filter 里的Action一样:Intent::setAction(Action name)。

启动另一个app里的Activity:

Intent testActivityIntent = new Intent();

testActivityIntent.setAction("com.android.1234F");

startActivity(testActivityIntent);

com.android.1234F就是在另一个App里AndroidManifest.xml中对相应Activity定义的Action,请看

<activity android:name=".SecondAndroid"

android:label="@string/app_name">

<intent-filter>

<action android:name="com.android.1234F" />

<category android:name="android.intent.category.DEFAULT" />

</intent-filter>

</activity>

接着,启动另一个app里的Service:

testActivityIntent = null ;

testActivityIntent = new Intent();

testActivityIntent.setAction("android.intent.action.START_PCM_PLAY_SERVICE") ;

stopService(testActivityIntent);

startService(testActivityIntent);

android.intent.action.START_PCM_PLAY_SERVICE
就是另一个app里AndroidManifest.xml中对相应Service定义的Action,请看

<service android:enabled="true"

android:exported="true"

android:name=".ServiceInSecondAndroid"

android:label="@string/app_name">

<intent-filter>

<action android:name="android.intent.action.START_PCM_PLAY_SERVICE"/>

<category android:name="android.intent.category.DEFAULT"/>

</intent-filter>

</service>

另一个 app里的 Activity就照正常的规则来书,这里展出了一个 Service 播放pcm的例子:

public class ServiceInSecondAndroid extends Service {

private AudioTrack at = null ;

@Override

public void onCreate()

{

super.onCreate();

Log.v("tiantian", "thirdAndroid.onCreate()");

if( at != null )

{

at.release() ;

}

at = new AudioTrack( AudioManager.STREAM_MUSIC , 44100 , AudioFormat.CHANNEL_OUT_STEREO ,AudioFormat.ENCODING_PCM_16BIT , 44100*4*25, AudioTrack.MODE_STATIC ) ;

if( at!= null )

Log.v("tiantian", "AudioTrack success create");

FileInputStream f1 ;

try

{

f1=new FileInputStream("/sdcard/gaosu_44100_stereo.pcm");

}

catch ( IOException e )

{

Log.v("tiantian", "gaosu_44100_stereo.pcm not exist");

return;

}

byte[] payload = new byte[44100*4*25] ;

Log.v("tiantian", "payload ok");

int len ;

try

{

len = f1.read(payload, 0, 44100*4*25);

}

catch (IOException e )

{

Log.v("tiantian", "fail to read gaosu_44100_stereo.pcm");

return ;

}

try

{

f1.close();

}

catch (IOException e )

{

Log.v("tiantian", "close error");

return;

}

at.write(payload,0,len);

at.play();

return ;

}

public IBinder onBind(Intent intent) {

Log.v("tiantian", "onBind");

return null;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐