在Service中启动Activity
1、创建主Activity,MainActivity。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(MainActivity.this, MyService.class);
startService(intent);
}
}
复制代码
2、创建在Service中启动的Activity,Main2Activity。
public class Main2Activity extends AppCompatActivity {
private static final String TAG = "Main2Activity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Log.d(TAG, "onCreate");
}
}复制代码
3、创建Service,命名为MyService。需要特别注意的是在Service启动Activity与普通启动Activity不同,需要设置Intent.FLAG_ACTIVITY_NEW_TASK 才可以正常启动。实例中增加到5秒延迟后启动Main2Activity。
public class MyService extends Service {
private static final String TAG = "MyService";
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
super.onCreate();
Log.e(TAG, "--------->onCreate: ");
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(MyService.this, Main2Activity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
startActivity(intent);
}
}, 3 * 1000);
}
@Override
public void onDestroy() {
super.onDestroy();
}
}复制代码
4、在AndroidManifest中声明MyService。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="realmusic.ace.com.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyService"
android:enabled="true"
android:exported="true" />
<activity
android:name=".Main2Activity"
android:label="@string/title_activity_main2"
android:theme="@style/AppTheme.NoActionBar"></activity>
</application>
</manifest>复制代码
5、在MyService中启动Main2Activity如下图:
在此流程就可以完成在Service中启动Activity的功能。