Muh*_*man 2 android android-intent
当用户打开智能手机然后让它在后台运行时,我需要启动我的应用程序.有什么先决条件?我怎样才能成功呢?谢谢
首先,Activity不能也不应该在后台运行.对于Android中的后台操作,您应该使用服务,但您可以通过下面的代码隐藏活动.
第1步:在AndroidManifest.xml中设置权限
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Run Code Online (Sandbox Code Playgroud)
Step2:在接收器中添加这是intent过滤器,
<receiver android:name=".BootReciever">
<intent-filter >
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
Run Code Online (Sandbox Code Playgroud)
Step3:现在您可以从Receiver类的onReceive方法启动应用程序的第一个活动.
public class BootReciever extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(context, MainActivity.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
myIntent.addCategory(Intent.CATEGORY_HOME);
context.startActivity(myIntent);
}
}
Run Code Online (Sandbox Code Playgroud)
和你的活动Oncreate把这个
moveTaskToBack(true);
Run Code Online (Sandbox Code Playgroud)
编辑:服务使用此
public class BootReciever extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, service.class);
context.startService(myIntent);
}
}
public class service 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)
{
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
}
}
Run Code Online (Sandbox Code Playgroud)
并将此行添加到Androidmanifeist.xml
<service android:enabled="true" android:name=".service" />
Run Code Online (Sandbox Code Playgroud)
有关详情,请参阅此处
http://blog.vogella.com/2011/12/11/automatically-starting-services-in-android-after-booting/
http://www.vogella.com/articles/AndroidServices/article.html
| 归档时间: |
|
| 查看次数: |
502 次 |
| 最近记录: |