android点击按钮创建桌面快捷方式java
要在Android中点击按钮创建桌面快捷方式,可以使用以下代码:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn_create_shortcut).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
createShortcut();
}
});
}
private void createShortcut() {
Intent shortcutIntent = new Intent(getApplicationContext(), MainActivity.class);
shortcutIntent.setAction(Intent.ACTION_MAIN);
Intent addIntent = new Intent();
addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "My Shortcut");
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.mipmap.ic_launcher));
addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
getApplicationContext().sendBroadcast(addIntent);
}
}
在XML布局文件中,添加一个按钮:
<Button
android:id="@+id/btn_create_shortcut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Create Shortcut" />
上述代码中,当点击按钮时,会调用createShortcut()方法,该方法创建一个Intent对象,并设置快捷方式的名称、图标等信息。最后通过发送广播来安装快捷方式
原文地址: https://www.cveoy.top/t/topic/h07q 著作权归作者所有。请勿转载和采集!