在android中启动手机启动活动

时间:2012-02-12 07:06:25

标签: android

我正在尝试启动手机启动活动,但整个程序没有运行程序中没有错误,请看我的编码(或http://pastebin.com/BKaE4AaU):

autostart.java

import android.content.BroadcastReceiver;  
import android.content.Context;  
import android.content.Intent;  
import android.content.SharedPreferences;  
import android.preference.PreferenceManager;  
import android.util.Log;


public class autostart extends BroadcastReceiver 
{
    public void onReceive(Context arg0, Intent arg1) 
    {
        Intent intent = new Intent(arg0,service.class);
        arg0.startService(intent);
        Log.i("Autostart", "started");
    }
}

service.java

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

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)
    {
        Intent intents = new Intent(getBaseContext(),hello.class);
        intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intents);
        Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onStart");
    }
}

hello.java

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

public class hello extends Activity 
{   
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Toast.makeText(getBaseContext(), "Hello........", Toast.LENGTH_LONG).show();
    }
}

manifest.java如下

         

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <receiver  android:name=".autostart"
              android:label="@string/app_name">
        <intent-filter>
              <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>

             

2 个答案:

答案 0 :(得分:5)

您的XML应存储在名为AndroidManifest.xml的文件中,而不是manifest.java。

您的代码未运行的另一个原因可能是您的应用程序安装在外部存储(SD卡)上。在挂载外部存储之前,BOOT_COMPLETE将发送到应用程序。因此,如果应用程序安装到外部存储器,它将不会收到BOOT_COMPLETE广播消息。

如果不是问题,则已经有very good description of how to get boot completed receivers working on Android

答案 1 :(得分:0)

因此,当设备启动时,您希望自己的活动弹出并在没有用户操作的情况下向用户显示?

请不要这样做 - 这是一个非常糟糕的用户体验。你知道任何现有的应用程序吗?我不知道。我个人不会使用这样的应用程序。

如果您需要通知用户某些内容,请使用系统首选方式 - notifications