【发布时间】:2017-11-09 17:36:04
【问题描述】:
我需要使用 Service 启动我的 Android 应用程序,然后从该 Service 启动 Activity。首先,我通过引用 Stack Overflow 创建了 Sample Application。我创建了 StartReceiver 类来启动 Service。
public class StartReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent arg1)
{
Intent intent = new Intent(context,MyService.class);
context.startService(intent);
Log.i("Autostart", "started");
}
}
这是我的服务类。
public class MyService extends Service
{
private static final String TAG = "MyService";
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
@Override
public void onStart(Intent intent, int startid)
{
Intent intents = new Intent(getBaseContext(),MainActivity.class);
intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intents);
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
}
}
这是我的Activity课程。
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(getBaseContext(), "Hello........", Toast.LENGTH_LONG).show();
}
}
这是我的 AndroidManifest 文件。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.onbitlabs.runwithoutactivity" android:versionCode="1" android:versionName="1.0"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<application android:icon="@mipmap/ic_launcher" android:label="@string/app_name">
<receiver android:name=".StartReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<activity android:name=".MainActivity"></activity>
<service android:enabled="true" android:name=".MyService" />
</application>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
</manifest>
当我运行应用程序时,Android Studio 给出 Error running app: Default Activity not found。 我该如何解决这个错误?
【问题讨论】:
-
尝试文件 -> 使缓存无效/重新启动
-
我试过了但是没有解决这个错误
标签: android android-activity android-service