public class MainActivity extends Activity {
private Button btn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn=(Button)findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this,CloseService.class);
startService(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
public class CloseService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent newIntent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);//之所以能够在源码中查看,但是调用的时候不显示,是因为这个不对上层开放
newIntent.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(newIntent);
return super.onStartCommand(intent, flags, startId);
}
}
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="feng.f7_30.activity"
android:versionCode="1"
android:versionName="1.0"
android:sharedUserId="android.uid.system">
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.SHUTDOWN"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="CloseService"></service>
</application>
</manifest>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="@string/btn_name" />
</RelativeLayout>
添加一条
<resources>
<string name="btn_name">close</string>
</resources>