通过官网的一个例子来看Activity的分组管理



/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.android.supportv4;

import android.app.ListActivity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Support4Demos extends ListActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        Intent intent = getIntent();
        String path = intent.getStringExtra("com.example.android.apis.Path");
        
        if (path == null) {
            path = "";
        }

        setListAdapter(new SimpleAdapter(this, getData(path),
                android.R.layout.simple_list_item_1, new String[] { "title" },
                new int[] { android.R.id.text1 }));
        getListView().setTextFilterEnabled(true);
    }

    protected List<Map<String, Object>> getData(String prefix) {
        List<Map<String, Object>> myData = new ArrayList<Map<String, Object>>();

        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory("com.example.android.supportv4.SUPPORT4_SAMPLE_CODE");

        PackageManager pm = getPackageManager();
        List<ResolveInfo> list = pm.queryIntentActivities(mainIntent, 0);

        if (null == list)
            return myData;

        String[] prefixPath;
        String prefixWithSlash = prefix;
        
        if (prefix.equals("")) {
            prefixPath = null;
        } else {
            prefixPath = prefix.split("/");
            prefixWithSlash = prefix + "/";
        }
        
        int len = list.size();
        
        Map<String, Boolean> entries = new HashMap<String, Boolean>();

        for (int i = 0; i < len; i++) {
            ResolveInfo info = list.get(i);
            CharSequence labelSeq = info.loadLabel(pm);
            String label = labelSeq != null
                    ? labelSeq.toString()
                    : info.activityInfo.name;
            
            if (prefixWithSlash.length() == 0 || label.startsWith(prefixWithSlash)) {
                
                String[] labelPath = label.split("/");

                String nextLabel = prefixPath == null ? labelPath[0] : labelPath[prefixPath.length];

                if ((prefixPath != null ? prefixPath.length : 0) == labelPath.length - 1) {
                    addItem(myData, nextLabel, activityIntent(
                            info.activityInfo.applicationInfo.packageName,
                            info.activityInfo.name));
                } else {
                    if (entries.get(nextLabel) == null) {
                        addItem(myData, nextLabel, browseIntent(prefix.equals("") ? nextLabel : prefix + "/" + nextLabel));
                        entries.put(nextLabel, true);
                    }
                }
            }
        }

        Collections.sort(myData, sDisplayNameComparator);
        
        return myData;
    }

    private final static Comparator<Map<String, Object>> sDisplayNameComparator =
        new Comparator<Map<String, Object>>() {
        private final Collator   collator = Collator.getInstance();

        public int compare(Map<String, Object> map1, Map<String, Object> map2) {
            return collator.compare(map1.get("title"), map2.get("title"));
        }
    };

    protected Intent activityIntent(String pkg, String componentName) {
        Intent result = new Intent();
        result.setClassName(pkg, componentName);
        return result;
    }
    
    protected Intent browseIntent(String path) {
        Intent result = new Intent();
        result.setClass(this, Support4Demos.class);
        result.putExtra("com.example.android.apis.Path", path);
        return result;
    }

    protected void addItem(List<Map<String, Object>> data, String name, Intent intent) {
        Map<String, Object> temp = new HashMap<String, Object>();
        temp.put("title", name);
        temp.put("intent", intent);
        data.add(temp);
    }

    @Override
    @SuppressWarnings("unchecked")
    protected void onListItemClick(ListView l, View v, int position, long id) {
        Map<String, Object> map = (Map<String, Object>)l.getItemAtPosition(position);

        Intent intent = (Intent) map.get("intent");
        startActivity(intent);
    }
}

这里的关键在于下面这几行代码

        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory("com.example.android.supportv4.SUPPORT4_SAMPLE_CODE");

        PackageManager pm = getPackageManager();
        List<ResolveInfo> list = pm.queryIntentActivities(mainIntent, 0);


是把在清单文件AndroidManifest.xml注册category类别为com.example.android.supportv4.SUPPORT4_SAMPLE_CODE的Activity找出来,当然我们也可以自定义一些自己的类别

本例的清单文件如下:

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2007 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<!-- Declare the contents of this Android application.  The namespace
     attribute brings in the Android platform namespace, and the package
     supplies a unique name for the application.  When writing your
     own application, the package name must be changed from "com.example.*"
     to come from a domain that you own or have control over. -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.supportv4">

    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <uses-sdk android:minSdkVersion="17" android:targetSdkVersion="22" />

    <!-- The smallest screen this app works on is a phone.  The app will
         scale its UI to larger screens but doesn't make good use of them
         so allow the compatibility mode button to be shown (mostly because
         this is just convenient for testing). -->
    <supports-screens android:requiresSmallestWidthDp="320"
            android:compatibleWidthLimitDp="480" />

    <application android:label="@string/activity_sample_code"
            android:icon="@drawable/app_sample_code"
            android:hardwareAccelerated="true"
            android:supportsRtl="true">

        <activity android:name="Support4Demos">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".app.SendResult"
                android:theme="@style/ThemeDialogWhenLarge">
        </activity>
        
        <!-- Fragment Support Samples -->

        <activity android:name=".app.FragmentAlertDialogSupport"
                android:label="@string/fragment_alert_dialog_support">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <activity android:name=".app.FragmentArgumentsSupport"
                android:label="@string/fragment_arguments_support">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <activity android:name=".app.FragmentCustomAnimationSupport"
                android:label="@string/fragment_custom_animation_support">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <activity android:name=".app.FragmentHideShowSupport"
                android:label="@string/fragment_hide_show_support"
                android:windowSoftInputMode="stateUnchanged">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <activity android:name=".app.FragmentContextMenuSupport"
                android:label="@string/fragment_context_menu_support">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <activity android:name=".app.FragmentDialogSupport"
                android:label="@string/fragment_dialog_support">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <activity android:name=".app.FragmentDialogOrActivitySupport"
                android:label="@string/fragment_dialog_or_activity_support">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <activity android:name=".app.FragmentLayoutSupport"
                android:label="@string/fragment_layout_support">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <activity android:name=".app.FragmentListArraySupport"
                android:label="@string/fragment_list_array_support">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <activity android:name=".app.FragmentLayoutSupport$DetailsActivity" />

        <activity android:name=".app.FragmentMenuSupport"
                android:label="@string/fragment_menu_support">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <activity android:name=".app.FragmentNestingTabsSupport"
                android:label="@string/fragment_nesting_tabs_support">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>
        
        <activity android:name=".app.FragmentRetainInstanceSupport"
                android:label="@string/fragment_retain_instance_support">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <activity android:name=".app.FragmentReceiveResultSupport"
                android:label="@string/fragment_receive_result_support">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <activity android:name=".app.FragmentStackSupport"
                android:label="@string/fragment_stack_support">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <activity android:name=".app.FragmentTabs"
                android:label="@string/fragment_tabs">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <activity android:name=".app.FragmentTabsPager"
                android:label="@string/fragment_tabs_pager">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <activity android:name=".app.FragmentPagerSupport"
                android:label="@string/fragment_pager_support">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <activity android:name=".app.FragmentStatePagerSupport"
                android:label="@string/fragment_state_pager_support">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <activity android:name=".app.LoaderCursorSupport"
                android:label="@string/loader_cursor_support">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <activity android:name=".app.LoaderRetainedSupport"
                android:label="@string/loader_retained_support">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>
        
        <activity android:name=".app.LoaderCustomSupport"
                android:label="@string/loader_custom_support">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <activity android:name=".app.LoaderThrottleSupport"
                android:label="@string/loader_throttle_support">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>
        <provider android:name=".app.LoaderThrottleSupport$SimpleProvider"
                  android:authorities="com.example.android.apis.supportv4.app.LoaderThrottle" />

        <activity android:name=".content.LocalServiceBroadcaster"
                android:label="@string/local_service_broadcaster">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>
        <service android:name=".content.LocalServiceBroadcaster$LocalService"
                android:stopWithTask="true" />

        <activity android:name=".content.SimpleWakefulController"
                  android:label="@string/simple_wakeful_controller">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <receiver android:name=".content.SimpleWakefulReceiver" />
        <service android:name=".content.SimpleWakefulService" />

        <activity android:name=".accessibility.AccessibilityManagerSupportActivity"
                android:label="@string/accessibility_manager_title">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <activity android:name=".accessibility.AccessibilityDelegateSupportActivity"
                android:label="@string/accessibility_delegate_title">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <activity android:name=".app.SharingSupport"
                  android:label="@string/sharing_support_title">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <activity android:name=".app.SharingReceiverSupport"
                  android:label="@string/sharing_receiver_title">
            <intent-filter>
                <action android:name="android.intent.action.SEND" />
                <action android:name="android.intent.action.SEND_MULTIPLE" />
                <data android:mimeType="text/plain" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

        <activity android:name=".text.BidiFormatterSupport"
                  android:label="@string/bidiformatter_support_title">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <activity android:name=".widget.DrawerLayoutActivity"
                  android:label="@string/drawer_layout_support">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <activity android:name=".widget.SwipeRefreshLayoutActivity"
                  android:label="@string/swipe"
                  android:theme="@style/ThemeHoloLight">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <activity android:name=".widget.ContentLoadingProgressBarActivity"
                  android:label="@string/content_loading_progress_bar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <activity android:name=".widget.SlidingPaneLayoutActivity"
                  android:label="@string/sliding_pane_layout_support">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <activity android:name=".widget.ExploreByTouchHelperActivity"
                  android:label="@string/explore_by_touch_helper_support">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <provider android:authorities="com.example.supportv4.content.sharingsupportprovider"
                  android:name=".content.SharingSupportProvider" />

        <!-- FileProvider Example -->

        <activity android:name=".content.FileProviderExample"
                android:label="@string/file_provider_example">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <activity android:name=".widget.NestedScrollActivity"
                  android:label="@string/nested_scroll">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <activity android:name=".graphics.RoundedBitmapDrawableActivity"
            android:label="Graphics/RoundedBitmapDrawable">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

        <activity android:name=".graphics.DrawableCompatActivity"
                  android:label="Graphics/DrawableCompat">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>


        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.example.android.supportv4.my_files"
            android:grantUriPermissions="true"
            android:exported="false">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/my_paths" />
        </provider>


        <activity android:name=".media.TransportControllerActivity"
                android:label="@string/sample_transport_controller_activity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="com.example.android.supportv4.SUPPORT4_SAMPLE_CODE" />
            </intent-filter>
        </activity>

    </application>
</manifest>




将Android activity转换为service,需要将activity中的UI逻辑移动到service中,并且需要在service中创建一个独立的线程来处理逻辑。下面是一个简单的示例: 1. 创建一个新的service类,并继承Service类。 ```java public class MyService extends Service { @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { // 在此处添加逻辑代码 return super.onStartCommand(intent, flags, startId); } } ``` 2. 在MyService类中添加需要运行的逻辑代码,例如在后台播放音乐。 ```java public class MyService extends Service { private MediaPlayer mMediaPlayer; @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { mMediaPlayer = MediaPlayer.create(this, R.raw.music); mMediaPlayer.setLooping(true); mMediaPlayer.start(); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); mMediaPlayer.stop(); } } ``` 3. 在AndroidManifest.xml文件中声明服务。 ```xml <service android:name=".MyService" android:enabled="true" android:exported="false" /> ``` 4. 在Activity中启动服务。 ```java Intent intent = new Intent(this, MyService.class); startService(intent); ``` 这样,当Activity启动时,服务就会在后台运行,播放音乐。如果Activity被销毁,服务仍将在后台运行,直到被停止或销毁。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值